Skip to content

fix(android): stop admitting orientation reads once the settle budget is spent - #4575

Merged
thymikee merged 4 commits into
mainfrom
t3/fix-android-orientation-settle
Nov 18, 2026
Merged

thymikee merged 4 commits into
mainfrom
t3/fix-android-orientation-settle

Conversation

@thymikee

@thymikee thymikee commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Summary

Android orientation settling could admit a final display read with too little time and replace the last observed rotation with a misleading adb timeout. The loop now makes one pre-wait budget check and sleeps only above a 300 ms read reserve. Reads retain their deadline-based signature. The immediate first read and normal 500 ms polling cadence are unchanged.

Two files change. Refs #4562. No shared adb timeout policy or scope expansion. One positive-cost regression replaces the larger intermediate test set.

Validation

  • Current head: 1404b7cfacaedc665054e8d42699b36ec1305a9d.
  • Same focused suite with main's loop: 1 failed / 29 passed, reproducing the false 50 ms adb timeout. Candidate: 30 passed; minimum and last admitted read budgets are 300 ms.
  • Exact-head pnpm check:affected --run --head 1404b7cfac... passed with exactCommit=true; hosted CI: 18 successful checks / one skipped placeholder.
  • Current-head device evidence: source-built isolated daemon, Android API 37, portrait-locked fixture; expected did not take effect error, requested/observed rotations 1/0. Cleanup complete.
  • Earlier source-head controls: three pinned trials and actual unpinned landscape rotation. Evidence retains its original SHA attribution; removed timing tests are not claimed at this head.

The maintainer accepted the remaining late-host-sleep caveat. No paired physical latency benchmark is claimed. Ready-for-human review is recorded at this head.

… is spent

The settle loop checked the deadline before its wait, then started another display read with the
remaining budget clamped to a 1 ms floor. A rotation that never takes effect therefore died as a
misleading adb timeout instead of reporting the last observed rotation. Admission is now rechecked
after the wait, so the existing "did not take effect" fact wins and a read that fails inside its own
budget stays a probe failure.

Closes #4562

Co-authored-by: Apex by Callstack <noreply@callstack.com>
Co-authored-by: opencode <noreply@opencode.ai>
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.30 MB 6.30 MB +21 B
Package (unpacked) 6.30 MB 6.30 MB +21 B
Package (download) 1.91 MB 1.91 MB +1 B

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 46.7 ms 34.5 ms -12.2 ms
CLI --help 74.9 ms 68.9 ms -6.1 ms

@thymikee

Copy link
Copy Markdown
Member Author

The guard at 3de249c does not fully remove the misleading adb timeout, so this needs one more change before merge. CI is green (18 checks, none failing).

