Skip to content

fix(android): persist the test-IME flush deadline across a daemon restart - #4882

Merged
thymikee merged 8 commits into
mainfrom
t3/android-ime-flush-evidence
Nov 21, 2026
Merged

thymikee merged 8 commits into
mainfrom
t3/android-ime-flush-evidence

Conversation

@thymikee

@thymikee thymikee commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Summary

After a test-IME restore on an emulator, adb emu kill must wait out the SettingsProvider flush window. The wait lived only in daemon memory, so a restart inside the window let close --shutdown or shutdown kill mid-flush. Fixes #3346.

  • The deadline is a durable record in <stateDir>/android-test-ime-flush/, written before and after ime set. The in-memory map is removed.
  • Clock: the host monotonic clock (monotonicNowMs on the adb host port). Wall-clock steps can't shorten a window. After a reboot the wait is capped at one window.
  • Expiry: an expired record costs no wait. The first kill-bound read deletes it.
  • A previous daemon's record holds the kill but can't clear a recovery marker.
  • A failed record write never blocks the restore: it warns and keeps the deadline in this daemon for every kill path.
  • Scope: stateDir threaded through the shutdown contract; 34 files incl. a commands.md regen.

Before / after

Fresh daemon, previous daemon's record 60% of a window from its deadline:

  • base: adb emu kill runs immediately.
  • head: sleeps the remaining ~1.5 s, then kills.

Validation

Base 4075dd1178, head c940db65ae.

  • Restart and failed-write regressions fail before their fixes, pass now.
  • unit-core (packages/platform-android, src/platform-runtime*, closure budget): pass.
  • Layering, typecheck, lint and fallow are clean.
  • Live check on emulator-5560: kill held to the deadline (see comment).

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.49 MB 6.49 MB +2.6 kB
Package (unpacked) 6.49 MB 6.49 MB +2.6 kB
Package (download) 1.98 MB 1.98 MB +761 B

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 22.8 ms 20.3 ms -2.5 ms
CLI --help 43.8 ms 44.6 ms +0.8 ms

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 45f230e. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The code change at e76756c needs one live check before merge. It changes when adb emu kill runs on Android emulators and adds host file reads and writes to every emulator test-IME restore, so it is device-facing. The tests use an in-memory host stub with performance.now() as the clock, so the production hrtime binding and the real record files are never exercised across two daemon processes (runtime.ts:42). Impact: the claim that two daemon processes agree on the host monotonic clock and that the record round-trips through the file is unproven. Required before merge: on an Android emulator built with pnpm build and pnpm build:android, using a fresh --state-dir $(mktemp -d), (1) run open <app> --platform android, type into a field, then close, and show <stateDir>/android-test-ime-flush/<serial> holding JSON with deadlineMs and confirmed: true; (2) immediately run daemon stop --state-dir <dir>, then shutdown --platform android --serial <serial> --state-dir <dir> from the new daemon within about 2 s, and record wall times that show the kill was held until the recorded deadline and that the record file is gone afterwards; (3) cold-boot the emulator and show adb shell settings get secure default_input_method returns the pre-session IME, not the helper; (4) repeat open and close, wait more than 3 s, then shut down, and show no hold and no record left. Please record the commands, serial, head SHA and outputs.

The two open inline threads on this PR: the one about the unwritable state dir (discussion) no longer applies at this head, because registerTestImeRestore now catches and warns (ime-state.ts:122) and ime set always runs (ime-restore.ts:184), so it can be resolved.

Not blocking, and fine to take or leave: if the post-write record fails (for example ENOSPC), only the issuing kill-bound close keeps the deadline, so an ordinary close followed within 2.5 s by a standalone shutdown kills without waiting (ime-restore.ts:221); the pre-write record deadline is computed before ime set is issued, so it is early by the round-trip if the daemon dies after the device accepts the write (ime-restore.ts:184); the new stateDir field sits beside sessionsDir and the two must now agree, though SessionStore.resolveDaemonStateDir() already derives one from the other (platform-runtime.ts:150); and the production monotonicNowMs binding has no test of its own (adb-host.fixtures.ts:84).

All 21 checks pass at e76756c. Tests were not run locally. Not verified here: the cross-process clock claim, which relies on libuv uv_hrtime being system-wide per boot, and behavior under Linux time namespaces. The next step before merge is the live emulator run above.

