fix(session): remove the keep-top guard from other displays (#2937)

* fix(session): remove the keep-top guard from other displays

#2763 put a transparent KeepTopActivity on every other display while a
session was on top, so lmkd killing that display's home could not move focus
off the session. A/B on a 12 GB AYN Thor (Android 13) and a Retroid Pocket
Duo (Android 16) found no case where it kept a session alive: with steady
pressure the bottom home (stock launcher or Cocoon) was killed up to 400
times per run without taking focus, and a burst big enough to matter makes
lmkd kill the session at adj 0 with or without the guard.

Its side effects were real:
- Android's ActivityRecordInputSink made the bottom screen ignore touch
  (worked around in #2910 by stepping aside on touch).
- Cocoon tracks each display's top activity, so it could not suspend or
  resume DroidDeck cleanly.
- The Thor's Game Assistant gives every app with an activity on top of the
  bottom display that display's volume, so DroidDeck's audio followed the
  bottom screen's volume slider.

Removes KeepTopActivity, the focus bounce and light pause, the memory
pressure trigger and their tests. onPause runs its departure cleanup every
time again.

tools/memory_guard_ab.py gains a burst mode, reads oom_score_adj without
su (lmkd kills the root manager app and su can then open its request screen
over the game), handles Android 13 dumps, a hung stop and a session that
does not start. docs/development/memory-guard-ab.md has the Thor results.

* test(session): the guard A/B fill mode starts its counter again, and a pressure run with no completed run fails

* test(session): the burst seed is rebuilt unless it is exactly 256 MiB

* test(session): the guard A/B burst takes its last partial chunk, and only a hog run that finished counts
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-20 11:40:10 -05:00
1 parent acb2cba970
commit d0022a35f9
11 files changed
+149 -380

No files matched your search

-9
View File
@@ -302,15 +302,6 @@
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity
android:name=".session.KeepTopActivity"
android:exported="false"
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity="${applicationId}.keeptop"
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity
android:name=".ui.SessionTypingActivity"
android:exported="false"
@@ -3251,8 +3251,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun onSessionEnded(status: Int) {
ended = true
uiHandler.removeCallbacks(guardWhenRunning)
com.droiddeck.launcher.session.KeepTopActivity.release()
++steamVrRequestGeneration
if (isInPictureInPictureMode) {
runOnUiThread { finish() }
@@ -5740,11 +5738,6 @@ 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()
@@ -5753,8 +5746,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name &&
(requestCode >= 0 || intent.component?.packageName == packageName ||
if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName ||
intent.action in setOf(Intent.ACTION_CHOOSER, Intent.ACTION_SEND, Intent.ACTION_OPEN_DOCUMENT,
Intent.ACTION_GET_CONTENT, "android.settings.PICTURE_IN_PICTURE_SETTINGS"))) pip.background()
super.startActivityForResult(intent, requestCode, options)
@@ -5786,10 +5778,6 @@ 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)
@@ -5834,13 +5822,6 @@ 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
com.droiddeck.launcher.session.LightPause.Resume.CLEANUP_FIRST -> departureCleanup()
com.droiddeck.launcher.session.LightPause.Resume.NORMAL -> Unit
}
drawerGameInventoryRevision++
com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event ->
com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) }
@@ -5906,73 +5887,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(cardboardPrefListener)
}
private var memoryPressureAt = 0L
private var focusBounce = false
private val lightPause = com.droiddeck.launcher.session.LightPause()
private val lightPauseCheck = Runnable { if (lightPause.timedOut()) departureCleanup() }
private var topResumed = false
private val guardWhenRunning = object : Runnable {
override fun run() {
if (!topResumed || isFinishing) return
if (SessionState.running) guardOtherDisplays() else uiHandler.postDelayed(this, 2_000)
}
}
// 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) {
super.onTrimMemory(level)
if (!com.droiddeck.launcher.session.TopUnderPressure.isPressure(level)) return
memoryPressureAt = android.os.SystemClock.elapsedRealtime()
guardOtherDisplays()
}
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
super.onTopResumedActivityChanged(isTopResumedActivity)
topResumed = isTopResumedActivity
uiHandler.removeCallbacks(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 || 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()) {
uiHandler.removeCallbacks(guardWhenRunning)
uiHandler.postDelayed(guardWhenRunning, com.droiddeck.launcher.session.KeepTopActivity.RETRY_MS)
}
if (!bounced) return
if (!wasResumed) return
focusBounce = true
uiHandler.postDelayed({ focusBounce = false }, 500)
}
override fun onPause() {
if (focusBounce) {
focusBounce = false
lightPause.paused(com.droiddeck.launcher.session.KeepTopActivity.bounces)
uiHandler.postDelayed(lightPauseCheck, 200)
} else departureCleanup()
departureCleanup()
super.onPause()
}
@@ -6635,10 +6551,6 @@ 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
frameGenRequests.incrementAndGet()
@@ -1,120 +0,0 @@
package com.droiddeck.launcher.session
import android.app.Activity
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.hardware.display.DisplayManager
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 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)
@Suppress("DEPRECATION") overridePendingTransition(0, 0)
if (intent.getBooleanExtra(EXTRA_BOUNCE, false)) {
bounces++
finish()
return
}
if (intent.getIntExtra(EXTRA_GENERATION, -1) != generation) {
finishAndRemoveTask()
return
}
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()
}
companion object {
private const val TAG = "KeepTop"
private const val EXTRA_BOUNCE = "bounce"
private const val EXTRA_GENERATION = "generation"
private var generation = 0
var bounces = 0
private set
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 || 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)
starting[id] = SystemClock.elapsedRealtime()
started = true
Log.i(TAG, "guarding display $id from a home launcher restart")
}.onFailure { Log.w(TAG, "could not guard display $id", it) }
}
if (!started) return false
return runCatching { launch(context, sessionDisplay, bounce = true) }
.onFailure { Log.w(TAG, "could not return focus to display $sessionDisplay", it) }.isSuccess
}
fun hasPendingStarts() = starting.isNotEmpty()
const val RETRY_MS = START_TIMEOUT_MS + 250
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)
.putExtra(EXTRA_BOUNCE, bounce)
.putExtra(EXTRA_GENERATION, generation)
context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle())
}
}
}
@@ -1,32 +0,0 @@
package com.droiddeck.launcher.session
// Tracks a pause that skipped the session's departure cleanup for the keep-top focus bounce.
internal class LightPause {
private var pending = false
private var bouncesAtPause = 0
fun paused(bounces: Int) {
pending = true
bouncesAtPause = bounces
}
// The bounce resumes the session within tens of milliseconds; still paused at the timeout means
// something else holds the pause.
fun timedOut(): Boolean = take()
fun stopped(): Boolean = take()
fun resumed(bounces: Int): Resume {
if (!pending) return Resume.NORMAL
pending = false
return if (bounces != bouncesAtPause) Resume.LIGHT else Resume.CLEANUP_FIRST
}
private fun take(): Boolean {
val was = pending
pending = false
return was
}
enum class Resume { NORMAL, LIGHT, CLEANUP_FIRST }
}
@@ -2394,8 +2394,7 @@ class SessionService : Service() {
override fun onTaskRemoved(rootIntent: Intent?) {
if (rootIntent?.component?.className in setOf(
com.droiddeck.launcher.ui.DualScreenActivity::class.java.name,
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name,
KeepTopActivity::class.java.name)) return
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return
if (pipTask || xrActivityVisible) {
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
activityVisible = false
@@ -1,13 +0,0 @@
package com.droiddeck.launcher.session
import android.content.ComponentCallbacks2
internal object TopUnderPressure {
const val WINDOW_MS = 5_000L
fun isPressure(level: Int) =
level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL || level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW
fun shouldReclaim(nowMs: Long, pressureAtMs: Long, sessionRunning: Boolean, finishing: Boolean) =
sessionRunning && !finishing && pressureAtMs > 0 && nowMs - pressureAtMs in 0..WINDOW_MS
}
@@ -1,56 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class LightPauseTest {
@Test
fun theBounceAloneResumesLight() {
val pause = LightPause()
pause.paused(bounces = 3)
assertEquals(LightPause.Resume.LIGHT, pause.resumed(bounces = 4))
assertFalse(pause.timedOut())
}
@Test
fun anUnrelatedPauseWithoutABounceCleansUpAtTheTimeout() {
val pause = LightPause()
pause.paused(bounces = 3)
assertTrue(pause.timedOut())
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 3))
}
@Test
fun aBounceWhileAnotherActivityHoldsThePauseStillCleansUpAtTheTimeout() {
val pause = LightPause()
pause.paused(bounces = 3)
assertTrue(pause.timedOut())
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4))
}
@Test
fun aResumeBeforeTheTimeoutWithoutABounceCleansUpFirst() {
val pause = LightPause()
pause.paused(bounces = 3)
assertEquals(LightPause.Resume.CLEANUP_FIRST, pause.resumed(bounces = 3))
assertFalse(pause.timedOut())
}
@Test
fun aStopAfterALightPauseCleansUpOnce() {
val pause = LightPause()
pause.paused(bounces = 3)
assertTrue(pause.stopped())
assertFalse(pause.timedOut())
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4))
}
@Test
fun aNormalPauseIsUntouched() {
val pause = LightPause()
assertFalse(pause.stopped())
assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 0))
}
}
@@ -1,25 +0,0 @@
package com.droiddeck.launcher.session
import android.content.ComponentCallbacks2
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class TopUnderPressureTest {
@Test
fun onlyRunningLevelsCountAsPressure() {
assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL))
assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW))
assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE))
assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN))
}
@Test
fun reclaimsOnlyDuringASessionShortlyAfterPressure() {
assertTrue(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = false))
assertFalse(TopUnderPressure.shouldReclaim(20_000, 9_500, sessionRunning = true, finishing = false))
assertFalse(TopUnderPressure.shouldReclaim(10_000, 0, sessionRunning = true, finishing = false))
assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = false, finishing = false))
assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = true))
}
}
+46 -13
View File
@@ -1,20 +1,24 @@
# 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.
`KeepTopActivity` (#2763, removed in the change that added this section) covered every other
display while a session was on top, so that display's home was not its top activity. The
reasoning: on the Thor, lmkd kills the bottom home under memory pressure, Android relaunches it
to the front, the session loses the top spot, drops to adj 50 and is killed next.
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.
It had three side effects:
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.
- Android gives a translucent activity alone in its task an `ActivityRecordInputSink` that
consumes every touch in the task bounds whatever the window's flags say
(`ENABLE_TOUCH_OPAQUE_ACTIVITIES`), so the bottom screen took no touch (#2910 worked around it).
- Cocoon tracks the top activity of each display; with a DroidDeck activity on the bottom it
could not suspend or resume DroidDeck properly.
- The Thor's `com.odin.gameassistant` gives every app with an activity on top of the bottom
display that display's volume (`secondary_screen_volume_level`). With the guard up, all of
DroidDeck's audio played at the bottom screen's volume (AudioFlinger track gain -37, -13 and
-2.6 dB at levels 3, 8 and 13; -7.4 dB, the top level, once the guard was removed).
The A/B below found no case on either device where the guard kept the session alive, so it was
removed.
## Tool
@@ -25,6 +29,7 @@ build that has the debugging tools:
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 pressure --burst --stop-mb 1500 --hold 20 --runs 3
python3 tools/memory_guard_ab.py --label fix summarize ~/.cache/droiddeck-memory-guard-ab/fix-stop650-1-events.txt
```
@@ -39,6 +44,13 @@ event log of every probe.
`--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.
- `pressure --burst` takes everything above `--stop-mb` at once instead: it copies a 256 MiB
random file into the tmpfs with all copies running in parallel (about 5 GiB in 2 to 3 s on a
Thor), the way a game's GPU allocation burst lands on lmkd.
- `oom_score_adj` is read without `su`. Under pressure lmkd keeps killing the root manager app,
and a `su` call can then open its request screen on top of the game.
- If the bottom display has no home (a killed home is not always restarted), the visible app on
top of it stands in.
- `--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
@@ -88,3 +100,24 @@ moves it to the front, even with no guard. The Thor's focus steal does not happe
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.
## Results: AYN Thor (12 GB), Android 13
Builds: `main` (56986b5, guard with the #2910 touch yield) and `no-guard` (`main` with
`guardOtherDisplays` returning at once). The game was focused on the top screen in every run.
| Pressure | Bottom app | no-guard | main |
| --- | --- | --- | --- |
| Fill to 650 MB free, hold 30 s | stock launcher | survived 1/1 usable run (launcher not reached) | survived 3/3 (launcher killed 80, 25, 0 times) |
| Fill to 550 MB free, hold 30 s | Cocoon as home | survived 3/3, Cocoon killed 387, 400, 84 times | survived 3/3, Cocoon killed 384, 127, 338 times |
| Burst to 400 MB free (about 5 GB in 2.5 to 3.4 s) | stock launcher | killed at adj 0 in 3/3 | killed at adj 0 in 3/3 |
| Burst to 1500 MB free (2.0 to 2.4 s) | stock launcher | survived 1/2, killed at adj 0 in 1/2 | killed at adj 0 in 2/2 |
No run on either build lost the top spot (`wm_on_top_resumed_lost_called` for
`SessionActivity`), moved a task to the front, or killed DroidDeck at adj 50. A killed bottom
home is either restarted in place or its task disappears and the next app shows on the bottom
screen, without taking focus. A burst big enough to matter makes lmkd kill the foreground
session at adj 0, which no activity on another display can prevent.
`kill -9` of the bottom app (`states`) is noisy on a Thor with many recent apps: each kill
surfaces the next app on the bottom screen, and every tap the tool sends there moves focus.
+72 -20
View File
@@ -26,30 +26,52 @@ PACKAGE = "com.droiddeck.launcher"
SESSION = f"{PACKAGE}/.SessionActivity"
HOG_PATH = "/data/local/tmp/dd-memory-hog.sh"
HOG_MOUNT = "/dev/dd-memory-hog"
SEED_PATH = "/data/local/tmp/dd-memory-burst.bin"
# oom_score_adj is read without su: under pressure lmkd kills the root manager app, and each su call
# can then open its request screen on top of the game.
# 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; }}
stop_mb=$1; hold=$2; mode=$3
cleanup() {{ kill $(jobs -p) 2>/dev/null; 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
i=0; failed=0
if [ "$mode" = burst ]; then
[ "$(stat -c %s {SEED_PATH} 2>/dev/null)" = 268435456 ] ||
{{ head -c 268435456 /dev/urandom > {SEED_PATH}.tmp && mv {SEED_PATH}.tmp {SEED_PATH}; }} ||
{{ rm -f {SEED_PATH}.tmp; cleanup; exit 1; }}
cat {SEED_PATH} > /dev/null
avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)
echo "avail=$avail"
take=$((avail - stop_mb))
[ "$take" -gt 0 ] || {{ echo "nothing to take"; cleanup; exit 2; }}
n=$((take / 256)); rest=$((take % 256)); pids=""
echo "burst_mb=$take start=$(date +%s%N)"
while [ $i -lt $n ]; do cat {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; i=$((i+1)); done
[ "$rest" -gt 0 ] && {{ head -c $((rest * 1048576)) {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; }}
for pid in $pids; do wait "$pid" || failed=1; done
echo "burst_done=$(date +%s%N)"
echo "avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)"
i=512
fi
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
head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || {{ failed=1; break; }}
i=$((i+1))
done
[ "$failed" = 0 ] || {{ echo "write failed"; cleanup; exit 1; }}
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*; "
HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; pkill -f '[d]d-memory-burst.bin'; sleep 1; rm -f {HOG_MOUNT}/f*; "
f"umount {HOG_MOUNT} 2>/dev/null; true")
def focused_display(input_dump: str) -> int | None:
@@ -58,7 +80,7 @@ def focused_display(input_dump: str) -> int | 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))
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:
@@ -85,7 +107,8 @@ def panel_windows(windows_dump: str, display: int) -> int:
def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | None:
display = None
"""The visible home on another display, else the visible app on top of it."""
display, top = None, None
for line in activities_dump.splitlines():
section = re.match(r"Display #(\d+) \(activities", line)
if section:
@@ -96,7 +119,10 @@ def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] |
home = re.search(r"type=home A=\d+:(\S+) .*visible=true", line)
if home:
return display, home.group(1)
return None
app = re.search(r"type=standard A=\d+:([\w.]+) .*visible=true", line)
if app and top is None and not app.group(1).startswith(PACKAGE):
top = display, app.group(1)
return top
def logical_size(displays_dump: str, display: int) -> tuple[int, int] | None:
@@ -151,8 +177,11 @@ class Device:
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)
command = [str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args]
try:
return subprocess.run(command, capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return subprocess.CompletedProcess(command, -1, "", f"timed out after {timeout} s")
def phase(self) -> str | None:
match = re.search(r'"phase":\s*"(\w+)"', self.ctl("state").stdout)
@@ -208,7 +237,8 @@ class Bench:
def prepare(self, apk: str | None):
self.d.sh("input keyevent KEYCODE_WAKEUP")
self.d.ctl("stop")
if self.d.ctl("stop", timeout=120).returncode != 0:
self.d.sh(f"am force-stop {PACKAGE}")
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)
@@ -234,7 +264,7 @@ class Bench:
"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),
"adj": int(self.d.sh(f"cat /proc/{pid}/oom_score_adj").strip() or -9999),
"pid": pid,
}
@@ -251,7 +281,8 @@ class Bench:
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"
self.d.su(f"kill -9 $(pidof {home})")
samples = self.d.sh(f"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)
@@ -297,7 +328,7 @@ class Bench:
self.probe("using_bottom_now")
self.game_front()
def pressure(self, run: str, stop_mb: int, hold: int):
def pressure(self, run: str, stop_mb: int, hold: int, burst: bool = False) -> bool:
with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as script:
script.write(HOG)
try:
@@ -305,16 +336,18 @@ class Bench:
finally:
os.unlink(script.name)
self.d.sh(f"chmod 755 {HOG_PATH}")
self.game_front()
self.close_panel()
self.game_front()
self.tap(self.session_display, (0.36, 0.11))
time.sleep(2)
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)}'"],
hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)} {'burst' if burst else 'fill'}'"],
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())
samples.append(self.d.sh(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:
@@ -324,12 +357,19 @@ class Bench:
time.sleep(3)
events = self.d.run("logcat", "-b", "events", "-d")
(self.out / f"{self.label}-{run}-events.txt").write_text(events)
workload_ok = hog.returncode == 0 and "released" in output.splitlines()
if not workload_ok:
print(f"memory-guard-ab: {run}: the memory hog failed (exit {hog.returncode}): "
f"{output.strip().splitlines()[-1] if output.strip() else 'no output'}", file=sys.stderr)
available = [int(value) for value in re.findall(r"avail=(\d+)", output)]
took = re.search(r"start=(\d+).*?burst_done=(\d+)", output, re.S)
self.write("pressure", {
"run": run, "stop_mb": stop_mb, "hold_s": hold, **{k: v for k, v in before.items() if k != "pid"},
"run": run, "workload_ok": workload_ok, "mode": "burst" if burst else "fill", "stop_mb": stop_mb, "hold_s": hold,
"burst_ms": (int(took.group(2)) - int(took.group(1))) // 1_000_000 if took else None, **{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),
})
return workload_ok
def fraction_pair(text: str) -> tuple[float, float]:
@@ -355,6 +395,8 @@ def main() -> int:
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)
pressure.add_argument("--burst", action="store_true",
help="take everything above --stop-mb at once instead of filling 32 MiB at a time")
summarize = commands.add_parser("summarize", help="summarize a saved events log")
summarize.add_argument("events", type=Path)
args = parser.parse_args()
@@ -376,9 +418,19 @@ def main() -> int:
bench.prepare(args.apk)
bench.states()
else:
completed = 0
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)
try:
bench.prepare(args.apk if run == 0 else None)
except RuntimeError as exc:
print(f"memory-guard-ab: run {run + 1} skipped: {exc}", file=sys.stderr)
continue
if bench.pressure(f"{'burst' if args.burst else 'stop'}{args.stop_mb}-{run + 1}", args.stop_mb,
args.hold, args.burst):
completed += 1
if completed == 0:
print("memory-guard-ab: no pressure run completed", file=sys.stderr)
return 1
except RuntimeError as exc:
print(f"memory-guard-ab: {exc}", file=sys.stderr)
return 1
+28
View File
@@ -66,6 +66,15 @@ class DumpParsingTest(unittest.TestCase):
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_android_13_activity_records_are_counted(self):
self.assertEqual(1, ab.session_count(
" * Hist #1: ActivityRecord{e1ec207 u0 com.droiddeck.launcher/.SessionActivity} t14519}\n"))
def test_the_visible_app_stands_in_when_no_home_is_on_the_other_display(self):
dump = ("Display #4 (activities from top to bottom):\n"
" * Task{21f60d6 #14493 type=standard A=10113:com.discord U=0 visible=true visibleRequested=true mode=fullscreen}\n")
self.assertEqual((4, "com.discord"), ab.bottom_home(dump, 0))
def test_no_bottom_home_without_another_display(self):
self.assertIsNone(ab.bottom_home(ACTIVITIES.split("\n\n")[1], 0))
@@ -80,6 +89,25 @@ class DumpParsingTest(unittest.TestCase):
self.assertIsNone(ab.logical_size(DISPLAYS, 5))
class HogScriptTest(unittest.TestCase):
def test_both_modes_start_the_fill_counter(self):
script = ab.HOG.splitlines()
counter = next(n for n, line in enumerate(script) if line.startswith("i=0"))
self.assertLess(counter, script.index('if [ "$mode" = burst ]; then'))
self.assertLess(counter, next(n for n, line in enumerate(script) if line.startswith("while [ $i -lt 512 ]")))
def test_a_failed_write_never_reports_released(self):
script = ab.HOG.splitlines()
check = script.index('[ "$failed" = 0 ] || { echo "write failed"; cleanup; exit 1; }')
self.assertLess(check, script.index("echo released"))
self.assertIn("failed=1", ab.HOG.split("echo released")[0])
def test_a_burst_takes_the_remainder_below_one_chunk(self):
self.assertIn("rest=$((take % 256))", ab.HOG)
self.assertIn('echo "nothing to take"', ab.HOG)
class SummaryTest(unittest.TestCase):
def test_max_adj_skips_samples_after_death(self):
self.assertEqual(50, ab.max_adj(["0", "50", "DEAD", ""]))