The check Date.now() >= deadline at input-actions.ts:173 only stops a read when the remaining budget is zero or less. The loop sleeps min(500, remaining), so the wait can land a few ms to about 100 ms before the deadline. The read is then admitted with that small timeout. A real dumpsys display read takes 20-280 ms, so it times out and readAndroidDisplayRotation throws could not confirm the display rotation: adb timed out after Nms. For example, with 100 ms reads the cycle is 600 ms. At t=14400 the remaining budget is 600, the sleep reaches t=14900, and the read gets timeoutMs=100. A pinned-orientation app (the #4562 scenario) can still see the adb timeout message in a sizeable share of runs, perhaps 15% at that read cost. The rule the code must satisfy is that no read is admitted with a timeout below what one display read needs. Please use one named minimum-read-budget constant (about 250 ms, as the issue suggests) and enforce it at the loop's single admission point, so the capped-sleep case and the 500..500+read-cost case are both covered. Keep the final rotation from the last in-budget read.

This change alters the live Android orientation command, and the only device run in the PR body used a pinned 0.21.31 binary, not this head. The fake-adb traces have zero read cost, which is why they missed the partial-budget case. After the fix, please build the head with pnpm build and pnpm build:android, then run pnpm clean:daemon. On an Android emulator, run agent-device orientation landscape-left with a foreground app that pins its orientation. Please share the device, source SHA and exact output, which must be did not take effect: the display still reports rotation 0 after 15000ms. Repeat it a few times or with a slowed dumpsys, because this window is probabilistic, and report each run's final error message.

Not blocking, and fine to take or leave: the new tests in input-actions.test.ts:594 pin only the zero-budget and full-budget sides, so a bare >= guard or a floor-based guard passes the same tests and they stay green with the gap above (a case where each read advances the clock by 100 ms, plus one where the remainder sits exactly at the minimum, would pin both sides), and the comment at input-actions.ts:169 narrates the bug where a named constant with a one-line constraint comment and one shared predicate for the while condition and the post-sleep check would say it better.

Could one named MIN_ORIENTATION_READ_BUDGET_MS used as the loop's only admission predicate replace the bare check? It looks about the same size as this change and would cover the whole class of starved reads.

Once the guard is a minimum-budget predicate, the tests pin both sides, and the head-bound pinned-orientation run shows did not take effect, this is ready for another look.

@thymikee

Copy link
Copy Markdown
Member Author

The admission correction is pushed at 67a44f5. One predicate now reserves 300 ms, rounded above the prior observed 20–280 ms display reads, both before the poll and after the wait. The checked remaining budget is passed unchanged to the read, so this does not raise an adb timeout floor. Genuine in-budget probe failures retain their existing outcome.

The new positive-cost regression reproduces a 50 ms probe timeout at 3de249c. The delayed-wait boundary rejects 299 ms and admits 300 ms. In an isolated baseline checkout the same suite had 2 failures / 33 passes; candidate passes all 35. TypeScript and Android helper builds passed. The exact-head affected gate passed all 8 runnable checks (receipt run-yFQYUv, exactCommit=true, checkoutChanged=false); unit: 19,973 passed / 10 skipped. The experiment checkout was removed after verifying the implementation identity.

The candidate-head pinned-orientation run is still missing. Fresh T3 inventory shows the previously used Android targets booted with ownership unestablished; its runtime inventory exposes published 0.21.31/0.21.36 rather than this candidate. No device was opened, shared runtime changed or foreign daemon stopped. The PR remains an explicitly blocked draft until candidate device evidence is available; the earlier pinned-runtime observations are only latency-premise evidence.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. The 300 ms read floor and its tests at 67a44f5 look right, but this still needs a device run before merge.

The change alters the live Android orientation settle (input-actions.ts#L165). The earlier review asked for a run on the head that shows did not take effect on a target that pins its orientation. That run is still missing, and the PR says so. The unit tests mock adb and the clock, so they cannot show that a pinned target now ends with did not take effect: the display still reports rotation N after 15000ms instead of could not confirm ... adb timed out. The 300 ms floor is also an empirical number that only a real device can check.

Please run a build of 67a44f5 (local source daemon, not published 0.21.x) on an Android emulator or device whose foreground app is portrait-locked. Issue orientation landscape-left and attach the output. It must show orientation landscape-left did not take effect: the display still reports rotation 0 after 15000ms, with requestedRotation=1 and observedRotation=0 in the details. It must not show could not confirm the display rotation. Include the run's head hash. Then add one unpinned run that succeeds, so we can see the happy path is unchanged.

CI is green on all 18 checks. The diff touches only the Android input actions and their unit test, so no hosted job drives a pinned-orientation device, and green CI does not cover this behavior. The code and tests need no further change. Before merge, the pinned and unpinned runs on this head must be attached.

Not blocking, take or leave: the floor is 20 ms above the highest read seen (280 ms), so a read that runs past its budget on a loaded emulator can still end as could not confirm (raise the constant if device runs show reads above 300 ms); and hasOrientationReadBudget is checked at the loop condition and after the sleep, so when 300-800 ms remain the loop can wait up to 500 ms for no read (one in-loop check that sleeps min(POLL, remaining - MIN_ORIENTATION_READ_BUDGET_MS) would read the last slot).

@thymikee

Copy link
Copy Markdown
Member Author

The requested head-bound pinned and unpinned runs are still missing. I rechecked the available device tooling: T3 requires agent-device 0.21.36 and is running 0.21.31; its device launcher exposes no source-entry or worktree state-directory binding. That cannot exercise 67a44f5. The assigned API_35B is also already booted with ownership unestablished, so I left it and the shared runtime untouched.

The PR stays a blocked draft. The green checks and mock-clock regressions are not being treated as evidence for either requested device run.

@thymikee

Copy link
Copy Markdown
Member Author

The missing source-head device runs now pass at 984b94ef3a680907abc228ee14c39d1c1e97ca14 (production code unchanged from 67a44f5). This supersedes the tooling limitation in my earlier comments: the exact T3-bound 0.21.36 CLI supports documented daemon endpoint/auth flags, so it can drive a fresh isolated HTTP daemon built from this checkout without changing the launcher or shared runtime.

Source identity: pnpm build and pnpm build:android passed; daemon 0.21.38-dev, codeOrigin=checkout, graph signature graph:125:6afa86f0a6bcc8f7bb46d4f69d30270be5e7a194. Its process loaded this worktree's dist/src/internal/daemon.js, with a fresh private state directory. The Android helper snapshots report backend=android-helper, helperVersion=0.21.38-dev, and healthy capture.

Pinned foreground target: own native fixture com.callstack.maintainer.orientation4575, PortraitActivity declared screenOrientation="portrait"; AVD agent-device-fieldreport-api37, Android 17/API 37, serial emulator-5558. Each bound-CLI orientation landscape-left --json exited 1:

Trial Wall time Final message
1 15.157 s orientation landscape-left did not take effect: the display still reports rotation 0 after 15000ms
2 15.133 s orientation landscape-left did not take effect: the display still reports rotation 0 after 15000ms
3 15.075 s orientation landscape-left did not take effect: the display still reports rotation 0 after 15000ms

All three have code=COMMAND_FAILED, details.requestedRotation=1, details.observedRotation=0. None reports could not confirm. Portrait was reset between trials.

Unpinned control: the same package's FreeActivity uses screenOrientation="unspecified". orientation landscape-left exited 0 in 0.875 s. Healthy helper snapshots changed from 1080×2424 to 2424×1080; the T3 screenshot visibly showed the unpinned fixture in landscape. The existing public response still says confirmed:false / “device owner reported no resulting orientation”; I am not claiming that unrelated response flag became true. Portrait was restored and verified at 1080×2424.

Performance reconciliation: the 300 ms constant is admission reserve, not a sleep or timeout floor. Immediate read and 500 ms polls remain unchanged. Added deterministic success traces cover already-rotated, first-poll and second-poll success: 1/2/3 display reads, waits [] / [500] / [500,500], elapsed clock 25/550/1075 ms with 25 ms reads. These traces pass both unchanged current main 655ede2796e5e21293ed58b258ce8332d262e412 and main with this production patch. They are schedule invariants, not a paired physical latency benchmark. Injecting a 300 ms extra wait fails all three; restoring the patch passes all three.

In an isolated checkout of that current main, applying only this production patch passed 108 tests across five suites: input-actions, screenshot, helper fallback, Android interaction freshness and ADB executor. This preserves #4603's screenshot rotation metadata fast path, #4605's proved-fresh settle path, #4609's helper-input animation-wait removal and #4610's cancellation/readiness ownership. The unmerged adaptive/fast-poll prototype #4611 is not assumed to be shipping. No poll-cadence or quiet-window changes were added here.

Final validation: pnpm check:affected --run --head 984b94ef3a680907abc228ee14c39d1c1e97ca14 passed all 8 runnable checks; receipt run-Q6UVhh, exactCommit=true, checkoutChanged=false, no fail-open reasons. Full unit suite: 19,975 passed / 10 skipped, 2,117 files. Coverage remains GitHub-owned, manual replay-android is parked, and provider integration was deduplicated by related tests. Hosted checks at the new head are still pending. Cold full-diff self-review found no new issue; no independent review of this test-only follow-up was available.

Cleanup complete: own session closed, fixture uninstalled, isolated source daemon stopped gracefully, portrait restored, and this run's emulator shut down to its original stopped state. Other devices and sessions were left alone. The experiment checkout was removed after verifying implementation SHA and clean status. Raw JSON, fixture manifest/source/APK and experiment logs are retained locally under ~/.local/state/agent-device-maintainer/runs/2026-11-17/approval/T76-live-evidence/ (final-head live results in final-984/).

@thymikee
thymikee marked this pull request as ready for review November 17, 2026 19:02
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. I reviewed 984b94e and found no problems in the code or the test changes, so the evidence gap from my earlier review is now closed.

The change since 67a44f5 is test-only. I traced the settle loop and the test arithmetic by hand and they hold.

The pinned and unpinned emulator results in your comment 6957928616 name the head, daemon identity, device, fixture and per-trial output.

CI is green: 24 checks, none failing. No hosted device job exercises the Android settle path, so the live runs are the only coverage of it. There are no conflicts and no open review threads.

Nothing more is needed from you before merge. It is ready for the maintainer.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 17, 2026
@thymikee

Copy link
Copy Markdown
Member Author

A follow-up pass at 984b94e on whether every added line earns its place. The fix stays: #4562 is a real false error, and slower remote emulators hit it more often. The code and tests can be smaller, so I removed the ready-for-human label until they shrink.

  • One budget check instead of two. The deadline is checked in the loop condition and again after the sleep (input-actions.ts:172, :175-176), through a helper. The shape the issue suggests needs one check: compute left = deadline - Date.now(), break when left < MIN_ORIENTATION_READ_BUDGET_MS, and sleep Math.min(POLL, left - MIN_ORIENTATION_READ_BUDGET_MS). The sleep then never spends the read's reserve, so the second check and the helper can go. Please also keep the read's deadline-based signature, because changing it to a timeout is churn.
  • About 50 lines of tests instead of about 270. The three-case latency test.each also passes on unchanged main, so it does not cover this fix. The "later in-budget read succeeds" test repeats one of those cases. The "real-budget failure stays a probe failure" test covers behavior that already existed. The two deadline tests check the same rule. One deadline regression test with reads that take real time is enough, optionally with the 299/300 ms boundary pair. Exact-timing tests will also break on any future polling change.

The live emulator evidence at this head still covers the behavior if the shape changes this way. Re-running the locked-app case once at the new head is enough.

@thymikee thymikee removed the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 17, 2026
… wait

The loop checked the deadline in its condition and again after the wait,
through a helper. Computing the time left once per iteration makes the
shape smaller: break when it is below one read's reserve, and let the
wait spend only what is above the reserve. The read keeps its
deadline-based signature.

The orientation tests shrink from about 270 lines to about 50. The
three-case latency test.each passed without the fix, the later
in-budget-read test repeated one of its cases, and the real-budget probe
failure covered pre-existing behaviour, so they are gone. One regression
test keeps the case the fix is about: display reads that cost real time
must end the settle with the last rotation, never with a starved read's
adb timeout.

Co-authored-by: Apex by Callstack <noreply@callstack.com>
Co-authored-by: opencode <noreply@opencode.ai>
@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 1404b7c

Since the review of 984b94e: 1 new · 0 still open · 0 no longer raised

1 finding(s): 1 minor.

🟡 Minor (1)

Where Finding
packages/platform-android/src/input-actions.ts:170 🆕 Reserve is checked before the sleep, so the final read can still be admitted starved

1 finding below minor hidden (user_settings.min_severity).

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

💬 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 1404b7c. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

Shrunk at 1404b7cfacaedc665054e8d42699b36ec1305a9d. The fix is unchanged in behaviour; the shape is smaller.

One budget check per iteration (input-actions.ts:167-180):

const deadline = Date.now() + ORIENTATION_SETTLE_TIMEOUT_MS;
let observed = await readAndroidDisplayRotation(device, orientation, deadline);
while (observed !== undefined && observed !== userRotation) {
  // The wait spends only what is above one read's reserve, so every admitted read can answer.
  const leftMs = deadline - Date.now();
  if (leftMs < MIN_ORIENTATION_READ_BUDGET_MS) break;
  await sleep(Math.min(ORIENTATION_SETTLE_POLL_MS, leftMs - MIN_ORIENTATION_READ_BUDGET_MS));
  observed = await readAndroidDisplayRotation(device, orientation, deadline);
}

The second check and hasOrientationReadBudget are gone, and the read keeps its deadline-based signature. Production diff against main is now +10/−3.

Tests: +49/−1 lines instead of +270. The three-case latency test.each, the later in-budget-read duplicate, and the real-budget probe-failure test are deleted, and the base success-path test is restored. What stays for this fix is one regression test whose reads cost real time (50 ms then 100 ms):

  • positive-cost display reads end the settle on the last rotation, never on a starved read — asserts did not take effect: the display still reports rotation 0 after 15000ms, observedRotation 0, no could not confirm the display rotation, 26 reads, and that the smallest and last admitted budgets are exactly the 300 ms reserve.

With main's loop in place, that test fails on the false error, so it is a real regression test:

AssertionError: The input was expected to not match the regular expression /could not confirm the display rotation/. Input:
'orientation landscape-left could not confirm the display rotation: adb shell dumpsys display timed out after 50ms'
Tests  1 failed | 29 passed (30)

Locked-app case, re-run once at this head. Bound 0.21.36 CLI against an isolated daemon built from this checkout (0.21.38-dev, codeOrigin=checkout, codeSignature=graph:125:a69d4ffd776aa3104b435ea44bc6a115b56e54fe), own AVD agent-device-fieldreport-api37 (Android 17/API 37, emulator-5558), fixture com.callstack.maintainer.orientation4575 opened at PortraitActivity (screenOrientation="portrait"):

$ agent-device orientation landscape-left --json   # exit 1, 15 s
orientation landscape-left did not take effect: the display still reports rotation 0 after 15000ms
details: requestedRotation=1 observedRotation=0 dispatched=unknown

No could not confirm the display rotation. dumpsys display after the trial reported mCurrentOrientation=0, matching observedRotation. Portrait restored, fixture uninstalled, session closed, own daemon and emulator stopped again.

pnpm check:affected --run --head 1404b7cfac... passed with exactCommit=true, and CI is green at this head (18 checks, plus the skipped matrix placeholder).

@thymikee

Copy link
Copy Markdown
Member Author

This PR is ready at 1404b7c, and it is now the smaller shape from the follow-up pass. The loop now makes one check before the wait, which fixes the over-reserving predicate from the earlier review (#4575 (comment)). Nothing from that review remains open in the code.

Not blocking, and you can take or leave these: the PR body still describes the 984b94e shape (a predicate reserving 300 ms before and after the wait, the deleted success-path timing tests, 37 passing tests), so please rewrite Summary and Validation to the current shape (single pre-wait check, one regression test, the evidence comment 6963006385); and the new test in packages/platform-android/src/tests/input-actions.test.ts#L597 asserts exactly 26 reads, which follows from the 500 ms poll and the 50/100 ms costs, so dropping that assertion and keeping the min and last budget assertions would avoid breakage on a future polling change.

The one open thread (#4575 (comment), late host sleep) is true but not worth a second check, so it can be resolved as is. If device runs ever show reads above 300 ms, raise the constant.

All 19 checks pass at 1404b7c. The diff is the Android settle loop and its unit test, and no hosted job drives a pinned-orientation device, so green checks do not cover the behavior. The test-clock arithmetic holds against both this head and main. The live evidence is one pinned trial at this head, as requested, and the success path (immediate read, 500 ms polls) is unchanged.

There are no conflicts. Nothing blocks merge once the PR body is updated.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 17, 2026
@thymikee
thymikee merged commit 972b5a5 into main Nov 18, 2026
19 checks passed
@thymikee
thymikee deleted the t3/fix-android-orientation-settle branch November 18, 2026 09:45
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.

1 participant