From 3588dc2502bf11a9feafef7c11a7de17dc90c813 Mon Sep 17 00:00:00 2001 From: gshost1 Date: Sun, 8 Nov 2026 05:19:54 -0800 Subject: [PATCH 1/5] fix(ffi): let a log callback call back into the library A host log callback runs inside the tracing event delivery of the call that logged. When it called another ad_* function, that call installed its own scoped dispatcher while the outer delivery still borrowed tracing's per-thread state, so tracing panicked ("RefCell already borrowed") and the nested call returned AD_RESULT_ERR_INTERNAL after printing a panic. A call made from inside the callback now runs without installing a dispatcher. Its own events are dropped rather than delivered, which the callback could not have received anyway because delivery is suppressed while it runs. --- .../docs/ffi/ownership-and-threading.mdx | 2 +- crates/ffi/include/agent_desktop.h | 3 + crates/ffi/src/log_callback.rs | 19 ++- .../ffi/src/log_callback_reentrancy_tests.rs | 118 ++++++++++++++++++ .../agent-desktop-ffi/references/threading.md | 3 + 5 files changed, 141 insertions(+), 4 deletions(-) create mode 100644 crates/ffi/src/log_callback_reentrancy_tests.rs diff --git a/apps/docs/content/docs/ffi/ownership-and-threading.mdx b/apps/docs/content/docs/ffi/ownership-and-threading.mdx index dc8e077897..b47eb58bd4 100644 --- a/apps/docs/content/docs/ffi/ownership-and-threading.mdx +++ b/apps/docs/content/docs/ffi/ownership-and-threading.mdx @@ -56,7 +56,7 @@ Snapshots, finds, listings, screenshots, clipboard reads, status, and trace read - `ad_adapter_destroy` revokes the adapter. Calls already in flight finish; calls that start afterward return `AD_RESULT_ERR_INVALID_ARGS`. - `ad_wait` blocks its calling thread for at most `scope.timeout_ms`. -- The `ad_set_log_callback` callback may run on any thread that calls an `ad_*` function, concurrently, and may still fire briefly after you unregister it. Keep it alive for the process lifetime and never let it unwind across the C ABI. +- The `ad_set_log_callback` callback may run on any thread that calls an `ad_*` function, concurrently, and may still fire briefly after you unregister it. Keep it alive for the process lifetime and never let it unwind across the C ABI. It may call `ad_*` functions itself; events from those nested calls are not delivered to it. - A language runtime's global lock does not give thread affinity; keep native handles in thread-confined objects, or use refs. - On macOS, `ad_check_permissions` reports Accessibility trust for the host executable (`python3`, `node`, your app), not for the library. diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.h index 152bbeb72f..2a3dda62e5 100644 --- a/crates/ffi/include/agent_desktop.h +++ b/crates/ffi/include/agent_desktop.h @@ -1756,6 +1756,9 @@ AdResult ad_mouse_wheel(const struct AdAdapter *adapter, * it is cleared, each call already in flight on another thread may still * invoke it once. * + * The callback may call other `ad_*` functions. Events those nested calls emit + * are not delivered to it. + * * The message pointer is valid only until the callback returns. The callback * must not unwind across this C ABI boundary; C++ exceptions and Rust panics * must be caught inside the callback. Violating that contract may abort the diff --git a/crates/ffi/src/log_callback.rs b/crates/ffi/src/log_callback.rs index a5d6a2afd6..db2805b14f 100644 --- a/crates/ffi/src/log_callback.rs +++ b/crates/ffi/src/log_callback.rs @@ -113,7 +113,7 @@ fn format_event(event: &Event<'_>) -> Option { } pub(crate) fn with_dispatch(body: impl FnOnce() -> R) -> R { - if current_callback().is_none() { + if current_callback().is_none() || IN_CALLBACK.get() { return body(); } let subscriber = tracing_subscriber::registry().with(CallbackLayer); @@ -129,6 +129,9 @@ pub(crate) fn with_dispatch(body: impl FnOnce() -> R) -> R { /// it is cleared, each call already in flight on another thread may still /// invoke it once. /// +/// The callback may call other `ad_*` functions. Events those nested calls emit +/// are not delivered to it. +/// /// The message pointer is valid only until the callback returns. The callback /// must not unwind across this C ABI boundary; C++ exceptions and Rust panics /// must be caught inside the callback. Violating that contract may abort the @@ -152,6 +155,12 @@ mod tests { static MESSAGES: Mutex> = Mutex::new(Vec::new()); static LOG_TEST_LOCK: Mutex<()> = Mutex::new(()); + pub(super) fn log_test_serialization() -> std::sync::MutexGuard<'static, ()> { + LOG_TEST_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + unsafe extern "C" fn record(_level: i32, message: *const c_char) { let message = unsafe { CStr::from_ptr(message) } .to_string_lossy() @@ -161,7 +170,7 @@ mod tests { #[test] fn scoped_dispatch_delivers_and_redacts() { - let _guard = LOG_TEST_LOCK.lock().unwrap(); + let _guard = log_test_serialization(); MESSAGES.lock().unwrap().clear(); assert_eq!(ad_set_log_callback(Some(record)), AdResult::Ok); with_dispatch(|| { @@ -183,7 +192,7 @@ mod tests { #[test] fn callback_does_not_capture_outside_scope() { - let _guard = LOG_TEST_LOCK.lock().unwrap(); + let _guard = log_test_serialization(); MESSAGES.lock().unwrap().clear(); assert_eq!(ad_set_log_callback(Some(record)), AdResult::Ok); tracing::error!(operation = "outside"); @@ -191,3 +200,7 @@ mod tests { assert!(MESSAGES.lock().unwrap().is_empty()); } } + +#[cfg(test)] +#[path = "log_callback_reentrancy_tests.rs"] +mod reentrancy_tests; diff --git a/crates/ffi/src/log_callback_reentrancy_tests.rs b/crates/ffi/src/log_callback_reentrancy_tests.rs new file mode 100644 index 0000000000..47f35a51d5 --- /dev/null +++ b/crates/ffi/src/log_callback_reentrancy_tests.rs @@ -0,0 +1,118 @@ +use std::cell::{Cell, RefCell}; +use std::ffi::{CStr, c_char}; +use std::time::{Duration, Instant}; + +use agent_desktop_core::{ + ActionOps, AdapterError, Deadline, InputOps, InteractionLease, MouseEvent, ObservationOps, + OperationReport, ProcessLeaseGuard, SystemOps, +}; + +use super::ad_set_log_callback; +use crate::adapter::{AdAdapter, ad_adapter_destroy, register_adapter}; +use crate::error::{AdResult, ad_last_error_details}; +use crate::input::mouse::ad_mouse_event; +use crate::types::{AdMouseEvent, AdPoint}; + +struct LoggingAdapter { + takes_process_lease: bool, +} + +impl ObservationOps for LoggingAdapter {} + +impl ActionOps for LoggingAdapter {} + +impl SystemOps for LoggingAdapter { + fn acquire_interaction_lease( + &self, + deadline: Deadline, + ) -> Result { + if self.takes_process_lease { + return InteractionLease::guarded(deadline, ProcessLeaseGuard::acquire(deadline)?); + } + InteractionLease::guarded(deadline, ()) + } +} + +impl InputOps for LoggingAdapter { + fn mouse_event( + &self, + event: MouseEvent, + _lease: &InteractionLease, + ) -> Result { + tracing::warn!(operation = "mouse_event"); + Ok(OperationReport::pointer_dispatched(&event, false)) + } +} + +thread_local! { + static ARMED_ADAPTER: Cell<*mut AdAdapter> = const { Cell::new(std::ptr::null_mut()) }; + static CALLBACK_RUNS: Cell = const { Cell::new(0) }; + static INNER_CALL: RefCell> = const { RefCell::new(None) }; +} + +fn move_event() -> AdMouseEvent { + AdMouseEvent { + kind: 0, + point: AdPoint { x: 1.0, y: 1.0 }, + button: 0, + click_count: 0, + } +} + +fn last_error_kind() -> String { + let details = ad_last_error_details(); + if details.is_null() { + return String::new(); + } + let text = unsafe { CStr::from_ptr(details) }.to_string_lossy(); + serde_json::from_str::(&text) + .ok() + .and_then(|value| value["kind"].as_str().map(str::to_owned)) + .unwrap_or_default() +} + +unsafe extern "C" fn reenter(_level: i32, _message: *const c_char) { + CALLBACK_RUNS.set(CALLBACK_RUNS.get().saturating_add(1)); + let adapter = ARMED_ADAPTER.replace(std::ptr::null_mut()); + if adapter.is_null() { + return; + } + let event = move_event(); + let started = Instant::now(); + let result = unsafe { ad_mouse_event(adapter, &event) }; + let elapsed = started.elapsed(); + INNER_CALL.set(Some((result, elapsed, last_error_kind()))); +} + +fn run_outer_call_reentered_by_callback( + takes_process_lease: bool, +) -> (AdResult, AdResult, Duration, String) { + let _serial = super::tests::log_test_serialization(); + let adapter = register_adapter(AdAdapter { + inner: Box::new(LoggingAdapter { + takes_process_lease, + }), + session_id: None, + _session_lease: None, + }) + .unwrap(); + CALLBACK_RUNS.set(0); + assert_eq!(ad_set_log_callback(Some(reenter)), AdResult::Ok); + ARMED_ADAPTER.set(adapter); + let outer = unsafe { ad_mouse_event(adapter, &move_event()) }; + ARMED_ADAPTER.set(std::ptr::null_mut()); + assert_eq!(ad_set_log_callback(None), AdResult::Ok); + unsafe { ad_adapter_destroy(adapter) }; + let (inner, elapsed, kind) = INNER_CALL + .take() + .expect("the log callback must run inside the outer call"); + (outer, inner, elapsed, kind) +} + +#[test] +fn a_log_callback_can_call_back_into_the_library() { + let (outer, inner, elapsed, kind) = run_outer_call_reentered_by_callback(false); + assert_eq!(inner, AdResult::Ok, "kind {kind:?} after {elapsed:?}"); + assert_eq!(outer, AdResult::Ok); + assert_eq!(CALLBACK_RUNS.get(), 1); +} diff --git a/skills/agent-desktop-ffi/references/threading.md b/skills/agent-desktop-ffi/references/threading.md index b2628c66a6..8479385da7 100644 --- a/skills/agent-desktop-ffi/references/threading.md +++ b/skills/agent-desktop-ffi/references/threading.md @@ -80,6 +80,9 @@ to cross an async task or thread boundary. `ad_set_log_callback(cb)` may be called from any thread. The callback may be invoked from any thread that calls an `ad_*` function. +The callback may itself call `ad_*` functions. Events those nested calls emit +are not delivered to the callback. + A callback unregistered via `NULL` may still receive an invocation already in flight on another thread. Keep the callback and captured state alive for the process lifetime, or quiesce active adapter calls before unregistering it. From 6058f8bcbf1217d3923f94e729e7a35a95886790 Mon Sep 17 00:00:00 2001 From: gshost1 Date: Sun, 8 Nov 2026 05:28:26 -0800 Subject: [PATCH 2/5] fix(core): refuse a same-thread interaction lease re-acquire at once The process-wide interaction lease guard was a bare flag with no owner, so a thread that already held it and asked again spun until its deadline and returned TIMEOUT interaction_process_lock_timeout, though only its own hold was in the way. With nested calls from an FFI log callback now possible, a mutating call made from the callback during a mutation waited the full 5 s FFI budget for that reason. The guard's state is now explicit, Free or Held by one thread. Another thread still waits for the lease as before; the holding thread is refused at once with POLICY_DENIED, details kind reentrant_interaction_lease and retryable false, with a suggestion to start the next interaction after the running call returns. Dropping a guard frees the lease on whichever thread drops it, including during unwinding. Tests that took the lease twice on one thread to provoke contention now contend from a second thread, which is what they meant to exercise. --- .../docs/ffi/ownership-and-threading.mdx | 2 +- .../src/session/interaction_lease_tests.rs | 31 +++---- crates/core/src/session/mod.rs | 1 + .../core/src/session/process_lease_guard.rs | 62 +++++++++++--- .../src/session/process_lease_guard_tests.rs | 85 +++++++++++++++++++ .../core/src/session/process_lease_state.rs | 32 +++++++ .../src/session/process_lease_state_tests.rs | 35 ++++++++ crates/ffi/include/agent_desktop.h | 4 +- crates/ffi/src/log_callback.rs | 4 +- .../ffi/src/log_callback_reentrancy_tests.rs | 9 ++ .../src/system/fixture/test_support.rs | 2 +- .../interaction_lease/adoption_tests.rs | 10 ++- .../src/system/interaction_lease/tests.rs | 20 +++-- .../agent-desktop-ffi/references/threading.md | 7 +- 14 files changed, 264 insertions(+), 40 deletions(-) create mode 100644 crates/core/src/session/process_lease_guard_tests.rs create mode 100644 crates/core/src/session/process_lease_state.rs create mode 100644 crates/core/src/session/process_lease_state_tests.rs diff --git a/apps/docs/content/docs/ffi/ownership-and-threading.mdx b/apps/docs/content/docs/ffi/ownership-and-threading.mdx index b47eb58bd4..a75c11d9c0 100644 --- a/apps/docs/content/docs/ffi/ownership-and-threading.mdx +++ b/apps/docs/content/docs/ffi/ownership-and-threading.mdx @@ -56,7 +56,7 @@ Snapshots, finds, listings, screenshots, clipboard reads, status, and trace read - `ad_adapter_destroy` revokes the adapter. Calls already in flight finish; calls that start afterward return `AD_RESULT_ERR_INVALID_ARGS`. - `ad_wait` blocks its calling thread for at most `scope.timeout_ms`. -- The `ad_set_log_callback` callback may run on any thread that calls an `ad_*` function, concurrently, and may still fire briefly after you unregister it. Keep it alive for the process lifetime and never let it unwind across the C ABI. It may call `ad_*` functions itself; events from those nested calls are not delivered to it. +- The `ad_set_log_callback` callback may run on any thread that calls an `ad_*` function, concurrently, and may still fire briefly after you unregister it. Keep it alive for the process lifetime and never let it unwind across the C ABI. It may call `ad_*` functions itself; events from those nested calls are not delivered to it. While the call that logged is a mutation, its thread holds the interaction lock, so a mutation from the callback fails at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease`, rather than waiting on a lock only its own thread can release. Observations from the callback still run. - A language runtime's global lock does not give thread affinity; keep native handles in thread-confined objects, or use refs. - On macOS, `ad_check_permissions` reports Accessibility trust for the host executable (`python3`, `node`, your app), not for the library. diff --git a/crates/core/src/session/interaction_lease_tests.rs b/crates/core/src/session/interaction_lease_tests.rs index 9a4d0bfe99..32c5c6b65c 100644 --- a/crates/core/src/session/interaction_lease_tests.rs +++ b/crates/core/src/session/interaction_lease_tests.rs @@ -1,9 +1,6 @@ #![cfg(unix)] -use std::{ - sync::{Mutex, MutexGuard}, - time::Duration, -}; +use std::{sync::MutexGuard, time::Duration}; use super::*; @@ -33,12 +30,8 @@ fn wait_for_marker(path: &std::path::Path) -> bool { path.is_file() } -static INTERACTION_LEASE_TEST_LOCK: Mutex<()> = Mutex::new(()); - fn interaction_lease_test_guard() -> MutexGuard<'static, ()> { - INTERACTION_LEASE_TEST_LOCK - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) + crate::session::process_lease_guard::test_serialization() } fn test_root(label: &str) -> PathBuf { @@ -56,9 +49,13 @@ fn a_second_lease_times_out_and_drop_releases_the_first() { let root = test_root("contention"); let first = acquire_unix_interaction_lease_at(Deadline::after(100).unwrap(), &root).unwrap(); let deadline = Deadline::after(10).unwrap(); - let error = match acquire_unix_interaction_lease_at(deadline, &root) { - Ok(_) => panic!("contended lease unexpectedly acquired"), - Err(error) => error, + let contender_root = root.clone(); + let contended = std::thread::spawn(move || { + acquire_unix_interaction_lease_at(deadline, &contender_root).err() + }); + let error = match contended.join().unwrap() { + None => panic!("contended lease unexpectedly acquired"), + Some(error) => error, }; assert_eq!(error.code, ErrorCode::Timeout); assert!( @@ -83,9 +80,13 @@ fn a_recovery_lease_retains_file_and_process_ownership_after_parent_drop() { let inherited = recovery.duplicate_inheritable_fd().unwrap(); drop(original); assert!(FileLock::is_held(&interaction_lock_path_at(&root).unwrap())); - let error = acquire_unix_interaction_lease_at(Deadline::after(10).unwrap(), &root) - .err() - .expect("the recovery lease must retain the process guard"); + let contender_root = root.clone(); + let error = std::thread::spawn(move || { + acquire_unix_interaction_lease_at(Deadline::after(10).unwrap(), &contender_root).err() + }) + .join() + .unwrap() + .expect("the recovery lease must retain the process guard"); assert_eq!( error.details.unwrap()["kind"], "interaction_process_lock_timeout" diff --git a/crates/core/src/session/mod.rs b/crates/core/src/session/mod.rs index 477b396593..b8d9953261 100644 --- a/crates/core/src/session/mod.rs +++ b/crates/core/src/session/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod interaction_lease; mod liveness; mod manifest; pub(crate) mod process_lease_guard; +mod process_lease_state; pub(crate) mod session_affinity; mod start; mod tree; diff --git a/crates/core/src/session/process_lease_guard.rs b/crates/core/src/session/process_lease_guard.rs index c92d33cfb5..803359dc8d 100644 --- a/crates/core/src/session/process_lease_guard.rs +++ b/crates/core/src/session/process_lease_guard.rs @@ -1,27 +1,32 @@ -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, MutexGuard, PoisonError}; use std::time::Duration; -use crate::{AdapterError, Deadline}; +use super::process_lease_state::ProcessLeaseState; +use crate::{AdapterError, Deadline, DeliverySemantics, ErrorCode}; -static PROCESS_LEASE_HELD: AtomicBool = AtomicBool::new(false); +static PROCESS_LEASE: Mutex = Mutex::new(ProcessLeaseState::Free); +/// This process's share of the interaction lease. Another thread waits for it until its deadline; the +/// thread that already holds it is refused at once, because waiting on its own hold could only time out. +/// A guard moved to another thread still counts as held by the thread that took it until it is dropped. pub struct ProcessLeaseGuard { contention_count: u64, } impl ProcessLeaseGuard { pub fn acquire(deadline: Deadline) -> Result { + let caller = std::thread::current().id(); let mut contention_count = 0_u64; loop { - if PROCESS_LEASE_HELD - .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) - .is_ok() - { - if deadline.is_expired() { - PROCESS_LEASE_HELD.store(false, Ordering::Release); + let attempt = lease_state().acquire(caller); + match attempt { + Ok(()) if deadline.is_expired() => { + lease_state().release(); return Err(timeout(deadline, contention_count)); } - return Ok(Self { contention_count }); + Ok(()) => return Ok(Self { contention_count }), + Err(owner) if owner == caller => return Err(reentrant()), + Err(_) => {} } contention_count = contention_count.saturating_add(1); let remaining = deadline.remaining(); @@ -39,13 +44,48 @@ impl ProcessLeaseGuard { impl Drop for ProcessLeaseGuard { fn drop(&mut self) { - PROCESS_LEASE_HELD.store(false, Ordering::Release); + lease_state().release(); } } +fn lease_state() -> MutexGuard<'static, ProcessLeaseState> { + PROCESS_LEASE.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn reentrant() -> AdapterError { + AdapterError::new( + ErrorCode::PolicyDenied, + "This thread already holds the interaction lease", + ) + .with_suggestion( + "Start the next interaction after the agent-desktop call running on this thread returns; \ + a log callback must not start one", + ) + .with_details(serde_json::json!({ + "kind": "reentrant_interaction_lease", + "retryable": false, + })) + .with_disposition(DeliverySemantics::not_delivered()) +} + fn timeout(deadline: Deadline, contention_count: u64) -> AdapterError { deadline.timeout_error().with_details(serde_json::json!({ "kind": "interaction_process_lock_timeout", "contention_count": contention_count, })) } + +#[cfg(test)] +static PROCESS_LEASE_TEST_LOCK: Mutex<()> = Mutex::new(()); + +/// Serializes the tests that take the process-wide lease, which would otherwise contend across test threads. +#[cfg(test)] +pub(crate) fn test_serialization() -> MutexGuard<'static, ()> { + PROCESS_LEASE_TEST_LOCK + .lock() + .unwrap_or_else(PoisonError::into_inner) +} + +#[cfg(test)] +#[path = "process_lease_guard_tests.rs"] +mod tests; diff --git a/crates/core/src/session/process_lease_guard_tests.rs b/crates/core/src/session/process_lease_guard_tests.rs new file mode 100644 index 0000000000..d6533f7efc --- /dev/null +++ b/crates/core/src/session/process_lease_guard_tests.rs @@ -0,0 +1,85 @@ +use std::time::{Duration, Instant}; + +use super::*; +use crate::ErrorCode; + +fn refusal(result: Result) -> AdapterError { + match result { + Ok(_) => panic!("the process lease was acquired while it was held"), + Err(error) => error, + } +} + +fn kind(error: &AdapterError) -> String { + error.details.as_ref().unwrap()["kind"] + .as_str() + .unwrap() + .to_owned() +} + +fn acquire_from_another_thread(timeout_ms: u64) -> Result { + std::thread::spawn(move || ProcessLeaseGuard::acquire(Deadline::after(timeout_ms).unwrap())) + .join() + .unwrap() +} + +#[test] +fn a_second_acquire_on_the_holding_thread_is_refused_at_once() { + let _serial = test_serialization(); + let held = ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap()).unwrap(); + let started = Instant::now(); + let error = refusal(ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap())); + let elapsed = started.elapsed(); + assert_eq!(error.code, ErrorCode::PolicyDenied, "after {elapsed:?}"); + assert_eq!(kind(&error), "reentrant_interaction_lease"); + assert!(elapsed < Duration::from_millis(100), "took {elapsed:?}"); + assert!(error.suggestion.is_some()); + assert_eq!(error.disposition, crate::DeliverySemantics::not_delivered()); + let payload = crate::ErrorPayload::from_app_error(&crate::AppError::Adapter(error.clone())); + assert!(payload.recovery.is_none()); + let still_held = refusal(acquire_from_another_thread(20)); + assert_eq!(kind(&still_held), "interaction_process_lock_timeout"); + drop(held); + ProcessLeaseGuard::acquire(Deadline::after(1_000).unwrap()).unwrap(); +} + +#[test] +fn another_thread_still_waits_for_the_holder_and_acquires_after_release() { + let _serial = test_serialization(); + let held = ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap()).unwrap(); + let error = refusal(acquire_from_another_thread(50)); + assert_eq!(error.code, ErrorCode::Timeout); + assert_eq!(kind(&error), "interaction_process_lock_timeout"); + assert!( + error.details.as_ref().unwrap()["contention_count"] + .as_u64() + .unwrap() + >= 1 + ); + let waiter = std::thread::spawn(|| { + ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap()) + .map(|guard| guard.contention_count()) + }); + std::thread::sleep(Duration::from_millis(20)); + drop(held); + assert!(waiter.join().unwrap().is_ok()); +} + +#[test] +fn a_guard_dropped_on_another_thread_frees_the_lease_for_its_first_owner() { + let _serial = test_serialization(); + let held = ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap()).unwrap(); + std::thread::spawn(move || drop(held)).join().unwrap(); + ProcessLeaseGuard::acquire(Deadline::after(100).unwrap()).unwrap(); +} + +#[test] +fn a_guard_released_by_unwinding_frees_the_lease() { + let _serial = test_serialization(); + let unwound = std::panic::catch_unwind(|| { + let _held = ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap()).unwrap(); + panic!("unwind while holding the process lease"); + }); + assert!(unwound.is_err()); + ProcessLeaseGuard::acquire(Deadline::after(100).unwrap()).unwrap(); +} diff --git a/crates/core/src/session/process_lease_state.rs b/crates/core/src/session/process_lease_state.rs new file mode 100644 index 0000000000..4f35e0b590 --- /dev/null +++ b/crates/core/src/session/process_lease_state.rs @@ -0,0 +1,32 @@ +use std::thread::ThreadId; + +/// Who holds this process's interaction lease: nobody, or exactly one thread. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ProcessLeaseState { + Free, + Held { owner: ThreadId }, +} + +impl ProcessLeaseState { + /// Takes the lease for `caller` when it is free. A held lease is left unchanged and its owner returned, + /// so the caller can tell a hold of its own from another thread's. + pub(crate) fn acquire(&mut self, caller: ThreadId) -> Result<(), ThreadId> { + match *self { + Self::Free => { + *self = Self::Held { owner: caller }; + Ok(()) + } + Self::Held { owner } => Err(owner), + } + } + + /// Frees the lease whichever thread releases it, since a guard may be dropped on a thread other than + /// the one that took it. + pub(crate) fn release(&mut self) { + *self = Self::Free; + } +} + +#[cfg(test)] +#[path = "process_lease_state_tests.rs"] +mod tests; diff --git a/crates/core/src/session/process_lease_state_tests.rs b/crates/core/src/session/process_lease_state_tests.rs new file mode 100644 index 0000000000..cf237945a5 --- /dev/null +++ b/crates/core/src/session/process_lease_state_tests.rs @@ -0,0 +1,35 @@ +use super::*; + +fn other_thread() -> ThreadId { + std::thread::spawn(|| std::thread::current().id()) + .join() + .unwrap() +} + +#[test] +fn a_free_lease_is_taken_by_its_caller() { + let caller = std::thread::current().id(); + let mut state = ProcessLeaseState::Free; + assert_eq!(state.acquire(caller), Ok(())); + assert_eq!(state, ProcessLeaseState::Held { owner: caller }); +} + +#[test] +fn a_held_lease_reports_its_owner_and_stays_held() { + let owner = other_thread(); + let caller = std::thread::current().id(); + let mut state = ProcessLeaseState::Held { owner }; + assert_eq!(state.acquire(caller), Err(owner)); + assert_eq!(state.acquire(owner), Err(owner)); + assert_eq!(state, ProcessLeaseState::Held { owner }); +} + +#[test] +fn release_frees_the_lease_for_any_thread() { + let mut state = ProcessLeaseState::Held { + owner: other_thread(), + }; + state.release(); + assert_eq!(state, ProcessLeaseState::Free); + assert_eq!(state.acquire(std::thread::current().id()), Ok(())); +} diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.h index 2a3dda62e5..ee56855bfe 100644 --- a/crates/ffi/include/agent_desktop.h +++ b/crates/ffi/include/agent_desktop.h @@ -1757,7 +1757,9 @@ AdResult ad_mouse_wheel(const struct AdAdapter *adapter, * invoke it once. * * The callback may call other `ad_*` functions. Events those nested calls emit - * are not delivered to it. + * are not delivered to it. A mutating call made from the callback while the + * call that logged holds the interaction lease fails at once with + * `AD_RESULT_ERR_POLICY_DENIED` and details kind `reentrant_interaction_lease`. * * The message pointer is valid only until the callback returns. The callback * must not unwind across this C ABI boundary; C++ exceptions and Rust panics diff --git a/crates/ffi/src/log_callback.rs b/crates/ffi/src/log_callback.rs index db2805b14f..bc01569c4a 100644 --- a/crates/ffi/src/log_callback.rs +++ b/crates/ffi/src/log_callback.rs @@ -130,7 +130,9 @@ pub(crate) fn with_dispatch(body: impl FnOnce() -> R) -> R { /// invoke it once. /// /// The callback may call other `ad_*` functions. Events those nested calls emit -/// are not delivered to it. +/// are not delivered to it. A mutating call made from the callback while the +/// call that logged holds the interaction lease fails at once with +/// `AD_RESULT_ERR_POLICY_DENIED` and details kind `reentrant_interaction_lease`. /// /// The message pointer is valid only until the callback returns. The callback /// must not unwind across this C ABI boundary; C++ exceptions and Rust panics diff --git a/crates/ffi/src/log_callback_reentrancy_tests.rs b/crates/ffi/src/log_callback_reentrancy_tests.rs index 47f35a51d5..c12737f8fa 100644 --- a/crates/ffi/src/log_callback_reentrancy_tests.rs +++ b/crates/ffi/src/log_callback_reentrancy_tests.rs @@ -116,3 +116,12 @@ fn a_log_callback_can_call_back_into_the_library() { assert_eq!(outer, AdResult::Ok); assert_eq!(CALLBACK_RUNS.get(), 1); } + +#[test] +fn a_mutation_from_a_log_callback_inside_a_mutation_is_refused_at_once() { + let (outer, inner, elapsed, kind) = run_outer_call_reentered_by_callback(true); + assert_eq!(outer, AdResult::Ok); + assert_eq!(inner, AdResult::ErrPolicyDenied, "after {elapsed:?}"); + assert_eq!(kind, "reentrant_interaction_lease"); + assert!(elapsed < Duration::from_millis(100), "took {elapsed:?}"); +} diff --git a/crates/windows/src/system/fixture/test_support.rs b/crates/windows/src/system/fixture/test_support.rs index c8aa4f104f..7628693ea3 100644 --- a/crates/windows/src/system/fixture/test_support.rs +++ b/crates/windows/src/system/fixture/test_support.rs @@ -43,7 +43,7 @@ pub(crate) static FIXTURE_APP_NAME_LOCK: Mutex<()> = Mutex::new(()); pub(crate) static SHELL_SURFACE_LOCK: Mutex<()> = Mutex::new(()); /// Serializes every test that reaches the real, machine-global interaction -/// lease - `ProcessLeaseGuard`'s `AtomicBool` is process-wide, so two lease +/// lease - `ProcessLeaseGuard`'s state is process-wide, so two lease /// tests in different OS threads of the same `cargo test` binary contend on /// it even when each targets its own scratch lock-file root. Held for the /// entire body of any such test, never just around one call. diff --git a/crates/windows/src/system/interaction_lease/adoption_tests.rs b/crates/windows/src/system/interaction_lease/adoption_tests.rs index 26e189d13a..9fa121ff69 100644 --- a/crates/windows/src/system/interaction_lease/adoption_tests.rs +++ b/crates/windows/src/system/interaction_lease/adoption_tests.rs @@ -39,9 +39,13 @@ fn adoption_of_share_zero_handle_succeeds_and_still_blocks_a_fresh_acquire() { windows_sys::Win32::Foundation::CloseHandle(raw); } - let error = match acquire_at(&root, Deadline::after(50).unwrap()) { - Ok(_) => panic!("the adopted duplicate must still hold the lease exclusively"), - Err(error) => error, + let contender_root = root.clone(); + let contender = std::thread::spawn(move || { + acquire_at(&contender_root, Deadline::after(50).unwrap()).err() + }); + let error = match contender.join().unwrap() { + None => panic!("the adopted duplicate must still hold the lease exclusively"), + Some(error) => error, }; assert_eq!(error.code, ErrorCode::Timeout); diff --git a/crates/windows/src/system/interaction_lease/tests.rs b/crates/windows/src/system/interaction_lease/tests.rs index e618b31bb8..d6663d0fcd 100644 --- a/crates/windows/src/system/interaction_lease/tests.rs +++ b/crates/windows/src/system/interaction_lease/tests.rs @@ -121,8 +121,8 @@ fn cross_process_contention_times_out_with_lock_timeout_kind() { }); } -/// A second in-process acquire refuses through `ProcessLeaseGuard` before the -/// file is ever opened, which is a different shape from cross-process +/// A second in-process acquire from another thread refuses through +/// `ProcessLeaseGuard` before the file is ever opened, which is a different shape from cross-process /// contention: `CreateFileW` with `dwShareMode = 0` also refuses a second /// open from the *same* process, so asserting the file-lock kind here would /// be untestable - this proves the in-process guard is what actually fires. @@ -131,9 +131,13 @@ fn in_process_second_acquire_times_out_with_process_lock_kind() { with_interaction_lease_test_lock(|| { let root = scratch_root("in-process"); let first = acquire_at(&root, Deadline::after(1_000).unwrap()).unwrap(); - let error = match acquire_at(&root, Deadline::after(50).unwrap()) { - Ok(_) => panic!("in-process double acquire unexpectedly succeeded"), - Err(error) => error, + let contender_root = root.clone(); + let contender = std::thread::spawn(move || { + acquire_at(&contender_root, Deadline::after(50).unwrap()).err() + }); + let error = match contender.join().unwrap() { + None => panic!("in-process double acquire unexpectedly succeeded"), + Some(error) => error, }; assert_eq!(error.code, ErrorCode::Timeout); assert_eq!( @@ -201,11 +205,15 @@ fn success_path_reports_earned_contention_count() { fn success_path_includes_process_guard_contention() { with_interaction_lease_test_lock(|| { let root = scratch_root("process-guard-contention"); - let first = acquire_at(&root, Deadline::after(2_000).unwrap()).unwrap(); + let holder_root = root.clone(); + let (held, held_signal) = std::sync::mpsc::channel(); let releaser = std::thread::spawn(move || { + let first = acquire_at(&holder_root, Deadline::after(2_000).unwrap()).unwrap(); + held.send(()).unwrap(); std::thread::sleep(Duration::from_millis(80)); drop(first); }); + held_signal.recv().unwrap(); let lease = acquire_at(&root, Deadline::after(2_000).unwrap()).unwrap(); assert!( diff --git a/skills/agent-desktop-ffi/references/threading.md b/skills/agent-desktop-ffi/references/threading.md index 8479385da7..6ba597e7d9 100644 --- a/skills/agent-desktop-ffi/references/threading.md +++ b/skills/agent-desktop-ffi/references/threading.md @@ -20,6 +20,7 @@ finite deadline and do not take the interaction lease. | read + read | Both may run concurrently; neither waits for the interaction lease | | read + mutation | The read does not wait for the lease and may overlap the mutation; its result is a point-in-time observation, not a transaction | | mutation + mutation | One lease holder runs at a time for the same OS user; the waiter consumes its command deadline and returns a structured timeout if it cannot acquire the lease | +| mutation inside a mutation on the same thread (from a log callback) | Refused at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease` | | native-handle call on another thread | Rejected with `AD_RESULT_ERR_INVALID_ARGS`; use a qualified ref instead | Snapshots, finds, gets, display/window/app listings, screenshots, clipboard @@ -81,7 +82,11 @@ to cross an async task or thread boundary. invoked from any thread that calls an `ad_*` function. The callback may itself call `ad_*` functions. Events those nested calls emit -are not delivered to the callback. +are not delivered to the callback. While the call that logged is a mutation, its +thread holds the interaction lease, so a mutating call from the callback fails +at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind +`reentrant_interaction_lease` and `retryable: false`, instead of waiting for a +lease only its own thread can release. Observations from the callback still run. A callback unregistered via `NULL` may still receive an invocation already in flight on another thread. Keep the callback and captured state alive for the From f8e2926e1d52336c608111242d44c687112fd3c8 Mon Sep 17 00:00:00 2001 From: gshost1 Date: Sun, 8 Nov 2026 05:50:04 -0800 Subject: [PATCH 3/5] fix(ffi): refuse a log callback's mutation at the FFI layer, not in core Keying the process lease guard to the thread that took it broke a real handoff: the Linux stale-input sweep moves the guard onto a worker thread, and when the sweep outlives its budget the worker can still hold it, so the caller's next action was refused as reentrant instead of waiting a few hundred milliseconds for the worker to finish. Core's guard goes back to waiting for any holder, as on main, and the tests changed for it go back to main's versions. The only same-thread re-acquire that can be reached is a mutating ad_* call made from a log callback while the call that logged holds the lease, so it is caught where it starts. Each FFI operation that takes the interaction lease (the shared lease helper, app launch, execute_by_ref) marks its thread for as long as it holds it. A mutation entered from inside the callback while that mark is set is refused at once with POLICY_DENIED, details kind reentrant_interaction_lease and retryable false, before it waits. Other threads are unaffected and wait for the lease as before. The nested-call dispatch check now reads the thread-local callback flag before the callback slot's mutex. The docs say which nested calls are refused and which wait on the outer call's lease and can time out. --- .../docs/ffi/ownership-and-threading.mdx | 2 +- .../src/session/interaction_lease_tests.rs | 31 ++++--- crates/core/src/session/mod.rs | 1 - .../core/src/session/process_lease_guard.rs | 62 +++---------- .../src/session/process_lease_guard_tests.rs | 85 ------------------ .../core/src/session/process_lease_state.rs | 32 ------- .../src/session/process_lease_state_tests.rs | 35 -------- crates/ffi/include/agent_desktop.h | 6 +- crates/ffi/src/apps/launch.rs | 4 +- .../src/commands/execute_by_ref_timeout.rs | 6 ++ crates/ffi/src/ffi_lease.rs | 33 +++++++ crates/ffi/src/lease_marker.rs | 47 ++++++++++ crates/ffi/src/lib.rs | 2 + crates/ffi/src/log_callback.rs | 12 ++- .../ffi/src/log_callback_reentrancy_tests.rs | 87 +++++++++++++++---- crates/ffi/src/operation.rs | 8 +- .../src/system/fixture/test_support.rs | 2 +- .../interaction_lease/adoption_tests.rs | 10 +-- .../src/system/interaction_lease/tests.rs | 20 ++--- .../agent-desktop-ffi/references/threading.md | 17 ++-- 20 files changed, 232 insertions(+), 270 deletions(-) delete mode 100644 crates/core/src/session/process_lease_guard_tests.rs delete mode 100644 crates/core/src/session/process_lease_state.rs delete mode 100644 crates/core/src/session/process_lease_state_tests.rs create mode 100644 crates/ffi/src/ffi_lease.rs create mode 100644 crates/ffi/src/lease_marker.rs diff --git a/apps/docs/content/docs/ffi/ownership-and-threading.mdx b/apps/docs/content/docs/ffi/ownership-and-threading.mdx index a75c11d9c0..74e4cb3388 100644 --- a/apps/docs/content/docs/ffi/ownership-and-threading.mdx +++ b/apps/docs/content/docs/ffi/ownership-and-threading.mdx @@ -56,7 +56,7 @@ Snapshots, finds, listings, screenshots, clipboard reads, status, and trace read - `ad_adapter_destroy` revokes the adapter. Calls already in flight finish; calls that start afterward return `AD_RESULT_ERR_INVALID_ARGS`. - `ad_wait` blocks its calling thread for at most `scope.timeout_ms`. -- The `ad_set_log_callback` callback may run on any thread that calls an `ad_*` function, concurrently, and may still fire briefly after you unregister it. Keep it alive for the process lifetime and never let it unwind across the C ABI. It may call `ad_*` functions itself; events from those nested calls are not delivered to it. While the call that logged is a mutation, its thread holds the interaction lock, so a mutation from the callback fails at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease`, rather than waiting on a lock only its own thread can release. Observations from the callback still run. +- The `ad_set_log_callback` callback may run on any thread that calls an `ad_*` function, concurrently, and may still fire briefly after you unregister it. Keep it alive for the process lifetime and never let it unwind across the C ABI. It may call `ad_*` functions itself; events from those nested calls are not delivered to it. A mutation from the callback while the call that logged is a mutation fails at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease`. Any other nested call that needs the interaction lock while the outer call holds it, including an observation that takes the lock internally, waits for a release that comes only after the callback returns and can time out, so do not make it from the callback. Other threads wait for the lock as usual. - A language runtime's global lock does not give thread affinity; keep native handles in thread-confined objects, or use refs. - On macOS, `ad_check_permissions` reports Accessibility trust for the host executable (`python3`, `node`, your app), not for the library. diff --git a/crates/core/src/session/interaction_lease_tests.rs b/crates/core/src/session/interaction_lease_tests.rs index 32c5c6b65c..9a4d0bfe99 100644 --- a/crates/core/src/session/interaction_lease_tests.rs +++ b/crates/core/src/session/interaction_lease_tests.rs @@ -1,6 +1,9 @@ #![cfg(unix)] -use std::{sync::MutexGuard, time::Duration}; +use std::{ + sync::{Mutex, MutexGuard}, + time::Duration, +}; use super::*; @@ -30,8 +33,12 @@ fn wait_for_marker(path: &std::path::Path) -> bool { path.is_file() } +static INTERACTION_LEASE_TEST_LOCK: Mutex<()> = Mutex::new(()); + fn interaction_lease_test_guard() -> MutexGuard<'static, ()> { - crate::session::process_lease_guard::test_serialization() + INTERACTION_LEASE_TEST_LOCK + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) } fn test_root(label: &str) -> PathBuf { @@ -49,13 +56,9 @@ fn a_second_lease_times_out_and_drop_releases_the_first() { let root = test_root("contention"); let first = acquire_unix_interaction_lease_at(Deadline::after(100).unwrap(), &root).unwrap(); let deadline = Deadline::after(10).unwrap(); - let contender_root = root.clone(); - let contended = std::thread::spawn(move || { - acquire_unix_interaction_lease_at(deadline, &contender_root).err() - }); - let error = match contended.join().unwrap() { - None => panic!("contended lease unexpectedly acquired"), - Some(error) => error, + let error = match acquire_unix_interaction_lease_at(deadline, &root) { + Ok(_) => panic!("contended lease unexpectedly acquired"), + Err(error) => error, }; assert_eq!(error.code, ErrorCode::Timeout); assert!( @@ -80,13 +83,9 @@ fn a_recovery_lease_retains_file_and_process_ownership_after_parent_drop() { let inherited = recovery.duplicate_inheritable_fd().unwrap(); drop(original); assert!(FileLock::is_held(&interaction_lock_path_at(&root).unwrap())); - let contender_root = root.clone(); - let error = std::thread::spawn(move || { - acquire_unix_interaction_lease_at(Deadline::after(10).unwrap(), &contender_root).err() - }) - .join() - .unwrap() - .expect("the recovery lease must retain the process guard"); + let error = acquire_unix_interaction_lease_at(Deadline::after(10).unwrap(), &root) + .err() + .expect("the recovery lease must retain the process guard"); assert_eq!( error.details.unwrap()["kind"], "interaction_process_lock_timeout" diff --git a/crates/core/src/session/mod.rs b/crates/core/src/session/mod.rs index b8d9953261..477b396593 100644 --- a/crates/core/src/session/mod.rs +++ b/crates/core/src/session/mod.rs @@ -3,7 +3,6 @@ pub(crate) mod interaction_lease; mod liveness; mod manifest; pub(crate) mod process_lease_guard; -mod process_lease_state; pub(crate) mod session_affinity; mod start; mod tree; diff --git a/crates/core/src/session/process_lease_guard.rs b/crates/core/src/session/process_lease_guard.rs index 803359dc8d..c92d33cfb5 100644 --- a/crates/core/src/session/process_lease_guard.rs +++ b/crates/core/src/session/process_lease_guard.rs @@ -1,32 +1,27 @@ -use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; -use super::process_lease_state::ProcessLeaseState; -use crate::{AdapterError, Deadline, DeliverySemantics, ErrorCode}; +use crate::{AdapterError, Deadline}; -static PROCESS_LEASE: Mutex = Mutex::new(ProcessLeaseState::Free); +static PROCESS_LEASE_HELD: AtomicBool = AtomicBool::new(false); -/// This process's share of the interaction lease. Another thread waits for it until its deadline; the -/// thread that already holds it is refused at once, because waiting on its own hold could only time out. -/// A guard moved to another thread still counts as held by the thread that took it until it is dropped. pub struct ProcessLeaseGuard { contention_count: u64, } impl ProcessLeaseGuard { pub fn acquire(deadline: Deadline) -> Result { - let caller = std::thread::current().id(); let mut contention_count = 0_u64; loop { - let attempt = lease_state().acquire(caller); - match attempt { - Ok(()) if deadline.is_expired() => { - lease_state().release(); + if PROCESS_LEASE_HELD + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + { + if deadline.is_expired() { + PROCESS_LEASE_HELD.store(false, Ordering::Release); return Err(timeout(deadline, contention_count)); } - Ok(()) => return Ok(Self { contention_count }), - Err(owner) if owner == caller => return Err(reentrant()), - Err(_) => {} + return Ok(Self { contention_count }); } contention_count = contention_count.saturating_add(1); let remaining = deadline.remaining(); @@ -44,48 +39,13 @@ impl ProcessLeaseGuard { impl Drop for ProcessLeaseGuard { fn drop(&mut self) { - lease_state().release(); + PROCESS_LEASE_HELD.store(false, Ordering::Release); } } -fn lease_state() -> MutexGuard<'static, ProcessLeaseState> { - PROCESS_LEASE.lock().unwrap_or_else(PoisonError::into_inner) -} - -fn reentrant() -> AdapterError { - AdapterError::new( - ErrorCode::PolicyDenied, - "This thread already holds the interaction lease", - ) - .with_suggestion( - "Start the next interaction after the agent-desktop call running on this thread returns; \ - a log callback must not start one", - ) - .with_details(serde_json::json!({ - "kind": "reentrant_interaction_lease", - "retryable": false, - })) - .with_disposition(DeliverySemantics::not_delivered()) -} - fn timeout(deadline: Deadline, contention_count: u64) -> AdapterError { deadline.timeout_error().with_details(serde_json::json!({ "kind": "interaction_process_lock_timeout", "contention_count": contention_count, })) } - -#[cfg(test)] -static PROCESS_LEASE_TEST_LOCK: Mutex<()> = Mutex::new(()); - -/// Serializes the tests that take the process-wide lease, which would otherwise contend across test threads. -#[cfg(test)] -pub(crate) fn test_serialization() -> MutexGuard<'static, ()> { - PROCESS_LEASE_TEST_LOCK - .lock() - .unwrap_or_else(PoisonError::into_inner) -} - -#[cfg(test)] -#[path = "process_lease_guard_tests.rs"] -mod tests; diff --git a/crates/core/src/session/process_lease_guard_tests.rs b/crates/core/src/session/process_lease_guard_tests.rs deleted file mode 100644 index d6533f7efc..0000000000 --- a/crates/core/src/session/process_lease_guard_tests.rs +++ /dev/null @@ -1,85 +0,0 @@ -use std::time::{Duration, Instant}; - -use super::*; -use crate::ErrorCode; - -fn refusal(result: Result) -> AdapterError { - match result { - Ok(_) => panic!("the process lease was acquired while it was held"), - Err(error) => error, - } -} - -fn kind(error: &AdapterError) -> String { - error.details.as_ref().unwrap()["kind"] - .as_str() - .unwrap() - .to_owned() -} - -fn acquire_from_another_thread(timeout_ms: u64) -> Result { - std::thread::spawn(move || ProcessLeaseGuard::acquire(Deadline::after(timeout_ms).unwrap())) - .join() - .unwrap() -} - -#[test] -fn a_second_acquire_on_the_holding_thread_is_refused_at_once() { - let _serial = test_serialization(); - let held = ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap()).unwrap(); - let started = Instant::now(); - let error = refusal(ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap())); - let elapsed = started.elapsed(); - assert_eq!(error.code, ErrorCode::PolicyDenied, "after {elapsed:?}"); - assert_eq!(kind(&error), "reentrant_interaction_lease"); - assert!(elapsed < Duration::from_millis(100), "took {elapsed:?}"); - assert!(error.suggestion.is_some()); - assert_eq!(error.disposition, crate::DeliverySemantics::not_delivered()); - let payload = crate::ErrorPayload::from_app_error(&crate::AppError::Adapter(error.clone())); - assert!(payload.recovery.is_none()); - let still_held = refusal(acquire_from_another_thread(20)); - assert_eq!(kind(&still_held), "interaction_process_lock_timeout"); - drop(held); - ProcessLeaseGuard::acquire(Deadline::after(1_000).unwrap()).unwrap(); -} - -#[test] -fn another_thread_still_waits_for_the_holder_and_acquires_after_release() { - let _serial = test_serialization(); - let held = ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap()).unwrap(); - let error = refusal(acquire_from_another_thread(50)); - assert_eq!(error.code, ErrorCode::Timeout); - assert_eq!(kind(&error), "interaction_process_lock_timeout"); - assert!( - error.details.as_ref().unwrap()["contention_count"] - .as_u64() - .unwrap() - >= 1 - ); - let waiter = std::thread::spawn(|| { - ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap()) - .map(|guard| guard.contention_count()) - }); - std::thread::sleep(Duration::from_millis(20)); - drop(held); - assert!(waiter.join().unwrap().is_ok()); -} - -#[test] -fn a_guard_dropped_on_another_thread_frees_the_lease_for_its_first_owner() { - let _serial = test_serialization(); - let held = ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap()).unwrap(); - std::thread::spawn(move || drop(held)).join().unwrap(); - ProcessLeaseGuard::acquire(Deadline::after(100).unwrap()).unwrap(); -} - -#[test] -fn a_guard_released_by_unwinding_frees_the_lease() { - let _serial = test_serialization(); - let unwound = std::panic::catch_unwind(|| { - let _held = ProcessLeaseGuard::acquire(Deadline::after(5_000).unwrap()).unwrap(); - panic!("unwind while holding the process lease"); - }); - assert!(unwound.is_err()); - ProcessLeaseGuard::acquire(Deadline::after(100).unwrap()).unwrap(); -} diff --git a/crates/core/src/session/process_lease_state.rs b/crates/core/src/session/process_lease_state.rs deleted file mode 100644 index 4f35e0b590..0000000000 --- a/crates/core/src/session/process_lease_state.rs +++ /dev/null @@ -1,32 +0,0 @@ -use std::thread::ThreadId; - -/// Who holds this process's interaction lease: nobody, or exactly one thread. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum ProcessLeaseState { - Free, - Held { owner: ThreadId }, -} - -impl ProcessLeaseState { - /// Takes the lease for `caller` when it is free. A held lease is left unchanged and its owner returned, - /// so the caller can tell a hold of its own from another thread's. - pub(crate) fn acquire(&mut self, caller: ThreadId) -> Result<(), ThreadId> { - match *self { - Self::Free => { - *self = Self::Held { owner: caller }; - Ok(()) - } - Self::Held { owner } => Err(owner), - } - } - - /// Frees the lease whichever thread releases it, since a guard may be dropped on a thread other than - /// the one that took it. - pub(crate) fn release(&mut self) { - *self = Self::Free; - } -} - -#[cfg(test)] -#[path = "process_lease_state_tests.rs"] -mod tests; diff --git a/crates/core/src/session/process_lease_state_tests.rs b/crates/core/src/session/process_lease_state_tests.rs deleted file mode 100644 index cf237945a5..0000000000 --- a/crates/core/src/session/process_lease_state_tests.rs +++ /dev/null @@ -1,35 +0,0 @@ -use super::*; - -fn other_thread() -> ThreadId { - std::thread::spawn(|| std::thread::current().id()) - .join() - .unwrap() -} - -#[test] -fn a_free_lease_is_taken_by_its_caller() { - let caller = std::thread::current().id(); - let mut state = ProcessLeaseState::Free; - assert_eq!(state.acquire(caller), Ok(())); - assert_eq!(state, ProcessLeaseState::Held { owner: caller }); -} - -#[test] -fn a_held_lease_reports_its_owner_and_stays_held() { - let owner = other_thread(); - let caller = std::thread::current().id(); - let mut state = ProcessLeaseState::Held { owner }; - assert_eq!(state.acquire(caller), Err(owner)); - assert_eq!(state.acquire(owner), Err(owner)); - assert_eq!(state, ProcessLeaseState::Held { owner }); -} - -#[test] -fn release_frees_the_lease_for_any_thread() { - let mut state = ProcessLeaseState::Held { - owner: other_thread(), - }; - state.release(); - assert_eq!(state, ProcessLeaseState::Free); - assert_eq!(state.acquire(std::thread::current().id()), Ok(())); -} diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.h index ee56855bfe..943b792152 100644 --- a/crates/ffi/include/agent_desktop.h +++ b/crates/ffi/include/agent_desktop.h @@ -1758,8 +1758,12 @@ AdResult ad_mouse_wheel(const struct AdAdapter *adapter, * * The callback may call other `ad_*` functions. Events those nested calls emit * are not delivered to it. A mutating call made from the callback while the - * call that logged holds the interaction lease fails at once with + * call that logged is itself a mutation fails at once with * `AD_RESULT_ERR_POLICY_DENIED` and details kind `reentrant_interaction_lease`. + * Any other nested call that needs the interaction lease while the call that + * logged holds it, including an observation that takes the lease internally, + * waits for a release that happens only after the callback returns, so it can + * time out. Do not make such calls from the callback. * * The message pointer is valid only until the callback returns. The callback * must not unwind across this C ABI boundary; C++ exceptions and Rust panics diff --git a/crates/ffi/src/apps/launch.rs b/crates/ffi/src/apps/launch.rs index 7c93637db5..2c0bf46efb 100644 --- a/crates/ffi/src/apps/launch.rs +++ b/crates/ffi/src/apps/launch.rs @@ -63,7 +63,9 @@ pub unsafe extern "C" fn ad_launch_app_exact( return set_last_error(&error); } }; - let lease = match adapter.inner.acquire_interaction_lease(deadline) { + let lease = match crate::ffi_lease::FfiLease::take(|| { + adapter.inner.acquire_interaction_lease(deadline) + }) { Ok(lease) => lease, Err(error) => { return set_last_error(&error); diff --git a/crates/ffi/src/commands/execute_by_ref_timeout.rs b/crates/ffi/src/commands/execute_by_ref_timeout.rs index dcaff696e1..7ddc257977 100644 --- a/crates/ffi/src/commands/execute_by_ref_timeout.rs +++ b/crates/ffi/src/commands/execute_by_ref_timeout.rs @@ -73,6 +73,12 @@ pub unsafe extern "C" fn ad_execute_by_ref_timeout( let caller_ip = caller_policy.to_interaction_policy(); let adapter_ref = crate::adapter::acquire_adapter!(adapter); + let _lease_marker = match crate::lease_marker::LeaseMarker::enter() { + Ok(marker) => marker, + Err(error) => { + return set_last_error(&error); + } + }; let context = match adapter_ref.command_context() { Ok(ctx) => ctx, Err(e) => { diff --git a/crates/ffi/src/ffi_lease.rs b/crates/ffi/src/ffi_lease.rs new file mode 100644 index 0000000000..28be89f588 --- /dev/null +++ b/crates/ffi/src/ffi_lease.rs @@ -0,0 +1,33 @@ +use std::ops::Deref; + +use agent_desktop_core::{AdapterError, InteractionLease}; + +use crate::lease_marker::LeaseMarker; + +/// An interaction lease taken by an FFI operation, with this thread marked as holding it for as long as +/// the lease lives. +pub(crate) struct FfiLease { + lease: InteractionLease, + _marker: LeaseMarker, +} + +impl FfiLease { + /// Marks this thread, then takes the lease with `acquire`. A refused mark returns before `acquire` runs. + pub(crate) fn take( + acquire: impl FnOnce() -> Result, + ) -> Result { + let marker = LeaseMarker::enter()?; + Ok(Self { + lease: acquire()?, + _marker: marker, + }) + } +} + +impl Deref for FfiLease { + type Target = InteractionLease; + + fn deref(&self) -> &InteractionLease { + &self.lease + } +} diff --git a/crates/ffi/src/lease_marker.rs b/crates/ffi/src/lease_marker.rs new file mode 100644 index 0000000000..2298090267 --- /dev/null +++ b/crates/ffi/src/lease_marker.rs @@ -0,0 +1,47 @@ +use std::cell::Cell; + +use agent_desktop_core::{AdapterError, DeliverySemantics, ErrorCode}; + +thread_local! { + static OPERATION_HOLDS_LEASE: Cell = const { Cell::new(false) }; +} + +/// Marks this thread's running FFI operation as holding, or about to take, the interaction lease, until it +/// is dropped. A mutating call made from a log callback while the mark is set is refused instead of waiting +/// for a lease that only the callback's own thread can release. +pub(crate) struct LeaseMarker { + previous: bool, +} + +impl LeaseMarker { + pub(crate) fn enter() -> Result { + if crate::log_callback::in_callback() && OPERATION_HOLDS_LEASE.get() { + return Err(reentrant()); + } + Ok(Self { + previous: OPERATION_HOLDS_LEASE.replace(true), + }) + } +} + +impl Drop for LeaseMarker { + fn drop(&mut self) { + OPERATION_HOLDS_LEASE.set(self.previous); + } +} + +fn reentrant() -> AdapterError { + AdapterError::new( + ErrorCode::PolicyDenied, + "A log callback cannot start an interaction while the call that logged holds the interaction lease", + ) + .with_suggestion( + "Return from the log callback and make the call after the running ad_* call returns, \ + or queue it for another thread that does not wait on this one", + ) + .with_details(serde_json::json!({ + "kind": "reentrant_interaction_lease", + "retryable": false, + })) + .with_disposition(DeliverySemantics::not_delivered()) +} diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index 58dffaedd2..fadd74866e 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -46,8 +46,10 @@ pub(crate) mod convert; pub(crate) mod displays; pub(crate) mod enum_validation; pub mod error; +pub(crate) mod ffi_lease; pub(crate) mod ffi_try; pub(crate) mod input; +pub(crate) mod lease_marker; pub(crate) mod log_callback; pub(crate) mod notifications; pub(crate) mod observation; diff --git a/crates/ffi/src/log_callback.rs b/crates/ffi/src/log_callback.rs index bc01569c4a..2d79a99d5f 100644 --- a/crates/ffi/src/log_callback.rs +++ b/crates/ffi/src/log_callback.rs @@ -112,8 +112,12 @@ fn format_event(event: &Event<'_>) -> Option { CString::new(serde_json::to_string(&sanitized).ok()?).ok() } +pub(crate) fn in_callback() -> bool { + IN_CALLBACK.get() +} + pub(crate) fn with_dispatch(body: impl FnOnce() -> R) -> R { - if current_callback().is_none() || IN_CALLBACK.get() { + if IN_CALLBACK.get() || current_callback().is_none() { return body(); } let subscriber = tracing_subscriber::registry().with(CallbackLayer); @@ -131,8 +135,12 @@ pub(crate) fn with_dispatch(body: impl FnOnce() -> R) -> R { /// /// The callback may call other `ad_*` functions. Events those nested calls emit /// are not delivered to it. A mutating call made from the callback while the -/// call that logged holds the interaction lease fails at once with +/// call that logged is itself a mutation fails at once with /// `AD_RESULT_ERR_POLICY_DENIED` and details kind `reentrant_interaction_lease`. +/// Any other nested call that needs the interaction lease while the call that +/// logged holds it, including an observation that takes the lease internally, +/// waits for a release that happens only after the callback returns, so it can +/// time out. Do not make such calls from the callback. /// /// The message pointer is valid only until the callback returns. The callback /// must not unwind across this C ABI boundary; C++ exceptions and Rust panics diff --git a/crates/ffi/src/log_callback_reentrancy_tests.rs b/crates/ffi/src/log_callback_reentrancy_tests.rs index c12737f8fa..db0e380415 100644 --- a/crates/ffi/src/log_callback_reentrancy_tests.rs +++ b/crates/ffi/src/log_callback_reentrancy_tests.rs @@ -1,18 +1,22 @@ use std::cell::{Cell, RefCell}; use std::ffi::{CStr, c_char}; +use std::thread::JoinHandle; use std::time::{Duration, Instant}; use agent_desktop_core::{ - ActionOps, AdapterError, Deadline, InputOps, InteractionLease, MouseEvent, ObservationOps, - OperationReport, ProcessLeaseGuard, SystemOps, + ActionOps, AdapterError, Deadline, DisplayInfo, InputOps, InteractionLease, MouseEvent, + ObservationOps, OperationReport, ProcessLeaseGuard, SystemOps, }; use super::ad_set_log_callback; use crate::adapter::{AdAdapter, ad_adapter_destroy, register_adapter}; +use crate::displays::list::ad_list_displays; use crate::error::{AdResult, ad_last_error_details}; use crate::input::mouse::ad_mouse_event; use crate::types::{AdMouseEvent, AdPoint}; +const CALLBACK_HOLD: Duration = Duration::from_millis(150); + struct LoggingAdapter { takes_process_lease: bool, } @@ -31,6 +35,11 @@ impl SystemOps for LoggingAdapter { } InteractionLease::guarded(deadline, ()) } + + fn list_displays(&self, _deadline: Deadline) -> Result, AdapterError> { + tracing::warn!(operation = "list_displays"); + Err(AdapterError::not_supported("list_displays")) + } } impl InputOps for LoggingAdapter { @@ -44,10 +53,13 @@ impl InputOps for LoggingAdapter { } } +type TimedCall = (AdResult, Duration); + thread_local! { static ARMED_ADAPTER: Cell<*mut AdAdapter> = const { Cell::new(std::ptr::null_mut()) }; static CALLBACK_RUNS: Cell = const { Cell::new(0) }; static INNER_CALL: RefCell> = const { RefCell::new(None) }; + static CONTENDER: RefCell>> = const { RefCell::new(None) }; } fn move_event() -> AdMouseEvent { @@ -71,22 +83,41 @@ fn last_error_kind() -> String { .unwrap_or_default() } +fn timed_mouse_event(adapter: *mut AdAdapter) -> TimedCall { + let event = move_event(); + let started = Instant::now(); + let result = unsafe { ad_mouse_event(adapter, &event) }; + (result, started.elapsed()) +} + unsafe extern "C" fn reenter(_level: i32, _message: *const c_char) { CALLBACK_RUNS.set(CALLBACK_RUNS.get().saturating_add(1)); let adapter = ARMED_ADAPTER.replace(std::ptr::null_mut()); if adapter.is_null() { return; } - let event = move_event(); - let started = Instant::now(); - let result = unsafe { ad_mouse_event(adapter, &event) }; - let elapsed = started.elapsed(); + let (result, elapsed) = timed_mouse_event(adapter); INNER_CALL.set(Some((result, elapsed, last_error_kind()))); } -fn run_outer_call_reentered_by_callback( +unsafe extern "C" fn start_contender(_level: i32, _message: *const c_char) { + let adapter = ARMED_ADAPTER.replace(std::ptr::null_mut()); + if adapter.is_null() { + return; + } + let address = adapter.expose_provenance(); + let contender = std::thread::spawn(move || { + timed_mouse_event(std::ptr::with_exposed_provenance_mut(address)) + }); + CONTENDER.set(Some(contender)); + std::thread::sleep(CALLBACK_HOLD); +} + +fn with_logging_adapter( takes_process_lease: bool, -) -> (AdResult, AdResult, Duration, String) { + callback: unsafe extern "C" fn(i32, *const c_char), + outer_call: impl FnOnce(*mut AdAdapter) -> R, +) -> R { let _serial = super::tests::log_test_serialization(); let adapter = register_adapter(AdAdapter { inner: Box::new(LoggingAdapter { @@ -97,31 +128,55 @@ fn run_outer_call_reentered_by_callback( }) .unwrap(); CALLBACK_RUNS.set(0); - assert_eq!(ad_set_log_callback(Some(reenter)), AdResult::Ok); + assert_eq!(ad_set_log_callback(Some(callback)), AdResult::Ok); ARMED_ADAPTER.set(adapter); - let outer = unsafe { ad_mouse_event(adapter, &move_event()) }; + let outer = outer_call(adapter); ARMED_ADAPTER.set(std::ptr::null_mut()); assert_eq!(ad_set_log_callback(None), AdResult::Ok); unsafe { ad_adapter_destroy(adapter) }; - let (inner, elapsed, kind) = INNER_CALL + outer +} + +fn inner_call() -> (AdResult, Duration, String) { + INNER_CALL .take() - .expect("the log callback must run inside the outer call"); - (outer, inner, elapsed, kind) + .expect("the log callback must run inside the outer call") } #[test] fn a_log_callback_can_call_back_into_the_library() { - let (outer, inner, elapsed, kind) = run_outer_call_reentered_by_callback(false); + let outer = with_logging_adapter(false, reenter, |adapter| unsafe { + let mut displays = std::ptr::null_mut(); + ad_list_displays(adapter, &mut displays) + }); + let (inner, elapsed, kind) = inner_call(); assert_eq!(inner, AdResult::Ok, "kind {kind:?} after {elapsed:?}"); - assert_eq!(outer, AdResult::Ok); + assert_ne!(outer, AdResult::ErrInternal); assert_eq!(CALLBACK_RUNS.get(), 1); } #[test] fn a_mutation_from_a_log_callback_inside_a_mutation_is_refused_at_once() { - let (outer, inner, elapsed, kind) = run_outer_call_reentered_by_callback(true); + let outer = with_logging_adapter(true, reenter, |adapter| unsafe { + ad_mouse_event(adapter, &move_event()) + }); + let (inner, elapsed, kind) = inner_call(); assert_eq!(outer, AdResult::Ok); assert_eq!(inner, AdResult::ErrPolicyDenied, "after {elapsed:?}"); assert_eq!(kind, "reentrant_interaction_lease"); assert!(elapsed < Duration::from_millis(100), "took {elapsed:?}"); } + +#[test] +fn another_thread_waits_for_the_lease_a_logging_mutation_holds() { + let (outer, (result, waited)) = with_logging_adapter(true, start_contender, |adapter| { + let outer = unsafe { ad_mouse_event(adapter, &move_event()) }; + let contender = CONTENDER + .take() + .expect("the log callback must start the contender inside the outer call"); + (outer, contender.join().unwrap()) + }); + assert_eq!(outer, AdResult::Ok); + assert_eq!(result, AdResult::Ok, "after {waited:?}"); + assert!(waited >= CALLBACK_HOLD / 2, "waited only {waited:?}"); +} diff --git a/crates/ffi/src/operation.rs b/crates/ffi/src/operation.rs index 32d7fc2ed7..0eccf716eb 100644 --- a/crates/ffi/src/operation.rs +++ b/crates/ffi/src/operation.rs @@ -1,12 +1,18 @@ use agent_desktop_core::{AdapterError, Deadline, InteractionLease, PlatformAdapter}; +use crate::ffi_lease::FfiLease; + pub(crate) const DEFAULT_FFI_TIMEOUT_MS: u64 = 5_000; pub(crate) fn deadline() -> Result { Deadline::after(DEFAULT_FFI_TIMEOUT_MS) } -pub(crate) fn lease(adapter: &dyn PlatformAdapter) -> Result { +pub(crate) fn lease(adapter: &dyn PlatformAdapter) -> Result { + FfiLease::take(|| acquire(adapter)) +} + +fn acquire(adapter: &dyn PlatformAdapter) -> Result { let deadline = deadline()?; #[cfg(unix)] if let Some(raw_fd) = inherited_lease_fd()? { diff --git a/crates/windows/src/system/fixture/test_support.rs b/crates/windows/src/system/fixture/test_support.rs index 7628693ea3..c8aa4f104f 100644 --- a/crates/windows/src/system/fixture/test_support.rs +++ b/crates/windows/src/system/fixture/test_support.rs @@ -43,7 +43,7 @@ pub(crate) static FIXTURE_APP_NAME_LOCK: Mutex<()> = Mutex::new(()); pub(crate) static SHELL_SURFACE_LOCK: Mutex<()> = Mutex::new(()); /// Serializes every test that reaches the real, machine-global interaction -/// lease - `ProcessLeaseGuard`'s state is process-wide, so two lease +/// lease - `ProcessLeaseGuard`'s `AtomicBool` is process-wide, so two lease /// tests in different OS threads of the same `cargo test` binary contend on /// it even when each targets its own scratch lock-file root. Held for the /// entire body of any such test, never just around one call. diff --git a/crates/windows/src/system/interaction_lease/adoption_tests.rs b/crates/windows/src/system/interaction_lease/adoption_tests.rs index 9fa121ff69..26e189d13a 100644 --- a/crates/windows/src/system/interaction_lease/adoption_tests.rs +++ b/crates/windows/src/system/interaction_lease/adoption_tests.rs @@ -39,13 +39,9 @@ fn adoption_of_share_zero_handle_succeeds_and_still_blocks_a_fresh_acquire() { windows_sys::Win32::Foundation::CloseHandle(raw); } - let contender_root = root.clone(); - let contender = std::thread::spawn(move || { - acquire_at(&contender_root, Deadline::after(50).unwrap()).err() - }); - let error = match contender.join().unwrap() { - None => panic!("the adopted duplicate must still hold the lease exclusively"), - Some(error) => error, + let error = match acquire_at(&root, Deadline::after(50).unwrap()) { + Ok(_) => panic!("the adopted duplicate must still hold the lease exclusively"), + Err(error) => error, }; assert_eq!(error.code, ErrorCode::Timeout); diff --git a/crates/windows/src/system/interaction_lease/tests.rs b/crates/windows/src/system/interaction_lease/tests.rs index d6663d0fcd..e618b31bb8 100644 --- a/crates/windows/src/system/interaction_lease/tests.rs +++ b/crates/windows/src/system/interaction_lease/tests.rs @@ -121,8 +121,8 @@ fn cross_process_contention_times_out_with_lock_timeout_kind() { }); } -/// A second in-process acquire from another thread refuses through -/// `ProcessLeaseGuard` before the file is ever opened, which is a different shape from cross-process +/// A second in-process acquire refuses through `ProcessLeaseGuard` before the +/// file is ever opened, which is a different shape from cross-process /// contention: `CreateFileW` with `dwShareMode = 0` also refuses a second /// open from the *same* process, so asserting the file-lock kind here would /// be untestable - this proves the in-process guard is what actually fires. @@ -131,13 +131,9 @@ fn in_process_second_acquire_times_out_with_process_lock_kind() { with_interaction_lease_test_lock(|| { let root = scratch_root("in-process"); let first = acquire_at(&root, Deadline::after(1_000).unwrap()).unwrap(); - let contender_root = root.clone(); - let contender = std::thread::spawn(move || { - acquire_at(&contender_root, Deadline::after(50).unwrap()).err() - }); - let error = match contender.join().unwrap() { - None => panic!("in-process double acquire unexpectedly succeeded"), - Some(error) => error, + let error = match acquire_at(&root, Deadline::after(50).unwrap()) { + Ok(_) => panic!("in-process double acquire unexpectedly succeeded"), + Err(error) => error, }; assert_eq!(error.code, ErrorCode::Timeout); assert_eq!( @@ -205,15 +201,11 @@ fn success_path_reports_earned_contention_count() { fn success_path_includes_process_guard_contention() { with_interaction_lease_test_lock(|| { let root = scratch_root("process-guard-contention"); - let holder_root = root.clone(); - let (held, held_signal) = std::sync::mpsc::channel(); + let first = acquire_at(&root, Deadline::after(2_000).unwrap()).unwrap(); let releaser = std::thread::spawn(move || { - let first = acquire_at(&holder_root, Deadline::after(2_000).unwrap()).unwrap(); - held.send(()).unwrap(); std::thread::sleep(Duration::from_millis(80)); drop(first); }); - held_signal.recv().unwrap(); let lease = acquire_at(&root, Deadline::after(2_000).unwrap()).unwrap(); assert!( diff --git a/skills/agent-desktop-ffi/references/threading.md b/skills/agent-desktop-ffi/references/threading.md index 6ba597e7d9..594116a87a 100644 --- a/skills/agent-desktop-ffi/references/threading.md +++ b/skills/agent-desktop-ffi/references/threading.md @@ -20,7 +20,7 @@ finite deadline and do not take the interaction lease. | read + read | Both may run concurrently; neither waits for the interaction lease | | read + mutation | The read does not wait for the lease and may overlap the mutation; its result is a point-in-time observation, not a transaction | | mutation + mutation | One lease holder runs at a time for the same OS user; the waiter consumes its command deadline and returns a structured timeout if it cannot acquire the lease | -| mutation inside a mutation on the same thread (from a log callback) | Refused at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease` | +| mutation from a log callback during a mutation on the same thread | Refused at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease` | | native-handle call on another thread | Rejected with `AD_RESULT_ERR_INVALID_ARGS`; use a qualified ref instead | Snapshots, finds, gets, display/window/app listings, screenshots, clipboard @@ -82,11 +82,16 @@ to cross an async task or thread boundary. invoked from any thread that calls an `ad_*` function. The callback may itself call `ad_*` functions. Events those nested calls emit -are not delivered to the callback. While the call that logged is a mutation, its -thread holds the interaction lease, so a mutating call from the callback fails -at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind -`reentrant_interaction_lease` and `retryable: false`, instead of waiting for a -lease only its own thread can release. Observations from the callback still run. +are not delivered to the callback. A mutation made from the callback while the +call that logged is itself a mutation fails at once with +`AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease` and +`retryable: false`. Any other nested call that needs the interaction lease while +the call that logged holds it, including an observation that takes the lease +internally (for example to switch on a Chromium or Electron renderer's +accessibility), waits for a release that happens only after the callback +returns, and can time out. Do not make such calls from the callback; queue them +for after the outer call returns. Another host thread is unaffected and waits +for the lease as usual. A callback unregistered via `NULL` may still receive an invocation already in flight on another thread. Keep the callback and captured state alive for the From d8dab0565c6919fe65dc0790bc425713ead81bb7 Mon Sep 17 00:00:00 2001 From: gshost1 Date: Sun, 8 Nov 2026 06:09:23 -0800 Subject: [PATCH 4/5] fix(ffi): mark only a held lease and cover close_app ad_close_app takes its lease inside core with no mark, so a lease-taking call from a log callback during it, or a close from a callback during another mutation, still waited out the 5 s budget. It is now marked around the core call the way execute_by_ref is. The shared lease helper marked its thread before acquiring, so a thread still queued behind another thread's lease refused its own callback's mutation even though it held nothing. It now marks only after the lease is held. Core gives no hook at the moment it acquires, so execute_by_ref and close_app keep marking for the whole core call; that narrower over-refusal is documented. One marking type, set and cleared without the always-false save and restore. The docs and header now name the calls that take the lease through the FFI layer instead of promising every mutation. Tests cover the launch, execute_by_ref and close_app refusal paths and a thread still waiting for the lease, clear the callback and adapters through a drop guard even on panic, and skip when an inherited lease descriptor would route past the test adapter. --- .../docs/ffi/ownership-and-threading.mdx | 2 +- crates/ffi/include/agent_desktop.h | 23 +- crates/ffi/src/apps/close.rs | 6 + .../src/commands/execute_by_ref_timeout.rs | 2 +- crates/ffi/src/ffi_lease.rs | 12 +- crates/ffi/src/lease_marker.rs | 34 ++- crates/ffi/src/log_callback.rs | 23 +- .../ffi/src/log_callback_reentrancy_tests.rs | 257 +++++++++++++----- .../agent-desktop-ffi/references/threading.md | 29 +- 9 files changed, 271 insertions(+), 117 deletions(-) diff --git a/apps/docs/content/docs/ffi/ownership-and-threading.mdx b/apps/docs/content/docs/ffi/ownership-and-threading.mdx index 74e4cb3388..2b1817c0e2 100644 --- a/apps/docs/content/docs/ffi/ownership-and-threading.mdx +++ b/apps/docs/content/docs/ffi/ownership-and-threading.mdx @@ -56,7 +56,7 @@ Snapshots, finds, listings, screenshots, clipboard reads, status, and trace read - `ad_adapter_destroy` revokes the adapter. Calls already in flight finish; calls that start afterward return `AD_RESULT_ERR_INVALID_ARGS`. - `ad_wait` blocks its calling thread for at most `scope.timeout_ms`. -- The `ad_set_log_callback` callback may run on any thread that calls an `ad_*` function, concurrently, and may still fire briefly after you unregister it. Keep it alive for the process lifetime and never let it unwind across the C ABI. It may call `ad_*` functions itself; events from those nested calls are not delivered to it. A mutation from the callback while the call that logged is a mutation fails at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease`. Any other nested call that needs the interaction lock while the outer call holds it, including an observation that takes the lock internally, waits for a release that comes only after the callback returns and can time out, so do not make it from the callback. Other threads wait for the lock as usual. +- The `ad_set_log_callback` callback may run on any thread that calls an `ad_*` function, concurrently, and may still fire briefly after you unregister it. Keep it alive for the process lifetime and never let it unwind across the C ABI. It may call `ad_*` functions itself; events from those nested calls are not delivered to it. The calls that take the interaction lock through the FFI layer are `ad_mouse_event`, `ad_mouse_event_with_modifiers`, `ad_mouse_wheel`, `ad_drag`, `ad_set_clipboard`, `ad_clear_clipboard`, `ad_execute_action`, `ad_execute_action_with_policy`, `ad_execute_by_ref`, `ad_execute_by_ref_timeout`, `ad_launch_app_exact`, `ad_close_app`, `ad_focus_window_exact`, `ad_window_op_exact`, `ad_notification_action`, `ad_dismiss_notification` and `ad_dismiss_all_notifications`. One of them made from the callback while the call that logged is one of them and holds the lock fails at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease`; for `ad_execute_by_ref*` and `ad_close_app` as the call that logged, that holds for the whole call, including its work before the lock is taken. Any other nested call that needs the lock while the outer call holds it, including an observation that takes the lock internally, waits for a release that comes only after the callback returns and can time out, so do not make it from the callback. Other threads, including one still waiting for the lock, wait as usual. - A language runtime's global lock does not give thread affinity; keep native handles in thread-confined objects, or use refs. - On macOS, `ad_check_permissions` reports Accessibility trust for the host executable (`python3`, `node`, your app), not for the library. diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.h index 943b792152..f7c90f290b 100644 --- a/crates/ffi/include/agent_desktop.h +++ b/crates/ffi/include/agent_desktop.h @@ -1757,13 +1757,22 @@ AdResult ad_mouse_wheel(const struct AdAdapter *adapter, * invoke it once. * * The callback may call other `ad_*` functions. Events those nested calls emit - * are not delivered to it. A mutating call made from the callback while the - * call that logged is itself a mutation fails at once with - * `AD_RESULT_ERR_POLICY_DENIED` and details kind `reentrant_interaction_lease`. - * Any other nested call that needs the interaction lease while the call that - * logged holds it, including an observation that takes the lease internally, - * waits for a release that happens only after the callback returns, so it can - * time out. Do not make such calls from the callback. + * are not delivered to it. The calls that take the interaction lease through + * this library's FFI layer are `ad_mouse_event`, `ad_mouse_event_with_modifiers`, + * `ad_mouse_wheel`, `ad_drag`, `ad_set_clipboard`, `ad_clear_clipboard`, + * `ad_execute_action`, `ad_execute_action_with_policy`, `ad_execute_by_ref`, + * `ad_execute_by_ref_timeout`, `ad_launch_app_exact`, `ad_close_app`, + * `ad_focus_window_exact`, `ad_window_op_exact`, `ad_notification_action`, + * `ad_dismiss_notification` and `ad_dismiss_all_notifications`. One of these + * made from the callback while the call that logged is one of them and holds + * the lease fails at once with `AD_RESULT_ERR_POLICY_DENIED` and details kind + * `reentrant_interaction_lease`. For `ad_execute_by_ref*` and `ad_close_app` + * as the call that logged, the refusal applies for the whole call, including + * its work before the lease is taken. Any other nested call that needs the + * lease while the call that logged holds it, including an observation that + * takes the lease internally, waits for a release that happens only after the + * callback returns, so it can time out. Do not make such calls from the + * callback. * * The message pointer is valid only until the callback returns. The callback * must not unwind across this C ABI boundary; C++ exceptions and Rust panics diff --git a/crates/ffi/src/apps/close.rs b/crates/ffi/src/apps/close.rs index f4639a0a99..97ca83e4ee 100644 --- a/crates/ffi/src/apps/close.rs +++ b/crates/ffi/src/apps/close.rs @@ -29,6 +29,12 @@ pub unsafe extern "C" fn ad_close_app( } }; let adapter = crate::adapter::acquire_adapter!(adapter); + let _lease_marker = match crate::lease_marker::mark_core_mutation() { + Ok(marker) => marker, + Err(error) => { + return set_last_error(&error); + } + }; match agent_desktop_core::commands::close_app::execute( agent_desktop_core::commands::close_app::CloseAppArgs { app: id_str, force }, adapter.inner.as_ref(), diff --git a/crates/ffi/src/commands/execute_by_ref_timeout.rs b/crates/ffi/src/commands/execute_by_ref_timeout.rs index 7ddc257977..4fedf25e16 100644 --- a/crates/ffi/src/commands/execute_by_ref_timeout.rs +++ b/crates/ffi/src/commands/execute_by_ref_timeout.rs @@ -73,7 +73,7 @@ pub unsafe extern "C" fn ad_execute_by_ref_timeout( let caller_ip = caller_policy.to_interaction_policy(); let adapter_ref = crate::adapter::acquire_adapter!(adapter); - let _lease_marker = match crate::lease_marker::LeaseMarker::enter() { + let _lease_marker = match crate::lease_marker::mark_core_mutation() { Ok(marker) => marker, Err(error) => { return set_last_error(&error); diff --git a/crates/ffi/src/ffi_lease.rs b/crates/ffi/src/ffi_lease.rs index 28be89f588..f1735b5592 100644 --- a/crates/ffi/src/ffi_lease.rs +++ b/crates/ffi/src/ffi_lease.rs @@ -2,7 +2,7 @@ use std::ops::Deref; use agent_desktop_core::{AdapterError, InteractionLease}; -use crate::lease_marker::LeaseMarker; +use crate::lease_marker::{LeaseMarker, refuse_reentrant_mutation}; /// An interaction lease taken by an FFI operation, with this thread marked as holding it for as long as /// the lease lives. @@ -12,14 +12,16 @@ pub(crate) struct FfiLease { } impl FfiLease { - /// Marks this thread, then takes the lease with `acquire`. A refused mark returns before `acquire` runs. + /// Takes the lease with `acquire` and marks this thread once it is held, so a thread still waiting for + /// another thread's lease is not marked. A reentrant mutation is refused before `acquire` runs. pub(crate) fn take( acquire: impl FnOnce() -> Result, ) -> Result { - let marker = LeaseMarker::enter()?; + refuse_reentrant_mutation()?; + let lease = acquire()?; Ok(Self { - lease: acquire()?, - _marker: marker, + lease, + _marker: LeaseMarker::hold(), }) } } diff --git a/crates/ffi/src/lease_marker.rs b/crates/ffi/src/lease_marker.rs index 2298090267..6962f9e378 100644 --- a/crates/ffi/src/lease_marker.rs +++ b/crates/ffi/src/lease_marker.rs @@ -6,30 +6,40 @@ thread_local! { static OPERATION_HOLDS_LEASE: Cell = const { Cell::new(false) }; } -/// Marks this thread's running FFI operation as holding, or about to take, the interaction lease, until it -/// is dropped. A mutating call made from a log callback while the mark is set is refused instead of waiting -/// for a lease that only the callback's own thread can release. +/// Marks this thread's running FFI operation as holding the interaction lease until it is dropped. pub(crate) struct LeaseMarker { - previous: bool, + _private: (), } impl LeaseMarker { - pub(crate) fn enter() -> Result { - if crate::log_callback::in_callback() && OPERATION_HOLDS_LEASE.get() { - return Err(reentrant()); - } - Ok(Self { - previous: OPERATION_HOLDS_LEASE.replace(true), - }) + pub(crate) fn hold() -> Self { + OPERATION_HOLDS_LEASE.set(true); + Self { _private: () } } } impl Drop for LeaseMarker { fn drop(&mut self) { - OPERATION_HOLDS_LEASE.set(self.previous); + OPERATION_HOLDS_LEASE.set(false); } } +/// Refuses a mutation started from a log callback while this thread's running FFI operation holds the +/// interaction lease, which only this thread can release once the callback returns. +pub(crate) fn refuse_reentrant_mutation() -> Result<(), AdapterError> { + if crate::log_callback::in_callback() && OPERATION_HOLDS_LEASE.get() { + return Err(reentrant()); + } + Ok(()) +} + +/// Marks a mutation whose lease core takes internally. Core offers no hook at the moment it acquires, +/// so the mark covers the whole call, including the work before the lease is taken. +pub(crate) fn mark_core_mutation() -> Result { + refuse_reentrant_mutation()?; + Ok(LeaseMarker::hold()) +} + fn reentrant() -> AdapterError { AdapterError::new( ErrorCode::PolicyDenied, diff --git a/crates/ffi/src/log_callback.rs b/crates/ffi/src/log_callback.rs index 2d79a99d5f..79e58091c4 100644 --- a/crates/ffi/src/log_callback.rs +++ b/crates/ffi/src/log_callback.rs @@ -134,13 +134,22 @@ pub(crate) fn with_dispatch(body: impl FnOnce() -> R) -> R { /// invoke it once. /// /// The callback may call other `ad_*` functions. Events those nested calls emit -/// are not delivered to it. A mutating call made from the callback while the -/// call that logged is itself a mutation fails at once with -/// `AD_RESULT_ERR_POLICY_DENIED` and details kind `reentrant_interaction_lease`. -/// Any other nested call that needs the interaction lease while the call that -/// logged holds it, including an observation that takes the lease internally, -/// waits for a release that happens only after the callback returns, so it can -/// time out. Do not make such calls from the callback. +/// are not delivered to it. The calls that take the interaction lease through +/// this library's FFI layer are `ad_mouse_event`, `ad_mouse_event_with_modifiers`, +/// `ad_mouse_wheel`, `ad_drag`, `ad_set_clipboard`, `ad_clear_clipboard`, +/// `ad_execute_action`, `ad_execute_action_with_policy`, `ad_execute_by_ref`, +/// `ad_execute_by_ref_timeout`, `ad_launch_app_exact`, `ad_close_app`, +/// `ad_focus_window_exact`, `ad_window_op_exact`, `ad_notification_action`, +/// `ad_dismiss_notification` and `ad_dismiss_all_notifications`. One of these +/// made from the callback while the call that logged is one of them and holds +/// the lease fails at once with `AD_RESULT_ERR_POLICY_DENIED` and details kind +/// `reentrant_interaction_lease`. For `ad_execute_by_ref*` and `ad_close_app` +/// as the call that logged, the refusal applies for the whole call, including +/// its work before the lease is taken. Any other nested call that needs the +/// lease while the call that logged holds it, including an observation that +/// takes the lease internally, waits for a release that happens only after the +/// callback returns, so it can time out. Do not make such calls from the +/// callback. /// /// The message pointer is valid only until the callback returns. The callback /// must not unwind across this C ABI boundary; C++ exceptions and Rust panics diff --git a/crates/ffi/src/log_callback_reentrancy_tests.rs b/crates/ffi/src/log_callback_reentrancy_tests.rs index db0e380415..389ef9c152 100644 --- a/crates/ffi/src/log_callback_reentrancy_tests.rs +++ b/crates/ffi/src/log_callback_reentrancy_tests.rs @@ -1,24 +1,30 @@ use std::cell::{Cell, RefCell}; -use std::ffi::{CStr, c_char}; +use std::ffi::{CStr, CString, c_char}; +use std::sync::MutexGuard; use std::thread::JoinHandle; use std::time::{Duration, Instant}; use agent_desktop_core::{ - ActionOps, AdapterError, Deadline, DisplayInfo, InputOps, InteractionLease, MouseEvent, - ObservationOps, OperationReport, ProcessLeaseGuard, SystemOps, + ActionOps, AdapterError, Deadline, DisplayInfo, INTERACTION_LEASE_FD_ENV, InputOps, + InteractionLease, MouseEvent, ObservationOps, OperationReport, ProcessLeaseGuard, SystemOps, }; use super::ad_set_log_callback; use crate::adapter::{AdAdapter, ad_adapter_destroy, register_adapter}; +use crate::apps::close::ad_close_app; +use crate::apps::launch::ad_launch_app_exact; +use crate::commands::execute_by_ref_timeout::ad_execute_by_ref_timeout; use crate::displays::list::ad_list_displays; use crate::error::{AdResult, ad_last_error_details}; +use crate::input::clipboard::ad_free_string; use crate::input::mouse::ad_mouse_event; -use crate::types::{AdMouseEvent, AdPoint}; +use crate::types::{AdAction, AdExactWindowInfo, AdMouseEvent, AdPoint}; const CALLBACK_HOLD: Duration = Duration::from_millis(150); struct LoggingAdapter { takes_process_lease: bool, + logs_while_acquiring: bool, } impl ObservationOps for LoggingAdapter {} @@ -30,6 +36,9 @@ impl SystemOps for LoggingAdapter { &self, deadline: Deadline, ) -> Result { + if self.logs_while_acquiring { + tracing::warn!(operation = "acquire_interaction_lease"); + } if self.takes_process_lease { return InteractionLease::guarded(deadline, ProcessLeaseGuard::acquire(deadline)?); } @@ -53,13 +62,70 @@ impl InputOps for LoggingAdapter { } } -type TimedCall = (AdResult, Duration); +type InnerCall = (AdResult, Duration, String); +type ContenderOutcome = (AdResult, Duration, Option); +type Action = fn(*mut AdAdapter); thread_local! { - static ARMED_ADAPTER: Cell<*mut AdAdapter> = const { Cell::new(std::ptr::null_mut()) }; + static ARMED: Cell> = const { Cell::new(None) }; static CALLBACK_RUNS: Cell = const { Cell::new(0) }; - static INNER_CALL: RefCell> = const { RefCell::new(None) }; - static CONTENDER: RefCell>> = const { RefCell::new(None) }; + static INNER_CALL: RefCell> = const { RefCell::new(None) }; + static SECOND_ADAPTER: Cell = const { Cell::new(0) }; + static CONTENDER: RefCell>> = const { RefCell::new(None) }; +} + +unsafe extern "C" fn run_armed_action(_level: i32, _message: *const c_char) { + CALLBACK_RUNS.set(CALLBACK_RUNS.get().saturating_add(1)); + if let Some((action, adapter)) = ARMED.take() { + action(adapter); + } +} + +struct LoggingSession { + adapters: Vec<*mut AdAdapter>, + _serial: MutexGuard<'static, ()>, +} + +impl LoggingSession { + fn start() -> Option { + if std::env::var_os(INTERACTION_LEASE_FD_ENV).is_some() { + eprintln!( + "skipped: {INTERACTION_LEASE_FD_ENV} routes FFI leases past the test adapter" + ); + return None; + } + let session = Self { + adapters: Vec::new(), + _serial: super::tests::log_test_serialization(), + }; + CALLBACK_RUNS.set(0); + assert_eq!(ad_set_log_callback(Some(run_armed_action)), AdResult::Ok); + Some(session) + } + + fn adapter(&mut self, takes_process_lease: bool, logs_while_acquiring: bool) -> *mut AdAdapter { + let adapter = register_adapter(AdAdapter { + inner: Box::new(LoggingAdapter { + takes_process_lease, + logs_while_acquiring, + }), + session_id: None, + _session_lease: None, + }) + .unwrap(); + self.adapters.push(adapter); + adapter + } +} + +impl Drop for LoggingSession { + fn drop(&mut self) { + let _ = ad_set_log_callback(None); + ARMED.set(None); + for adapter in self.adapters.drain(..) { + unsafe { ad_adapter_destroy(adapter) }; + } + } } fn move_event() -> AdMouseEvent { @@ -71,6 +137,10 @@ fn move_event() -> AdMouseEvent { } } +fn mouse_event(adapter: *mut AdAdapter) -> AdResult { + unsafe { ad_mouse_event(adapter, &move_event()) } +} + fn last_error_kind() -> String { let details = ad_last_error_details(); if details.is_null() { @@ -83,61 +153,68 @@ fn last_error_kind() -> String { .unwrap_or_default() } -fn timed_mouse_event(adapter: *mut AdAdapter) -> TimedCall { - let event = move_event(); +fn record(call: impl FnOnce() -> AdResult) { let started = Instant::now(); - let result = unsafe { ad_mouse_event(adapter, &event) }; - (result, started.elapsed()) + let result = call(); + let elapsed = started.elapsed(); + INNER_CALL.set(Some((result, elapsed, last_error_kind()))); } -unsafe extern "C" fn reenter(_level: i32, _message: *const c_char) { - CALLBACK_RUNS.set(CALLBACK_RUNS.get().saturating_add(1)); - let adapter = ARMED_ADAPTER.replace(std::ptr::null_mut()); - if adapter.is_null() { - return; - } - let (result, elapsed) = timed_mouse_event(adapter); - INNER_CALL.set(Some((result, elapsed, last_error_kind()))); +fn reenter_mouse_event(adapter: *mut AdAdapter) { + record(|| mouse_event(adapter)); } -unsafe extern "C" fn start_contender(_level: i32, _message: *const c_char) { - let adapter = ARMED_ADAPTER.replace(std::ptr::null_mut()); - if adapter.is_null() { - return; - } - let address = adapter.expose_provenance(); - let contender = std::thread::spawn(move || { - timed_mouse_event(std::ptr::with_exposed_provenance_mut(address)) +fn reenter_launch_app_exact(adapter: *mut AdAdapter) { + let id = CString::new("org.example.app").unwrap(); + let mut out: AdExactWindowInfo = unsafe { std::mem::zeroed() }; + record(|| unsafe { ad_launch_app_exact(adapter, id.as_ptr(), 1_000, &mut out) }); +} + +fn reenter_execute_by_ref_timeout(adapter: *mut AdAdapter) { + let ref_id = CString::new("@s8f3k2p9:e1").unwrap(); + let action: AdAction = unsafe { std::mem::zeroed() }; + let mut out: *mut c_char = std::ptr::null_mut(); + record(|| unsafe { + ad_execute_by_ref_timeout(adapter, ref_id.as_ptr(), &action, 0, -1, &mut out) }); + unsafe { ad_free_string(out) }; +} + +fn reenter_close_app(adapter: *mut AdAdapter) { + let id = CString::new("org.example.app").unwrap(); + record(|| unsafe { ad_close_app(adapter, id.as_ptr(), false) }); +} + +fn spawn_contender(address: usize, inner: Option) -> JoinHandle { + std::thread::spawn(move || { + let adapter = std::ptr::with_exposed_provenance_mut(address); + ARMED.set(inner.map(|action| (action, adapter))); + let started = Instant::now(); + let result = mouse_event(adapter); + (result, started.elapsed(), INNER_CALL.take()) + }) +} + +fn start_contender(adapter: *mut AdAdapter) { + CONTENDER.set(Some(spawn_contender(adapter.expose_provenance(), None))); + std::thread::sleep(CALLBACK_HOLD); +} + +fn start_waiting_reentrant_contender(_adapter: *mut AdAdapter) { + let contender = spawn_contender(SECOND_ADAPTER.get(), Some(reenter_mouse_event)); CONTENDER.set(Some(contender)); std::thread::sleep(CALLBACK_HOLD); } -fn with_logging_adapter( - takes_process_lease: bool, - callback: unsafe extern "C" fn(i32, *const c_char), - outer_call: impl FnOnce(*mut AdAdapter) -> R, -) -> R { - let _serial = super::tests::log_test_serialization(); - let adapter = register_adapter(AdAdapter { - inner: Box::new(LoggingAdapter { - takes_process_lease, - }), - session_id: None, - _session_lease: None, - }) - .unwrap(); - CALLBACK_RUNS.set(0); - assert_eq!(ad_set_log_callback(Some(callback)), AdResult::Ok); - ARMED_ADAPTER.set(adapter); - let outer = outer_call(adapter); - ARMED_ADAPTER.set(std::ptr::null_mut()); - assert_eq!(ad_set_log_callback(None), AdResult::Ok); - unsafe { ad_adapter_destroy(adapter) }; - outer -} - -fn inner_call() -> (AdResult, Duration, String) { +fn joined_contender() -> ContenderOutcome { + CONTENDER + .take() + .expect("the log callback must start the contender inside the outer call") + .join() + .unwrap() +} + +fn inner_call() -> InnerCall { INNER_CALL .take() .expect("the log callback must run inside the outer call") @@ -145,10 +222,13 @@ fn inner_call() -> (AdResult, Duration, String) { #[test] fn a_log_callback_can_call_back_into_the_library() { - let outer = with_logging_adapter(false, reenter, |adapter| unsafe { - let mut displays = std::ptr::null_mut(); - ad_list_displays(adapter, &mut displays) - }); + let Some(mut session) = LoggingSession::start() else { + return; + }; + let adapter = session.adapter(false, false); + ARMED.set(Some((reenter_mouse_event, adapter))); + let mut displays = std::ptr::null_mut(); + let outer = unsafe { ad_list_displays(adapter, &mut displays) }; let (inner, elapsed, kind) = inner_call(); assert_eq!(inner, AdResult::Ok, "kind {kind:?} after {elapsed:?}"); assert_ne!(outer, AdResult::ErrInternal); @@ -156,27 +236,58 @@ fn a_log_callback_can_call_back_into_the_library() { } #[test] -fn a_mutation_from_a_log_callback_inside_a_mutation_is_refused_at_once() { - let outer = with_logging_adapter(true, reenter, |adapter| unsafe { - ad_mouse_event(adapter, &move_event()) - }); - let (inner, elapsed, kind) = inner_call(); - assert_eq!(outer, AdResult::Ok); - assert_eq!(inner, AdResult::ErrPolicyDenied, "after {elapsed:?}"); - assert_eq!(kind, "reentrant_interaction_lease"); - assert!(elapsed < Duration::from_millis(100), "took {elapsed:?}"); +fn every_lease_taking_mutation_from_a_log_callback_inside_a_mutation_is_refused_at_once() { + let entry_points: [(&str, Action); 4] = [ + ("ad_mouse_event", reenter_mouse_event), + ("ad_launch_app_exact", reenter_launch_app_exact), + ("ad_execute_by_ref_timeout", reenter_execute_by_ref_timeout), + ("ad_close_app", reenter_close_app), + ]; + for (name, action) in entry_points { + let Some(mut session) = LoggingSession::start() else { + return; + }; + let adapter = session.adapter(true, false); + ARMED.set(Some((action, adapter))); + let outer = mouse_event(adapter); + let (inner, elapsed, kind) = inner_call(); + assert_eq!(outer, AdResult::Ok, "{name}"); + assert_eq!(inner, AdResult::ErrPolicyDenied, "{name} after {elapsed:?}"); + assert_eq!(kind, "reentrant_interaction_lease", "{name}"); + assert!( + elapsed < Duration::from_millis(100), + "{name} took {elapsed:?}" + ); + } } #[test] fn another_thread_waits_for_the_lease_a_logging_mutation_holds() { - let (outer, (result, waited)) = with_logging_adapter(true, start_contender, |adapter| { - let outer = unsafe { ad_mouse_event(adapter, &move_event()) }; - let contender = CONTENDER - .take() - .expect("the log callback must start the contender inside the outer call"); - (outer, contender.join().unwrap()) - }); + let Some(mut session) = LoggingSession::start() else { + return; + }; + let adapter = session.adapter(true, false); + ARMED.set(Some((start_contender, adapter))); + let outer = mouse_event(adapter); + let (result, waited, _) = joined_contender(); assert_eq!(outer, AdResult::Ok); assert_eq!(result, AdResult::Ok, "after {waited:?}"); assert!(waited >= CALLBACK_HOLD / 2, "waited only {waited:?}"); } + +#[test] +fn a_thread_still_waiting_for_the_lease_is_not_refused_from_its_callback() { + let Some(mut session) = LoggingSession::start() else { + return; + }; + let holder = session.adapter(true, false); + let waiter = session.adapter(true, true); + SECOND_ADAPTER.set(waiter.expose_provenance()); + ARMED.set(Some((start_waiting_reentrant_contender, holder))); + let outer = mouse_event(holder); + let (result, waited, inner) = joined_contender(); + let (inner, inner_elapsed, kind) = inner.expect("the waiting thread's callback must run"); + assert_eq!(outer, AdResult::Ok); + assert_eq!(inner, AdResult::Ok, "kind {kind:?} after {inner_elapsed:?}"); + assert_eq!(result, AdResult::Ok, "after {waited:?}"); +} diff --git a/skills/agent-desktop-ffi/references/threading.md b/skills/agent-desktop-ffi/references/threading.md index 594116a87a..1151e5c726 100644 --- a/skills/agent-desktop-ffi/references/threading.md +++ b/skills/agent-desktop-ffi/references/threading.md @@ -20,7 +20,7 @@ finite deadline and do not take the interaction lease. | read + read | Both may run concurrently; neither waits for the interaction lease | | read + mutation | The read does not wait for the lease and may overlap the mutation; its result is a point-in-time observation, not a transaction | | mutation + mutation | One lease holder runs at a time for the same OS user; the waiter consumes its command deadline and returns a structured timeout if it cannot acquire the lease | -| mutation from a log callback during a mutation on the same thread | Refused at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease` | +| lease-taking call from a log callback while the same thread's lease-taking call holds the lease | Refused at once with `AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease`; see Log callback threading for the list | | native-handle call on another thread | Rejected with `AD_RESULT_ERR_INVALID_ARGS`; use a qualified ref instead | Snapshots, finds, gets, display/window/app listings, screenshots, clipboard @@ -82,16 +82,23 @@ to cross an async task or thread boundary. invoked from any thread that calls an `ad_*` function. The callback may itself call `ad_*` functions. Events those nested calls emit -are not delivered to the callback. A mutation made from the callback while the -call that logged is itself a mutation fails at once with -`AD_RESULT_ERR_POLICY_DENIED`, details kind `reentrant_interaction_lease` and -`retryable: false`. Any other nested call that needs the interaction lease while -the call that logged holds it, including an observation that takes the lease -internally (for example to switch on a Chromium or Electron renderer's -accessibility), waits for a release that happens only after the callback -returns, and can time out. Do not make such calls from the callback; queue them -for after the outer call returns. Another host thread is unaffected and waits -for the lease as usual. +are not delivered to the callback. + +These calls take the interaction lease through the FFI layer: `ad_mouse_event`, `ad_mouse_event_with_modifiers`, `ad_mouse_wheel`, `ad_drag`, `ad_set_clipboard`, `ad_clear_clipboard`, `ad_execute_action`, `ad_execute_action_with_policy`, `ad_execute_by_ref`, `ad_execute_by_ref_timeout`, `ad_launch_app_exact`, `ad_close_app`, `ad_focus_window_exact`, `ad_window_op_exact`, `ad_notification_action`, `ad_dismiss_notification` and `ad_dismiss_all_notifications`. +One of them made from the callback while the call that logged is one of them +and holds the lease fails at once with `AD_RESULT_ERR_POLICY_DENIED`, details +kind `reentrant_interaction_lease` and `retryable: false`. When the call that +logged is `ad_execute_by_ref*` or `ad_close_app`, whose lease core takes +internally, the refusal covers the whole call, including the auto-wait and ref +resolution before the lease is taken. + +Any other nested call that needs the interaction lease while the call that +logged holds it, including an observation that takes the lease internally (for +example to switch on a Chromium or Electron renderer's accessibility), waits +for a release that happens only after the callback returns, and can time out. +Do not make such calls from the callback; queue them for after the outer call +returns. Another host thread, or a thread still waiting for the lease, is not +refused and waits for the lease as usual. A callback unregistered via `NULL` may still receive an invocation already in flight on another thread. Keep the callback and captured state alive for the From bbcd9aa6bfbe43e2578b9f57b69fd9aca7a3796f Mon Sep 17 00:00:00 2001 From: gshost1 Date: Sun, 8 Nov 2026 06:36:13 -0800 Subject: [PATCH 5/5] test(ffi): read the inherited lease fd variable only on Unix INTERACTION_LEASE_FD_ENV is exported by core only on Unix, so the reentrancy tests did not compile on the Windows CI jobs. --- crates/ffi/src/log_callback_reentrancy_tests.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/crates/ffi/src/log_callback_reentrancy_tests.rs b/crates/ffi/src/log_callback_reentrancy_tests.rs index 389ef9c152..fefcb5fdbc 100644 --- a/crates/ffi/src/log_callback_reentrancy_tests.rs +++ b/crates/ffi/src/log_callback_reentrancy_tests.rs @@ -5,8 +5,8 @@ use std::thread::JoinHandle; use std::time::{Duration, Instant}; use agent_desktop_core::{ - ActionOps, AdapterError, Deadline, DisplayInfo, INTERACTION_LEASE_FD_ENV, InputOps, - InteractionLease, MouseEvent, ObservationOps, OperationReport, ProcessLeaseGuard, SystemOps, + ActionOps, AdapterError, Deadline, DisplayInfo, InputOps, InteractionLease, MouseEvent, + ObservationOps, OperationReport, ProcessLeaseGuard, SystemOps, }; use super::ad_set_log_callback; @@ -88,10 +88,9 @@ struct LoggingSession { impl LoggingSession { fn start() -> Option { - if std::env::var_os(INTERACTION_LEASE_FD_ENV).is_some() { - eprintln!( - "skipped: {INTERACTION_LEASE_FD_ENV} routes FFI leases past the test adapter" - ); + #[cfg(unix)] + if std::env::var_os(agent_desktop_core::INTERACTION_LEASE_FD_ENV).is_some() { + eprintln!("skipped: an inherited lease fd routes FFI leases past the test adapter"); return None; } let session = Self {