@thymikee

Copy link
Copy Markdown
Member Author

Replying to the review at e76756c (#4882 (comment)).

Live emulator restart check: not run yet. It shuts down and cold-boots the emulator, and every Android emulator booted on this host belongs to other work. My brief allows only a device it names, so I'm waiting for one. I'll post the commands, serial, head SHA, timings and record-file contents here once it runs. The unwritable-state-dir thread is already resolved.

Optional notes:

  • ime-restore.ts:221 (ENOSPC, then an ordinary close and a standalone shutdown within 2.5 s): accepted. Keeping that window would take a second, in-process persistence path, which the brief rules out. A failed write emits the android_test_ime_flush_record_write_failed warning.
  • ime-restore.ts:184 (pre-write deadline early by the ime set round trip): accepted. The record after the write replaces it with an accurate deadline, so the early one only matters if the daemon dies between the device accepting the write and the record after it, and then only by one adb round trip.
  • platform-runtime.ts:150 (stateDir beside sessionsDir): kept explicit. Claim recovery passes the dead owner's baseDir, and the daemon passes its own baseDir. Deriving it from sessionsDir would bake in a path convention the gateway doesn't own today.
  • adb-host.fixtures.ts:84 (no test for the production monotonicNowMs binding): the root binding object isn't exported, and adding an export only for tests is against the test-authoring rules. The live restart check covers it.

@thymikee
thymikee force-pushed the t3/android-ime-flush-evidence branch from e76756c to fddebef Compare November 21, 2026 17:14
thymikee and others added 6 commits November 21, 2026 18:19
…tart

A confirmed or issued test-IME restore on an emulator owes the
SettingsProvider flush window before any adb emu kill. The deadline lived
only in the daemon's in-process map, so a restart inside the window let a
kill land mid-flush. The deadline is now a durable record in the daemon
state dir, stamped on the host monotonic clock and capped at one window,
and the Android shutdown runtime reads it through the state dir.

Fixes #3346

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-check after clear

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The new module grew the mechanics eager closure; the records live beside
the recovery markers, which the closure already evaluates. Also drop the
now-unused export of the pending-writes map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
platform-android may not read process directly (R13); the root adb host
binding owns the hrtime read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…store

An unwritable state dir made the pre-write throw before ime set, leaving
the device on the test IME. The write failure now warns with a typed
diagnostic phase, the restore proceeds, and a kill-bound close holds its
own kill for the window it could not record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main's help text for --shutdown changed without regenerating the page,
which fails the generated-block guard on every branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@thymikee
thymikee force-pushed the t3/android-ime-flush-evidence branch from fddebef to a2f6f20 Compare November 21, 2026 17:21
@thymikee

Copy link
Copy Markdown
Member Author

Live emulator restart check, as requested in #4882 (comment).

Setup

  • Device: AVD agent-device-pr4539-api37, serial emulator-5560, Android 17 (API 37), on a macOS host.
  • Source: fddebef01b. The new head a2f6f20b40 is a rebase onto main (git range-diff shows patches 1–5 unchanged) plus the regenerated commands.md.
  • Build: pnpm build, pnpm build:android, pnpm clean:daemon. Driven with node bin/agent-device.mjs ... --platform android --serial emulator-5560 --state-dir $SD, where $SD is a fresh mktemp -d.
  • IME before the session: com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME.
  • Timestamps: each t line printed Date.now() and process.hrtime from a separate node process. That puts the host clock behind monotonicNowMs on the wall clock, and it also shows a third process reading the same clock as both daemons.

(1) open, type, close

  • open com.android.settings, press "Search Settings", then fill @e2 "wifi". The IME was then com.callstack.agentdevice.imehelper/.TestInputMethodService.
  • close --session ime-flush (ordinary, no --shutdown). Afterwards $SD/android-test-ime-flush/emulator-5560 held:
{"version":1,"serial":"emulator-5560","deadlineMs":1059695627.28,"confirmed":true,"writer":"179826d6-e448-4ffa-b63e-d4de22fb7bcc"}

(2) daemon stop, then standalone shutdown from a new daemon

close returned          mono=1059693415.65  17:16:26.604Z
daemon stop (pid 16182)  mono=1059694013.95  17:16:27.202Z
shutdown invoked         mono=1059694113.90  17:16:27.302Z   (new daemon pid 29273)
recorded deadline        mono=1059695627.28  17:16:28.815Z
shutdown request         17:16:27.785Z → 17:16:28.841Z  (durationMs 1056, from events.ndjson)
CLI returned             mono=1059695767.87
  • The shutdown request started 1,030 ms before the deadline and finished 26 ms after it.
  • The kill is the request's last step, so it landed after the deadline, and the deadline was read by a different process from the one that wrote it.
  • android-test-ime-flush/ was empty afterwards.

(3) Cold boot

  • emulator -avd agent-device-pr4539-api37 -port 5560 -no-snapshot-load, then sys.boot_completed=1.
  • adb shell settings get secure default_input_method returned com.google.android.inputmethod.latin/com.android.inputmethod.latin.LatinIME, the IME from before the session, not the helper.

(4) Open, type, close, wait 3.5 s, shutdown

record   {"deadlineMs":1059796680.009,"confirmed":true,"writer":"00a937e9-…"}
shutdown invoked  mono=1059798041.36  (1,361 ms past the deadline)
shutdown request  durationMs 151  (vs 1056 when held)
  • No hold, and android-test-ime-flush/ was empty afterwards.

Cleanup: the AVD is shut down, the daemon is stopped and the T3 device panel is closed. Not covered: Linux time namespaces, since this was a macOS host.

Also in this push: website/docs/docs/commands.md regenerated (pnpm generate:command-docs). The --shutdown help row on main had changed without regenerating the page, so the generated-block guard failed on every branch, main included.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The earlier findings on e76756c (#4882 (comment)) are fixed except one regression, which still shows at a2f6f20. An unwritable state dir no longer blocks the restore, because registerTestImeRestore now catches, warns, and ime set always runs.

If only <stateDir>/android-test-ime-flush is unwritable (for example a regular file sits at that path), both deadline registrations can fail while ime set and the read-back still succeed. The failed deadline then lives only in the restore call's local unrecorded object (https://github.com/callstack/agent-device/blob/a2f6f20/packages/platform-android/src/ime-restore.ts#L221). An ordinary close does not consume it and clears the pending-recovery marker, so an immediate standalone shutdown in the same daemon finds no record and reaches adb emu kill inside the flush window. Base kept the deadline in its per-device map and waited under the same conditions. A read-only run of the real restore, record and shutdown modules with a simulated ENOTDIR waited before the kill on base and killed without a wait at head. The emulator can lose the confirmed IME restore and reboot on the test IME after a successful ordinary close. To fix this, keep a process-local fallback deadline when publishing the flush record fails. Then make the shared kill guard in ime-state.ts honor the later of the durable and fallback deadlines, so an ordinary close stays wait-free. Please cover ordinary close followed by standalone shutdown with flush writes failing.

Could Android's ime-state.ts own the flush deadline and call its sibling record store through the existing files port? That would remove the pass through AndroidAdbHost, root composition, and back into Android mechanics, and all production flush-record consumers are already in the Android package.

The open inline thread #4882 (comment) no longer applies at this head, since the unwritable state dir case is handled as described above, so it can be resolved. No other open threads still apply.

Only the Body rules check is not passing. It was cancelled at its Checkout step and did not fail on a rule. It checks the PR body, not code, and the latest change (a docs regen) does not touch this route. The other 23 checks pass, and a re-run should settle it. No conflicts are known.

The author's live run was on fddebef, not a2f6f20. The match rests on the byte-identical logical patch diff, and the base moved by #4682 (host-kit ps lstart locale), which does not touch this route. Not verified here: the live run timings, which come from the author's comment; Linux time namespaces and the cross-process uv_hrtime assumption on Linux hosts (macOS host only); and the tests, which were not run locally.

Before merge, the fallback deadline fix above needs to land, and the cancelled Body rules check needs a re-run so all checks are green.

… in this daemon

When the flush-record directory is unwritable, the deadline lived only in
the restoring call, so an ordinary close followed by a standalone shutdown
killed inside the window. The shared kill guard now also waits out a
process-local fallback deadline; ordinary closes stay wait-free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member Author

Replying to #4882 (comment). Fixed in 88fe0de.

Fallback deadline (ime-restore.ts:221)

  • When writing the flush record fails, registerTestImeRestore now keeps the deadline in a process-local map, keyed by serial, and still emits the android_test_ime_flush_record_write_failed warning. If two writes fail, the later deadline wins.
  • The shared kill guard awaitTestImeFlushWindow waits out the durable record first, then this daemon's fallback deadline. So the later of the two is honored on every kill path: kill-bound close, standalone shutdown, and claim recovery.
  • If a newer write opens, or the fallback moves, while the guard sleeps, it runs another round.
  • A covered fallback window alone reports covered-issued, which proves only that a write was issued. Ordinary closes still never sleep.
  • The per-call holder and awaitUnrecordedTestImeFlushWindow are removed, so the net diff is smaller.
  • This supersedes my earlier "accepted" on this point.
  • Regression test: ime-restore.test.ts › an unrecordable window from an ordinary close still holds a later standalone shutdown. Record writes fail with ENOTDIR, then an ordinary close restores with no wait, then the standalone shutdown sleeps about one window before adb emu kill. It fails at a2f6f20 (sleep called 0 times) and passes now.

Simplicity question (could ime-state.ts use the files port directly?)

It's possible. All production consumers are in the Android package, and the record functions already live in ime-recovery-marker.ts next to the markers. I kept the imeFlushRecords facet for two reasons:

  • It mirrors imeRecoveryMarkers.
  • It lets restore and shutdown tests use the in-memory record store. The stub's files port throws on purpose, so a test can't lean on file I/O by accident.

Going direct would delete the facet, its root binding and three mechanics exports. But the fixtures would then need an in-memory files implementation for that directory, or the strict stub would have to be loosened. I can do that here or as a follow-up if you prefer it.

The new push also reruns the cancelled Body rules check.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 88fe0de. The verdict and the full list are in the summary comment.

… marker clear

When the record held an older confirmed window and a newer write failed
to record, the kill guard reported covered-confirmed and could clear the
retry marker. A fallback deadline newer than the record now reports
covered-issued.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of c940db6

Since the review of 88fe0de: 1 new · 0 still open · 1 no longer raised (1 marked fixed)

1 finding(s): 1 minor.

🟡 Minor (1)

Where Finding
packages/platform-android/src/ime-state.ts:117 🆕 Fallback flush deadline is keyed by serial only, so another state dir can consume it

Reviewed with this repository's own Sentinel configuration (a29f3ea79a59).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on c940db6. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

This PR is ready at c940db6. The delta fixes the problem in the earlier review (#4882 (comment)), and no findings remain that must be fixed before merge. Not blocking, and fine to take or leave: after the fallback wait in awaitUnrecordedTestImeFlushDeadline (https://github.com/callstack/agent-device/blob/c940db6/packages/platform-android/src/ime-state.ts#L199), the guard never reads the durable record again, so a second restore whose record writes succeed during that sleep could be killed inside its new window. The rule would be that the guard returns only after one pass in which neither the record nor the fallback reports a newer deadline, and continuing the loop after a non-zero fallback sleep would give that. This was found by reading the code and not reproduced with a test. The inline thread on the fallback-outranks-record check (#4882 (comment)) and the one on the unwritable state dir (#4882 (comment)) are fixed at this commit and can be resolved. The serial-only fallback key thread (#4882 (comment)) does not apply, because one daemon builds every runtime from one base dir, so no other state dir can consume the fallback. It can be resolved too. Only the Body rules check is not passing, and it shows as cancelled, not failed on a rule. This delta touches no code that check covers, so a re-run should turn it green, and that is the only step left before merge. Not verified here: the new tests were not run locally, and the claim that they fail at a2f6f20 rests on reading the removed code and the author's statement. The live device run predates this delta. It still covers the normal route, which the delta leaves unchanged. The fallback route is unit-tested only, since it needs a failing record write that is impractical to reproduce live. No conflicts.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 21, 2026
@thymikee
thymikee merged commit d6767e0 into main Nov 21, 2026
21 of 22 checks passed
@thymikee
thymikee deleted the t3/android-ime-flush-evidence branch November 21, 2026 19:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Android: durable flush evidence so a daemon restart inside the test-IME flush window cannot release adb emu kill

1 participant