fix(android): keep close --shutdown's IME restore out of the settings flush window

Merged
TH
2mo ago
+990-50

Summary

close --shutdown left an Android emulator restarted with the agent-device test IME as its default keyboard (#3318). The restore itself succeeded — default_input_method read back correctly while the emulator was still running — but AOSP's SettingsProvider persists setting changes asynchronously (delayed XML flush, capped at 2 s in SettingsState.java), and the close finalizer ran adb emu kill immediately, before settings_secure.xml was rewritten. The reboot reloaded the stale file with the helper IME still default.

The fix, enforced at both ends of the hazard: the one inner function that issues a restore’s ime set registers the device’s flush window (write + 2.5 s, timed on a monotonic per-serial clock — the window is a property of the device’s SettingsProvider, not of any host state dir) in the registrar’s finally for every issued emulator write whatever the outcome, because a readback mismatch cannot prove the provider never accepted the write; and the one executor of adb emu kill waits that window out before killing. Whether a write confirmed by read-back is a separate fact the mark carries, and it gates only one decision: whether an uninspected close may retire another session’s durable recovery marker. So every kill path is gated — close --shutdown, the standalone shutdown command, and any future caller. A close cancelled mid-wait never reaches the kill and hands the remaining window to the next kill-bound caller; overlapping windows coalesce into one wait because the provider rewrites the whole settings file per flush. Touched files: 10.

Validation

Per-head validation lives in comments: the latest validation comment records the tested head and its results (pnpm check:affected --run, pnpm typecheck, pnpm fallow audit --base origin/main). New regression tests pin: restore-before-kill ordering with an awaited deferred restore, the flush deadline with signal forwarding, the marker surviving the settle, an abort mid-settle retaining marker + window with the retry consuming the remaining wait, coalescing of overlapping windows into a single wait, a cross-session kill-bound close waiting a window another close registered, a never-activated close leaving a retained marker untouched, a never-activated close covering an issued-but-unconfirmed window killing but keeping the marker, no settle on ordinary close / physical-device / failed-restore paths, the kill-site gate (kill waits a registered window / skips with none / abort never reaches adb emu kill), and startup-orphan recovery registering the window while paying no boot sleep.

Live device evidence: on an arm64 API 35 (google_apis) emulator, head cycles run open com.android.settings --relaunch (helper becomes default) → close --shutdown (~2.9 s, settle included) → -no-snapshot-load restart → LatinIME, 5/5. The base commit was then run on the same AVD as a control and does not reproduce there either (LatinIME 3/3, close in ~0.3 s), so this emulator cannot discriminate the fix — it proves no new breakage only. The reproduction stands on the reporter's platforms (API 32/37 x86_64). Falsification of the hazard itself on this image: a helper ime set followed by SIGKILL of qemu within ~1 s did strand the helper across restart, confirming the lost-flush window exists here too; graceful adb emu kill just usually wins the race on this fast image. A base run on API 32/37 is the missing discriminator and needs a provisioned AVD on those images.

Review history, with the defects each round found in shipped code: round one resolved three blocking findings (test type errors, format gate, abort-signal gap in the settle); round two found that an aborted settle still cleared the marker, letting a retry kill inside the flush window (10b4126e5); round three found that round-two's refactor routed the never-activated close through the shared marker clear, erasing a retained orphan marker (6c5221baf, split not-activated-here from no-record at the reason type); round four (cubic) found the double-window lock hold in the round-two/three design, fixed by coalescing to one deadline (3bbda232d); round five (independent review) found that an ordinary close registered no window, leaving a second session's close --shutdown free to kill inside the flush window — every confirmed restore now registers its window, and the kill-bound predicate has a single owner (fcf968b22); round six (cubic) found that daemon-startup orphan recovery called the inner restore directly and registered no window, and that the standalone shutdown command's kill was never gated by any close-side wait — registration moved inside the inner restore and the flush hold moved to the kill-site itself (83e78a7b8); round seven (cubic) found that the window guard timed itself on the wall clock, letting a forward host-clock step release the kill inside the flush window — the window is now timed on the process monotonic clock — encoded in the map name, testImeLastRestoreAtPerfMs — and the kill-site wait tests assert the derived magnitude and the abort/retry remainder re-derivation (5753cfa45, c352648db); round eight (cubic) found that the cancelled-kill test passed on any rejection rather than the cancellation it claims — it now binds the rejection by identity to controller.signal.reason alongside the AbortError name (44ca81028, ab7334854); round nine (cubic) found the residual race in the wait itself: it read the mark once and reported covered even when a restore landed while it slept, releasing the kill inside the newer window — the wait now re-reads after every sleep and loops to the newest deadline, and the kill-site tests observe the middle of the wait with deferred sleeps (91d4c0b0a); round ten (cubic) confirmed that a daemon restart inside the window forfeits the remaining wait for a dead process's write — classified as a cross-process-deadline design boundary (a persisted deadline must be clock-independent and carry an expiry rule, reopening round seven's clock class otherwise) and filed as follow-up #3346, with the boundary recorded in the state module's doc comment (7c8297593, ce40232e3); round eleven (cubic) found that a kill racing an in-flight restore read idle — the window opens when the device accepts ime set, but the mark registered only after the readback — so in-flight writes are now tracked from issue and drained by the kill-side wait each round, the tests' hardcoded window literals moved behind an exported constant, and two local-only gate misses (an oxlint spread, a complexity threshold) were repaired after GitHub surfaced them (4d1b6d094, 248aa0b35, b0516feb8); round twelve (coordinator) demanded the reachability proof, which produced a self-corrected ledger — proven interleaving is fire-and-forget startup recovery vs an early kill, with weaker pairs labeled candidate/open in-thread; round thirteen (coordinator) found the pending-write design had silently encoded "readback mismatch ⇒ no provider write" — the mark now registers in the registrar's finally for every issued emulator restore, whatever the outcome (b79910d46); round fourteen (cubic) found the finally-registration had silently inverted the marker-clear rule’s premise — the mark carried a timestamp alone, so a later uninspected kill-bound close covering a set-failed restore’s mark cleared the durable recovery marker while the helper was still active — the mark now carries its write’s own provenance, the flush wait reports covered-issued vs covered-confirmed, and the clear rule consumes that fact instead of inferring it from coverage (663f11d8c); round fifteen (cubic) collapsed a byte-identical mark seeder duplicated across two test files into the shared IME fixtures module, where the next mark-shape change lands in one edit, and tightened the marker-retention test’s sleep assertion from any-positive to the file’s own nearly-full-window bound (b36626a4f).

Unresolved risk: the timed wait assumes the AOSP 2 s flush cap; a device overriding SETTINGS_PROVIDER_MAX_WRITE_DELAY_MILLIS upward could still lose the write.

Closes #3318