fix(session): the bottom screen takes touch again while a game runs (#2910)

* fix(session): the bottom screen takes touch again while a game runs

Since #2763, a transparent KeepTopActivity covers every other display while a
session is on top. Its window is NOT_TOUCHABLE, but Android gives a
translucent activity alone in its task an ActivityRecordInputSink that eats
every touch on that display (ENABLE_TOUCH_OPAQUE_ACTIVITIES, on for this
target SDK). With the dual-screen panel closed, the bottom screen's launcher,
Cocoon or any other app could not be touched until the session ended, and
the guard stayed over it after Home/PiP as well.

- The guard now takes touches itself: a touch removes it from that display.
- It comes back when the session is top-resumed again, or after 5 s if the
  session kept the top spot (the user touched the bottom screen once and
  stayed in the game).
- Stopping or entering PiP removes the guards; PiP keeps the session at adj
  50 with or without them, so they protected nothing there.

A/B on a Retroid Pocket Duo (Android 16, Cocoon as bottom home): the guard
is on top in every state it was on top on main, except the 5 s after a
bottom touch and PiP. Under lmkd pressure (kills down to adj 50, bottom
home killed 14-31 times per run) neither build lost the top spot.

* test(session): A/B tool for the keep-top guard on rooted dual screens, with Duo findings

* test(session): the guard A/B tool stops on a failed session start and cleans up an interrupted pressure run
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-20 00:18:50 -05:00
1 parent 4e81030fb8
commit 5051fc8b32
5 files changed
+650 -8

No files matched your search

@@ -5615,6 +5615,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onPictureInPictureModeChanged(inPip: Boolean, newConfig: android.content.res.Configuration) {
super.onPictureInPictureModeChanged(inPip, newConfig)
if (inPip) {
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
com.droiddeck.launcher.session.KeepTopActivity.stepAside()
}
if (::pip.isInitialized) pip.changed(inPip)
if (!inPip && surfaceW > 0) resizeOutputForWindow(surfaceW, surfaceH)
applyUnfoldedControls()
@@ -5657,6 +5662,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onStop() {
if (lightPause.stopped()) departureCleanup()
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
com.droiddeck.launcher.session.KeepTopActivity.stepAside()
if (runtimeRemovalBlocked) { super.onStop(); return }
started = false
if (::hud.isInitialized) hud.setBackgrounded(true)
@@ -5700,6 +5708,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onResume() {
super.onResume()
com.droiddeck.launcher.session.KeepTopActivity.onYield = onGuardYield
uiHandler.removeCallbacks(lightPauseCheck)
when (lightPause.resumed(com.droiddeck.launcher.session.KeepTopActivity.bounces)) {
com.droiddeck.launcher.session.LightPause.Resume.LIGHT -> return
@@ -5783,6 +5792,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
// A touch that removed a guard while the session kept the top spot did not move focus to that
// display, so the guard comes back unless the user carries on there.
private val rearmAfterYield = Runnable {
if (topResumed && !isFinishing) {
com.droiddeck.launcher.session.KeepTopActivity.rearm()
guardOtherDisplays()
}
}
private val onGuardYield: () -> Unit = {
uiHandler.removeCallbacks(rearmAfterYield)
uiHandler.postDelayed(rearmAfterYield, com.droiddeck.launcher.session.KeepTopActivity.YIELD_GRACE_MS)
}
// RUNNING_LOW and RUNNING_CRITICAL are not delivered from API 34, so the guard also goes up
// as soon as a running session is on top.
override fun onTrimMemory(level: Int) {
@@ -5796,13 +5818,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
super.onTopResumedActivityChanged(isTopResumedActivity)
topResumed = isTopResumedActivity
uiHandler.removeCallbacks(guardWhenRunning)
if (isTopResumedActivity) uiHandler.post(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
if (isTopResumedActivity) {
com.droiddeck.launcher.session.KeepTopActivity.rearm()
uiHandler.post(guardWhenRunning)
}
else if (com.droiddeck.launcher.session.TopUnderPressure.shouldReclaim(
android.os.SystemClock.elapsedRealtime(), memoryPressureAt, SessionState.running, isFinishing)) guardOtherDisplays()
}
private fun guardOtherDisplays() {
if (!SessionState.running || isFinishing) return
if (!SessionState.running || isFinishing || isInPictureInPictureMode) return
val wasResumed = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)
val bounced = com.droiddeck.launcher.session.KeepTopActivity.guardOtherDisplays(this, display?.displayId ?: android.view.Display.DEFAULT_DISPLAY)
if (com.droiddeck.launcher.session.KeepTopActivity.hasPendingStarts()) {
@@ -6483,6 +6509,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onDestroy() {
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.removeCallbacks(rearmAfterYield)
if (com.droiddeck.launcher.session.KeepTopActivity.onYield === onGuardYield) com.droiddeck.launcher.session.KeepTopActivity.onYield = null
com.droiddeck.launcher.session.KeepTopActivity.release()
synchronized(frameGenGlobalLock) {
frameGenActivityActive = false
@@ -9,11 +9,15 @@ import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.Display
import android.view.MotionEvent
import android.view.WindowManager
// While a session runs, sits invisibly on top of every other display until it ends, so
// that display's home launcher is not its top activity. lmkd kills the launcher first; restarted as a
// top activity it takes focus from the session, which then drops to adj 50 and is killed next.
// While a session is on screen, sits invisibly on top of every other display, so that display's
// home launcher is not its top activity. lmkd kills the launcher first; restarted as a top activity
// it takes focus from the session, which then drops to adj 50 and is killed next.
// Android gives a translucent activity alone in its task an input sink that eats every touch on the
// display whatever its window flags say, so a touch makes the guard leave that display until the
// session is back on top.
class KeepTopActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -27,13 +31,28 @@ class KeepTopActivity : Activity() {
finishAndRemoveTask()
return
}
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
val id = display?.displayId ?: Display.INVALID_DISPLAY
starting.remove(id)
if (id in yielded) {
finishAndRemoveTask()
return
}
guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask()
guards[id] = this
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN && !isFinishing) {
val id = display?.displayId ?: Display.INVALID_DISPLAY
yielded.add(id)
Log.i(TAG, "display $id touched, leaving it to the app below")
finishAndRemoveTask()
onYield?.invoke()
}
return true
}
override fun onDestroy() {
guards.values.remove(this)
super.onDestroy()
@@ -49,13 +68,18 @@ class KeepTopActivity : Activity() {
private val guards = HashMap<Int, KeepTopActivity>()
private const val START_TIMEOUT_MS = 2_000L
private val starting = HashMap<Int, Long>()
private val yielded = HashSet<Int>()
const val YIELD_GRACE_MS = 5_000L
var onYield: (() -> Unit)? = null
fun rearm() = yielded.clear()
fun guardOtherDisplays(context: Context, sessionDisplay: Int): Boolean {
val displays = context.getSystemService(DisplayManager::class.java)?.displays ?: return false
var started = false
for (display in displays) {
val id = display.displayId
if (id == sessionDisplay || display.state != Display.STATE_ON || guards[id]?.isFinishing == false ||
if (id == sessionDisplay || id in yielded || display.state != Display.STATE_ON || guards[id]?.isFinishing == false ||
starting[id]?.let { SystemClock.elapsedRealtime() - it < START_TIMEOUT_MS } == true) continue
runCatching {
launch(context, id, bounce = false)
@@ -73,13 +97,18 @@ class KeepTopActivity : Activity() {
const val RETRY_MS = START_TIMEOUT_MS + 250
fun release() {
fun stepAside() {
generation++
guards.values.toList().forEach { it.finishAndRemoveTask() }
guards.clear()
starting.clear()
}
fun release() {
stepAside()
yielded.clear()
}
private fun launch(context: Context, displayId: Int, bounce: Boolean) {
val intent = Intent(context, KeepTopActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
+90
View File
@@ -0,0 +1,90 @@
# Keep-top guard A/B on dual screens
`KeepTopActivity` (#2763) covers every other display while a session is on top, so that
display's home is not its top activity. On the Thor, lmkd kills the bottom home under memory
pressure, Android relaunches it to the front (`wm_task_to_front`), the session loses the top
spot, drops to adj 50 and is killed in lmkd's next pass.
Android gives a translucent activity that is alone in its task an `ActivityRecordInputSink`
that consumes every touch inside the task bounds, whatever the window's flags say
(`ENABLE_TOUCH_OPAQUE_ACTIVITIES`, on for DroidDeck's target SDK; see
`services/core/java/com/android/server/wm/ActivityRecordInputSink.java`). The guard's
`FLAG_NOT_TOUCHABLE` therefore did nothing: with the dual-screen panel closed, the bottom
screen took no touch until the session ended, and the guard also stayed over it after Home.
The guard now takes touches itself. A touch removes it from that display. It comes back when
the session is top-resumed again, or after 5 s if the session kept the top spot (one touch on
the bottom screen, then back to the game). Stopping or entering PiP removes the guards.
## Tool
`tools/memory_guard_ab.py` drives a rooted dual-screen device over adb (`su` required) with a
build that has the debugging tools:
```sh
python3 tools/memory_guard_ab.py --label main --apk main.apk states
python3 tools/memory_guard_ab.py --label fix --apk fix.apk states
python3 tools/memory_guard_ab.py --label fix pressure --stop-mb 650 --hold 30 --runs 3
python3 tools/memory_guard_ab.py --label fix summarize ~/.cache/droiddeck-memory-guard-ab/fix-stop650-1-events.txt
```
Results are JSON lines in `~/.cache/droiddeck-memory-guard-ab/<label>.jsonl`, next to the
event log of every probe.
- `states` starts a fresh Steam session and walks the reachable states. In each one it records
the focused display, the guards, the panel and DroidDeck's `oom_score_adj`, then kills the
bottom home with `kill -9` (what lmkd does) and samples the adj for 5 s. It also counts guard
launches during 3 idle seconds and `SessionActivity` instances, which catch a guard loop.
- `pressure` fills a private tmpfs with `/dev/urandom` until `MemAvailable` reaches
`--stop-mb`, holds it, and releases it. zram cannot compress that data and no app owns it,
so lmkd keeps killing by adj. It records lmkd's `killinfo`, process deaths, focus loss and
whether DroidDeck survived.
- `--bottom-tap` must point at an inert spot of the bottom home; `--panel-close` at the
panel's close button. Both are fractions of the bottom display.
- `am start` of `SessionActivity` needs `--display 0`; without it, it creates a second
session on the focused bottom display.
## Results: Retroid Pocket Duo, Android 16, Cocoon as the bottom home
Builds: `main` (45c31a4), `fix` (this branch), and `no-guard` (`main` with
`guardOtherDisplays` returning at once, the behaviour before #2763).
### Bottom home killed in each state
| State | main | fix | no-guard |
| --- | --- | --- | --- |
| Panel open | guard, adj 0 | guard, adj 0 | adj 0 |
| Panel closed, bottom untouched | guard, adj 0 | guard, adj 0 | adj 0 |
| One bottom touch, under 5 s ago | guard, adj 0 (touch eaten) | no guard, adj 0 | focus on bottom, adj 50 |
| One bottom touch, then 8 s in the game | guard, adj 0 | guard, adj 0 | focus on bottom, adj 50 |
| Used the bottom screen, then tapped the game | guard, adj 0 | guard, adj 0 | adj 0 |
| Home (session in PiP) | guard, adj 50 | no guard, adj 50 | adj 50 |
| Using the bottom screen now | not reachable (touches eaten) | focus on bottom, adj 50 | focus on bottom, adj 50 |
No probe on any build lost the session's top spot or raised its adj when the bottom home was
killed. The fix has the guard on top wherever `main` has it, except in the 5 s after a bottom
touch and in PiP, where the session is at adj 50 with or without it. There were no guard
launches while idle and one session in every state.
### Real memory pressure, panel closed, game focused
| Run | lmkd kills (down to adj 0) | Bottom home deaths | Session lost the top spot | DroidDeck |
| --- | --- | --- | --- | --- |
| no-guard, stop at 650 MB | 42 (0) | 14 | no | survived |
| main, stop at 650 MB | 10 (0) | 0 | no | survived |
| fix, stop at 650 MB | 42 (0) | 18 | no | survived |
| no-guard, stop at 500 MB | 36 (2) | 15 | no | killed at adj 0 |
| main, stop at 500 MB | 73 (4) | 28 | no | killed at adj 0 |
| fix, stop at 500 MB | 74 (1) | 31 | no | survived |
Around 650 MB available, lmkd kills down to adj 50: the bottom home dies over and over and the
session survives. At 500 MB lmkd reaches its adj 0 pass and kills the foreground session
whatever the guard does; which build survives that is luck.
### What the Duo cannot show
Android 16 on the Duo restarts a killed bottom home in place (`wm_restart_activity`) and never
moves it to the front, even with no guard. The Thor's focus steal does not happen here, so the
Duo shows that the guard covers the same states as before, not that it saves the session. That
needs a Thor: run `states` and `pressure --stop-mb` near its adj-50 level on `main` and on the
fix, and look for `task_to_front` and `session_top_lost` before `droiddeck_died_at_adj` 50.
+389
View File
@@ -0,0 +1,389 @@
#!/usr/bin/env python3
"""A/B the session's keep-top guard on a rooted dual-screen device.
See docs/development/memory-guard-ab.md. Needs `su` on the device and a running DroidDeck build
with debugging tools (tools/droiddeckctl).
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shlex
import subprocess
import sys
import tempfile
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from adb_device import DeviceResolutionError, resolve_serial # noqa: E402
TOOLS = Path(__file__).resolve().parent
PACKAGE = "com.droiddeck.launcher"
SESSION = f"{PACKAGE}/.SessionActivity"
HOG_PATH = "/data/local/tmp/dd-memory-hog.sh"
HOG_MOUNT = "/dev/dd-memory-hog"
# Incompressible data in a private tmpfs: zram cannot shrink it and no app owns it, so lmkd keeps
# killing by oom_score_adj while it is held.
HOG = f"""#!/system/bin/sh
stop_mb=$1; hold=$2
cleanup() {{ rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }}
trap 'cleanup; exit 1' HUP INT TERM
mkdir -p {HOG_MOUNT}
grep -q ' {HOG_MOUNT} ' /proc/mounts || mount -t tmpfs -o size=16g tmpfs {HOG_MOUNT}
i=0
while [ $i -lt 512 ]; do
avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)
echo "avail=$avail"
[ "$avail" -le "$stop_mb" ] && break
head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || break
i=$((i+1))
done
sleep "$hold"
cleanup
echo released
"""
# Stops a writer left by an interrupted run before its files go, so the unmount does not fail. The
# bracketed patterns keep pkill from matching the shell that runs this line.
HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; sleep 1; rm -f {HOG_MOUNT}/f*; "
f"umount {HOG_MOUNT} 2>/dev/null; true")
def focused_display(input_dump: str) -> int | None:
match = re.search(r"FocusedDisplayId: (-?\d+)", input_dump)
return int(match.group(1)) if match else None
def activity_count(activities_dump: str, activity: str) -> int:
return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r" ", activities_dump))
def guard_count(activities_dump: str) -> int:
return activity_count(activities_dump, f"{PACKAGE}/.session.KeepTopActivity")
def session_count(activities_dump: str) -> int:
return activity_count(activities_dump, SESSION)
def panel_windows(windows_dump: str, display: int) -> int:
count, current = 0, None
for line in windows_dump.splitlines():
header = re.match(r"\s*Window #\d+ Window\{\S+ u\d+ (.+?)\}:", line)
if header:
current = header.group(1)
continue
shown = re.search(r"mDisplayId=(\d+)", line)
if shown and current is not None:
if current == PACKAGE and int(shown.group(1)) == display:
count += 1
current = None
return count
def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | None:
display = None
for line in activities_dump.splitlines():
section = re.match(r"Display #(\d+) \(activities", line)
if section:
display = int(section.group(1))
continue
if line.strip() == "" or display is None or display == session_display:
continue
home = re.search(r"type=home A=\d+:(\S+) .*visible=true", line)
if home:
return display, home.group(1)
return None
def logical_size(displays_dump: str, display: int) -> tuple[int, int] | None:
current = None
for line in displays_dump.splitlines():
header = re.search(r"Display: mDisplayId=(\d+)", line)
if header:
current = int(header.group(1))
continue
size = re.search(r"\bcur=(\d+)x(\d+)", line)
if size and current == display:
return int(size.group(1)), int(size.group(2))
return None
def max_adj(samples: list[str]) -> int | None:
values = [int(sample) for sample in samples if re.fullmatch(r"-?\d+", sample)]
return max(values) if values else None
def summarize_events(events: str) -> dict:
kills = [tuple(int(field) for field in match.groups())
for match in re.finditer(r"killinfo: \[(\d+),(\d+),(-?\d+),(-?\d+),", events)]
died = [(match.group(1), int(match.group(2)))
for match in re.finditer(r"am_proc_died: \[\d+,\d+,([^,\]]+),(-?\d+),", events)]
session_died = [adj for name, adj in died if name == PACKAGE]
return {
"lmkd_kills": len(kills),
"lmkd_kills_down_to_adj0": sum(1 for kill in kills if kill[3] <= 0),
"processes_died": {name: sum(1 for other, _ in died if other == name) for name in sorted({n for n, _ in died})},
"droiddeck_died_at_adj": session_died[0] if session_died else None,
"session_top_lost": len(re.findall(r"wm_on_top_resumed_lost_called: \[\d+,com\.droiddeck\.launcher\.SessionActivity,", events)),
"task_to_front": len(re.findall(r"wm_task_to_front:", events)),
"guard_creates": len(re.findall(r"wm_create_activity: .*KeepTopActivity", events)),
}
class Device:
def __init__(self, adb: str, serial: str):
self.adb, self.serial = adb, serial
def run(self, *args: str, timeout: int = 120, check: bool = False) -> str:
result = subprocess.run([self.adb, "-s", self.serial, *args], capture_output=True, text=True, timeout=timeout)
if check and result.returncode != 0:
raise RuntimeError(f"adb {' '.join(args)} failed: {result.stderr.strip()}")
return result.stdout.replace("\r", "")
def sh(self, command: str, timeout: int = 120) -> str:
return self.run("shell", command, timeout=timeout)
def su(self, command: str, timeout: int = 120) -> str:
return self.sh(f"su -c {shlex.quote(command)}", timeout=timeout)
def ctl(self, *args: str, timeout: int = 300) -> subprocess.CompletedProcess[str]:
return subprocess.run([str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args],
capture_output=True, text=True, timeout=timeout)
def phase(self) -> str | None:
match = re.search(r'"phase":\s*"(\w+)"', self.ctl("state").stdout)
return match.group(1) if match else None
def pid(self) -> str:
return self.sh(f"pidof {PACKAGE}").strip()
def running_pid(self) -> str:
pid = self.pid()
if not re.fullmatch(r"\d+", pid):
raise RuntimeError(f"{PACKAGE} is not running")
return pid
def size(self, display: int) -> tuple[int, int]:
size = logical_size(self.sh("dumpsys window displays"), display)
if not size:
raise RuntimeError(f"no size for display {display}")
return size
class Bench:
def __init__(self, device: Device, out: Path, label: str, session_display: int, bottom_tap: tuple[float, float],
panel_close: tuple[float, float]):
self.d, self.out, self.label, self.session_display = device, out, label, session_display
self.bottom_tap, self.panel_close = bottom_tap, panel_close
self.out.mkdir(parents=True, exist_ok=True)
def bottom(self) -> tuple[int, str]:
found = bottom_home(self.d.sh("dumpsys activity activities"), self.session_display)
if not found:
raise RuntimeError("no visible home activity on another display")
return found
def tap(self, display: int, fraction: tuple[float, float]):
width, height = self.d.size(display)
self.d.sh(f"input -d {display} tap {int(width * fraction[0])} {int(height * fraction[1])}")
def tap_bottom(self):
self.tap(self.bottom()[0], self.bottom_tap)
def game_front(self):
self.d.su(f"am start --display {self.session_display} -n {SESSION} -f 0x20000000")
time.sleep(3)
def close_panel(self):
display = self.bottom()[0]
for _ in range(3):
if panel_windows(self.d.sh("dumpsys window windows"), display) == 0:
return
self.tap(display, self.panel_close)
time.sleep(3)
def prepare(self, apk: str | None):
self.d.sh("input keyevent KEYCODE_WAKEUP")
self.d.ctl("stop")
if apk:
env = dict(os.environ, ADB_SERIAL=self.d.serial)
subprocess.run([str(TOOLS / "deploy_local.sh"), apk], env=env, check=True, capture_output=True)
self.d.sh(f"monkey -p {PACKAGE} -c android.intent.category.LAUNCHER 1")
time.sleep(6)
for attempt in range(2):
started = self.d.ctl("start", "steam", "--wait", "--timeout", "240")
if self.d.phase() == "READY":
break
if attempt == 1:
raise RuntimeError("the Steam session did not reach READY: "
+ (started.stderr.strip() or started.stdout.strip() or f"exit {started.returncode}"))
time.sleep(5)
time.sleep(15)
self.game_front()
def snapshot(self) -> dict:
activities = self.d.sh("dumpsys activity activities")
display = self.bottom()[0]
pid = self.d.running_pid()
return {
"focused_display": focused_display(self.d.sh("dumpsys input")),
"guards": guard_count(activities),
"sessions": session_count(activities),
"panel": panel_windows(self.d.sh("dumpsys window windows"), display),
"adj": int(self.d.su(f"cat /proc/{pid}/oom_score_adj").strip() or -9999),
"pid": pid,
}
def write(self, kind: str, record: dict):
record = {"label": self.label, "kind": kind, **record}
with (self.out / f"{self.label}.jsonl").open("a") as results:
results.write(json.dumps(record) + "\n")
print(json.dumps(record))
def probe(self, state: str):
self.d.run("logcat", "-b", "events", "-c")
time.sleep(3)
idle_creates = summarize_events(self.d.run("logcat", "-b", "events", "-d"))["guard_creates"]
before = self.snapshot()
_, home = self.bottom()
self.d.run("logcat", "-b", "events", "-c")
samples = self.d.su(f"kill -9 $(pidof {home}); for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj"
" 2>/dev/null || echo DEAD; sleep 0.1; done").split()
events = self.d.run("logcat", "-b", "events", "-d")
(self.out / f"{self.label}-{state}-events.txt").write_text(events)
summary = summarize_events(events)
self.write("state", {
"state": state, "bottom_home": home, **{k: v for k, v in before.items() if k != "pid"},
"guard_creates_idle_3s": idle_creates, "adj_max_after_home_kill": max_adj(samples),
"session_top_lost": summary["session_top_lost"], "droiddeck_alive": self.d.pid() == before["pid"],
"phase": self.d.phase(),
})
time.sleep(4)
def states(self):
self.probe("panel_open")
self.game_front()
self.close_panel()
self.probe("panel_closed_untouched")
self.game_front()
self.tap_bottom()
time.sleep(1)
self.probe("one_bottom_tap_just_now")
self.game_front()
self.tap_bottom()
time.sleep(8)
self.probe("one_bottom_tap_then_stayed")
self.game_front()
self.tap_bottom()
time.sleep(1)
self.tap_bottom()
time.sleep(1)
self.tap(self.session_display, (0.36, 0.11))
time.sleep(3)
self.probe("used_bottom_then_tapped_game")
self.game_front()
self.d.sh("input keyevent KEYCODE_HOME")
time.sleep(4)
self.probe("home_pip")
self.game_front()
self.tap_bottom()
time.sleep(1)
self.tap_bottom()
time.sleep(2)
self.probe("using_bottom_now")
self.game_front()
def pressure(self, run: str, stop_mb: int, hold: int):
with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as script:
script.write(HOG)
try:
self.d.run("push", script.name, HOG_PATH, check=True)
finally:
os.unlink(script.name)
self.d.sh(f"chmod 755 {HOG_PATH}")
self.game_front()
self.close_panel()
before = self.snapshot()
self.d.run("logcat", "-b", "events", "-c")
hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)}'"],
stdout=subprocess.PIPE, text=True)
samples = []
try:
while hog.poll() is None:
samples.append(self.d.su(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip())
time.sleep(0.5)
output = hog.stdout.read() if hog.stdout else ""
finally:
if hog.poll() is None:
hog.terminate()
self.d.su(HOG_CLEANUP)
time.sleep(3)
events = self.d.run("logcat", "-b", "events", "-d")
(self.out / f"{self.label}-{run}-events.txt").write_text(events)
available = [int(value) for value in re.findall(r"avail=(\d+)", output)]
self.write("pressure", {
"run": run, "stop_mb": stop_mb, "hold_s": hold, **{k: v for k, v in before.items() if k != "pid"},
"min_available_mb": min(available) if available else None, "adj_max": max_adj(samples),
"droiddeck_alive": self.d.pid() == before["pid"], "phase": self.d.phase(), **summarize_events(events),
})
def fraction_pair(text: str) -> tuple[float, float]:
x, y = (float(part) for part in text.split(","))
return x, y
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--adb", default=os.environ.get("ADB", "adb"))
parser.add_argument("--serial")
parser.add_argument("--out", type=Path, default=Path.home() / ".cache" / "droiddeck-memory-guard-ab")
parser.add_argument("--label", required=True, help="build name for the results, e.g. main or fix")
parser.add_argument("--apk", help="install this APK and start a fresh Steam session first")
parser.add_argument("--session-display", type=int, default=0)
parser.add_argument("--bottom-tap", type=fraction_pair, default=(0.78, 0.47),
help="x,y fractions of an inert spot on the bottom home (default 0.78,0.47)")
parser.add_argument("--panel-close", type=fraction_pair, default=(0.053, 0.071),
help="x,y fractions of the dual-screen panel's close button")
commands = parser.add_subparsers(dest="command", required=True)
commands.add_parser("states", help="kill the bottom home like lmkd in each session state")
pressure = commands.add_parser("pressure", help="hold real memory pressure and record lmkd kills")
pressure.add_argument("--stop-mb", type=int, default=650, help="stop filling at this MemAvailable")
pressure.add_argument("--hold", type=int, default=30)
pressure.add_argument("--runs", type=int, default=1)
summarize = commands.add_parser("summarize", help="summarize a saved events log")
summarize.add_argument("events", type=Path)
args = parser.parse_args()
if args.command == "summarize":
print(json.dumps(summarize_events(args.events.read_text()), indent=2))
return 0
try:
device = Device(args.adb, resolve_serial(args.adb, args.serial))
except DeviceResolutionError as exc:
print(f"memory-guard-ab: {exc}", file=sys.stderr)
return 2
if device.su("id -u").strip() != "0":
print("memory-guard-ab: needs a rooted device (su)", file=sys.stderr)
return 2
bench = Bench(device, args.out, args.label, args.session_display, args.bottom_tap, args.panel_close)
try:
if args.command == "states":
bench.prepare(args.apk)
bench.states()
else:
for run in range(args.runs):
bench.prepare(args.apk if run == 0 else None)
bench.pressure(f"stop{args.stop_mb}-{run + 1}", args.stop_mb, args.hold)
except RuntimeError as exc:
print(f"memory-guard-ab: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
+106
View File
@@ -0,0 +1,106 @@
from pathlib import Path
import sys
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import memory_guard_ab as ab
ACTIVITIES = """\
Display #2 (activities from top to bottom):
* Task{b24f3e8 #1421 type=standard A=10120:com.droiddeck.launcher.keeptop U=0 visible=true visibleRequested=true mode=fullscreen translucent=true sz=1}
* Hist #0: ActivityRecord{10082571 u0 com.droiddeck.launcher/.session.KeepTopActivity t1421}
* Task{3002b72 #6 type=home U=0 visible=true visibleRequested=true mode=fullscreen translucent=false sz=2}
* Task{b347c40 #7 type=home A=10082:com.android.launcher3 nonResizable U=0 rootTaskId=6 visible=false visibleRequested=false mode=fullscreen translucent=true sz=1}
* Task{1ea585a #1448 type=home A=10130:rip.moth.cocoonshell nonResizable U=0 rootTaskId=6 visible=true visibleRequested=true mode=fullscreen translucent=false sz=1}
Display #0 (activities from top to bottom):
* Task{972c91 #1434 type=standard A=10120:com.droiddeck.launcher U=0 visible=true visibleRequested=true mode=fullscreen translucent=false sz=2}
* Hist #1: ActivityRecord{240807202 u0 com.droiddeck.launcher/.session.KeepTopActivity t1633}
* Hist #0: ActivityRecord{126627493 u0 com.droiddeck.launcher/.SessionActivity t1434}
* Task{93ad796 #1 type=home U=0 visible=false visibleRequested=false mode=fullscreen translucent=true sz=1}
* Task{ae41383 #1408 type=home I=com.android.launcher3/.uioverrides.QuickstepLauncher U=0 rootTaskId=1 visible=true visibleRequested=true mode=fullscreen translucent=true sz=1}
"""
WINDOWS = """\
Window #19 Window{6dc6ad8 u0 NavigationBar2}:
mDisplayId=2 rootTaskId=1 mSession=Session{1 2:u0a1} mClient=android.os.BinderProxy@1
Window #20 Window{cde10e4 u0 com.droiddeck.launcher}:
mDisplayId=2 rootTaskId=1 mSession=Session{2 3:u0a120} mClient=android.os.BinderProxy@2
Window #21 Window{d8e62b4 u0 com.droiddeck.launcher/com.droiddeck.launcher.session.KeepTopActivity}:
mDisplayId=2 taskId=1425 mSession=Session{2 3:u0a120} mClient=android.os.BinderProxy@3
Window #22 Window{aeb9be7 u0 com.droiddeck.launcher}:
mDisplayId=0 rootTaskId=1 mSession=Session{2 3:u0a120} mClient=android.os.BinderProxy@4
"""
DISPLAYS = """\
Display: mDisplayId=2 (organized)
init=1280x960 320dpi mMinSizeOfResizeableTaskDp=220 cur=1280x960 app=1280x960 rng=960x960-1280x1280
Display: mDisplayId=0 (organized)
init=1080x1920 369dpi mMinSizeOfResizeableTaskDp=220 cur=1920x1080 app=1920x1080 rng=1080x1080-1920x1920
"""
EVENTS = """\
11-19 22:50:25.389 514 514 I killinfo: [28834,10129,995,50,95820,1,28492]
11-19 22:50:26.239 514 514 I killinfo: [29132,1000,102,50,84792,1,43120]
11-19 22:50:33.400 514 514 I killinfo: [25557,10120,0,0,94252,1,79084]
11-19 22:50:29.811 2034 3827 I am_proc_died: [0,31749,rip.moth.cocoonshell,102,2]
11-19 22:50:30.199 2034 3827 I am_proc_died: [0,2286,rip.moth.cocoonshell,102,2]
11-19 22:50:33.535 2034 10103 I am_proc_died: [0,25557,com.droiddeck.launcher,0,2]
11-19 22:50:34.551 2034 11587 I wm_task_to_front: [0,1408,0]
11-19 22:42:44.766 2034 2707 I wm_create_activity: [0,1239004,1628,com.droiddeck.launcher/.session.KeepTopActivity,NULL,NULL,NULL,411107328]
11-19 22:42:44.816 16856 16856 I wm_on_top_resumed_lost_called: [24689759,com.droiddeck.launcher.SessionActivity,topStateChangedWhenResumed]
11-19 22:42:44.817 16856 16856 I wm_on_top_resumed_lost_called: [24689760,com.droiddeck.launcher.MainActivity,pausing]
"""
class DumpParsingTest(unittest.TestCase):
def test_focused_display(self):
self.assertEqual(2, ab.focused_display(" FocusedDisplayId: 2\n FocusedApplications:\n"))
self.assertIsNone(ab.focused_display(""))
def test_guards_and_sessions_are_counted_on_every_display(self):
self.assertEqual(2, ab.guard_count(ACTIVITIES))
self.assertEqual(1, ab.session_count(ACTIVITIES))
def test_the_bottom_home_is_the_visible_home_on_another_display(self):
self.assertEqual((2, "rip.moth.cocoonshell"), ab.bottom_home(ACTIVITIES, 0))
def test_no_bottom_home_without_another_display(self):
self.assertIsNone(ab.bottom_home(ACTIVITIES.split("\n\n")[1], 0))
def test_panel_windows_are_the_apps_bare_windows_on_that_display(self):
self.assertEqual(1, ab.panel_windows(WINDOWS, 2))
self.assertEqual(1, ab.panel_windows(WINDOWS, 0))
self.assertEqual(0, ab.panel_windows(WINDOWS, 3))
def test_logical_size_follows_rotation(self):
self.assertEqual((1920, 1080), ab.logical_size(DISPLAYS, 0))
self.assertEqual((1280, 960), ab.logical_size(DISPLAYS, 2))
self.assertIsNone(ab.logical_size(DISPLAYS, 5))
class SummaryTest(unittest.TestCase):
def test_max_adj_skips_samples_after_death(self):
self.assertEqual(50, ab.max_adj(["0", "50", "DEAD", ""]))
self.assertIsNone(ab.max_adj(["DEAD"]))
def test_events_summary(self):
summary = ab.summarize_events(EVENTS)
self.assertEqual(3, summary["lmkd_kills"])
self.assertEqual(1, summary["lmkd_kills_down_to_adj0"])
self.assertEqual({"com.droiddeck.launcher": 1, "rip.moth.cocoonshell": 2}, summary["processes_died"])
self.assertEqual(0, summary["droiddeck_died_at_adj"])
self.assertEqual(1, summary["session_top_lost"])
self.assertEqual(1, summary["task_to_front"])
self.assertEqual(1, summary["guard_creates"])
def test_a_quiet_log_summarizes_to_nothing(self):
summary = ab.summarize_events("")
self.assertEqual(0, summary["lmkd_kills"])
self.assertIsNone(summary["droiddeck_died_at_adj"])
self.assertEqual({}, summary["processes_died"])
if __name__ == "__main__":
unittest.main()