Skip to content

fix(ffi): let a log callback call back in, and refuse a reentrant mutation at once - #55

Merged
gshost1 merged 7 commits into
mainfrom
fix/process-lease-reentrancy
Nov 8, 2026
Merged

gshost1 merged 7 commits into
mainfrom
fix/process-lease-reentrancy

Conversation

@gshost1

@gshost1 gshost1 commented Nov 8, 2026 •

Copy link
Copy Markdown
Owner

Two linked bugs on the FFI path where a host log callback calls back into the library on the same thread. Ledger rows STATE-21 (found while fixing) and STATE-17.

  • STATE-21: an ad_* call made from inside a host log callback panicked in tracing (RefCell already borrowed, from tracing-core's dispatcher), because the inner call tried to install its own dispatcher while the outer event delivery still held it. trap_panic turned it into AD_RESULT_ERR_INTERNAL with panic noise on stderr.
  • STATE-17: once that no longer panics, a mutation from the callback while the same thread's outer call holds the interaction lease waits on the process lease guard until its deadline (5 s for FFI) and fails with TIMEOUT interaction_process_lock_timeout, a self-deadlock bounded only by the timeout.

State before and after

nested call from a log callback
before: callback -> ad_* -> install dispatcher -> tracing panics -> AD_RESULT_ERR_INTERNAL
after:  callback -> ad_* -> runs with no dispatcher installed (its own log events are dropped)

mutation from a callback (same thread)
before: outer call holds the lease -> callback -> mutation -> waits on the guard -> TIMEOUT after 5 s
after:  outer call holds the lease (thread marked) -> callback -> mutation
            -> POLICY_DENIED reentrant_interaction_lease, at once, not_delivered
        other threads (including one still waiting for the lease): unchanged, they wait

The core lease guard is unchanged (a first version keyed it on the owning thread; review showed Linux's stale-input sweep hands the guard to a worker thread, so that design refused a legitimate wait).

What changed

  • crates/ffi/src/log_callback.rs: with_dispatch installs no dispatcher while IN_CALLBACK is set, checking the thread-local before the callback mutex.
  • crates/ffi/src/lease_marker.rs (new): a per-thread mark, "this thread's FFI operation holds the interaction lease". LeaseMarker::hold() is the only setter and refuse_reentrant_mutation() the only check.
  • crates/ffi/src/ffi_lease.rs (new): FfiLease::take checks, acquires, then marks; operation::lease returns it, so every interaction_lease! caller is covered; apps/launch.rs uses it.
  • ad_execute_by_ref* and ad_close_app, whose lease core takes internally, are marked around the core call (mark_core_mutation()).
  • Error: POLICY_DENIED, details {"kind": "reentrant_interaction_lease", "retryable": false}, disposition not_delivered, with a suggestion for the callback case; retryable: false suppresses PolicyDenied's headless recovery hint. No new ErrorCode.
  • Docs: the ad_set_log_callback doc comment (C header regenerated), apps/docs/.../ownership-and-threading.mdx and skills/agent-desktop-ffi/references/threading.md list the 17 calls refused from a callback during a mutation (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, ad_dismiss_all_notifications), and say anything else that needs the lease waits and can time out.

How tested

Variant (fix broken on purpose) Test that fails
Reentrancy check removed table test over ad_mouse_event, ad_launch_app_exact, ad_execute_by_ref_timeout, ad_close_app (ad_mouse_event after 5.000237716s left: ErrTimeout right: ErrPolicyDenied)
FfiLease marks before acquiring a_thread_still_waiting_for_the_lease_is_not_refused_from_its_callback
close_app or execute_by_ref unmarked the table test, on that call
main's with_dispatch a_log_callback_can_call_back_into_the_library, the waiting-thread test, the table test (ErrInternal, the tracing panic)

Also kept: another_thread_waits_for_the_lease_a_logging_mutation_holds. A LoggingSession guard restores the global callback and destroys the adapters even on panic; the tests skip if AGENT_DESKTOP_INTERACTION_LEASE_FD is set.

Gates on head d8dab056 (main merged in), then on bbcd9aa6 (adds the Unix-only gate for the inherited lease fd variable, which broke the Windows CI compile; the FFI tests now also type-check for x86_64-pc-windows-msvc locally): fmt, clippy -D warnings, source-rule and architecture scripts, core Windows check, Win32 leakage check, cargo tree, host-set tests 4904 passed, 0 failed on both; CI 27/27 green on bbcd9aa6; pre-commit hooks including the cbindgen header drift check.

Review: two rounds (high, medium). Round 1 moved the check from core to FFI; round 2 covered ad_close_app, marked only while held, and added the table and waiting-thread tests.

Performance

One thread-local read per FFI mutation; the callback check reads the thread-local before the callback mutex.

Risks

  • A future FFI entry point whose lease core takes internally must call mark_core_mutation(); otherwise a callback mutation during it waits 5 s instead of being refused.
  • During ad_execute_by_ref* and ad_close_app, a lease-taking call from the callback is refused even before core has taken the lease (auto-wait, ref resolution); documented.
  • Log events from a nested call inside a log callback are dropped.

What's left

Merge rule: rule 3. Since this head's base 9ea5d145, main moved to 950abe84 through PR #57 (src/main.rs, src/tests/main_tests.rs) and Mac-session PRs (macOS and e2e files); none overlaps this PR's files and none is an always-overlap file. main CI on 950abe84 green. Prior art: none upstream.

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.
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.
gshost1 added a commit that referenced this pull request Nov 8, 2026
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.
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.
@gshost1 gshost1 changed the title fix(ffi): let a log callback call back in, and refuse a same-thread lease at once fix(ffi): let a log callback call back in, and refuse a reentrant mutation at once Nov 8, 2026
INTERACTION_LEASE_FD_ENV is exported by core only on Unix, so the
reentrancy tests did not compile on the Windows CI jobs.
@gshost1
gshost1 merged commit e50786e into main Nov 8, 2026
27 checks passed
@gshost1
gshost1 deleted the fix/process-lease-reentrancy branch November 8, 2026 16:08
gshost1 added a commit that referenced this pull request Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant