refactor(steam): keep Steam Lite as a measuring tool and research record

This commit is contained in:
Kurt Himebauch committed 2026-11-26 21:33:57 -05:00
1 parent ec802525ae
commit 225eba2a97
6 files changed
+342 -976

No files matched your search

+263 -246
View File
@@ -1,197 +1,176 @@
# Steam Lite Runtime (experiment)
# Steam web helper memory (Steam Lite Runtime research record)
An opt-in supervisor, `droiddeck-steam-lite`, that asks Valve's own Steam web helper to give
memory back while a game is in front, through the client's loopback DevTools endpoint and the
session's existing zRAM preload. It adds no UI, edits no Valve files and does nothing unless a
developer turns it on. Stock stays the default.
Can DroidDeck make Valve's own Steam web helper (CEF) use less memory and CPU while a game runs,
without replacing or degrading it? This records what was measured on two 8 GB handhelds, which
approaches worked, which did not, and what is left to investigate.
## Results in short
Nothing here changes a default. The tree keeps:
Measured on two 8 GB handhelds (Retroid Pocket Duo Lite Plus and Retroid Pocket Duo: Qualcomm
CQ7790S, 7.2 GiB, 6 GiB zRAM, Android 16, kernel 6.6), DroidDeck at main `46f99b9` plus this
branch, Run without proot, the native arm64 Steam client (build 1793740892, CEF Chrome
126.0.6478.183, V8 12.6), 1280×720 Big Picture:
- `droiddeck-steam-lite`, a guest measuring tool: `probe`, `sample`, `record`, and `apply`, which
runs a single intervention to reproduce the results below.
- `tools/steam_lite_bench.py` and `tools/steam_lite_charts.py`, which drive the devices and draw
the charts.
- The raw data under `evidence/steam-lite/data`.
- `DD_STEAM_CEF_GPU=0`, a session switch that draws the web helper fully in software.
- **Where Steam's memory is:** 0.9–1.1 GiB of PSS in the library (renderer 320–530 MiB, browser
300–340 MiB of which ~80 MiB is the shared, clean `libcef.so`, client ~220 MiB, network and
storage services ~70 MiB), plus **190–260 MiB of KGSL GPU memory** in the browser process (the GPU
runs in-process). KGSL is unswappable and not in PSS. Some sessions held 650–1080 MiB of it
until the overlay was opened once; that state was not reproducible on demand.
- **Frame pacing:** with Sonic Mania in front on the Duo, stock, L1, L2 and soft compositing all
ran at 58.5–59.4 fps with a 16 ms p95. In those L1 and L2 runs the supervisor had nothing to do
(the monitor had already paged the client out), so this covers soft compositing and an idle
supervisor only; pacing during an active L1/L2 pass and under L3 was not measured.
- **The one large, safe saving is compositing the web helper in software**
(`DD_STEAM_SOFT_COMPOSITING=1`, already used for the open driver pair): KGSL 239 → 26 MiB in the
library, for +0.9 points of one core and +25 MiB of PSS, about 190 MiB net, and the UI looks the
same. Drawing it fully in software (`DD_STEAM_CEF_GPU=0`) saves the same and nothing more.
- **Page-out (level 2) works and is large once the zRAM preload answers:** 447 MB of the client paged
out in one pass, the client at 674 MiB resident with a game in front against ~900 for stock, and
+136 MiB `MemAvailable`. With #3293 the session's own monitor usually pages the client out during
the launch already (140–350 MiB), and level 2 then correctly does nothing.
- **GC (level 1) is not worth having:** −27 to −40 MiB of renderer right after it runs, but 80 s into
a game level 1 and stock are the same (875–889 vs 902 MiB with nothing paged out): V8's own idle
memory reducer gets there anyway. Pressure notifications (moderate, critical, on the renderer or
the browser), pausing hidden animations, minimizing or hiding the window, and the V8 or GPU-budget
flags gave nothing or made it worse.
- **Arcade Paradise's out-of-memory kill is not Steam's to fix:** loading a save made the game
allocate **1.7 GB of KGSL memory in 22 s** (unevictable rose 1.37 → 3.05 GiB) and lmkd killed the
session on a PSI stall with 0.8–1.0 GiB still "available" and 5 GiB of zRAM free. All 9 trials that
loaded were killed, whatever the arm (stock, level 1, soft compositing, both), and so were two
runs with no tooling at all. Nothing Steam can give back (40–400 MiB) covers that.
- **The zRAM preload did nothing on native userland sessions** (any process, game or client): it
opened `/tmp/.dd-zram` with raw system calls the native hook does not map. Fixed in #3293.
The opt-in supervisor that ran interventions automatically (`DD_STEAM_LITE` levels 1–3) was
removed after the measurements. Its last version, with its state machine and tests, is commit
`7cc65e0c9` in PR #3301.
| Profile | RAM in game (Lite Plus, Bully) | CPU | Frame or overlay cost | Visual change | Brittleness | Overhead | Recommendation |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Stock | 723–902 MiB resident, 0–231 MiB paged by the monitor | web helper 2.1–2.9 % of one core | — | — | — | — | default |
| L1 conservative | 875–889 MiB resident: no lasting saving | 2.2–2.6 % | overlay unchanged (tool-bound 4.0–4.1 s) | none | low: public `HeapProfiler`/`Memory` | one 0.3–0.45 s pass; supervisor 18 MiB PSS, ~0.15 % CPU | do not promote |
| L2 balanced | 674 MiB resident when it paged out (447 MB); skipped twice because the monitor had already paged 123–353 MB | 2.4–2.8 % | overlay unchanged; read-back on return | none | low: DroidDeck's own preload protocol | 3.5 s pass, off the UI thread | keep as an experiment; only useful with #3293, and then mostly redundant with the monitor |
| L3 aggressive | not measured beyond the ablation: critical pressure freed ~0, no outside pages existed to freeze | — | — | none | medium: `Page.setWebLifecycleState` on store pages | — | do not promote |
| Soft compositing | KGSL −213 to −218 MiB, PSS +23 to +31 MiB (library); +176 MiB `MemAvailable` in game on the Duo (median of 3) | +0.9 points (library idle); one in-game run 11.4 % | game frame pacing unchanged; scrolling smoothness not measured | none seen | low: existing DroidDeck switch | none | best candidate to promote for ≤8 GB devices, after a smoothness check on a scrolling library |
## Conclusions
Not run: a 3–4 GB device (none available), a Mali/vkbridge device, the x86_64 client, frame
pacing of a heavy game under each profile (measured with Sonic Mania only), scroll smoothness,
suspend/resume, downloads, store pages and friends/chat under each level. Durability against future Steam builds is unknown.
Measured on a Retroid Pocket Duo Lite Plus and a Retroid Pocket Duo (Qualcomm CQ7790S, 7.2 GiB,
6 GiB zRAM, Android 16, kernel 6.6). Both ran without proot, with the native arm64 Steam client
(build 1793740892, CEF Chrome 126.0.6478.183, V8 12.6) and 1280×720 Big Picture.
## Turning it on
| Setting | Where | Effect |
| Approach | Measured | Verdict |
| --- | --- | --- |
| `DD_STEAM_LITE=1` (`conservative`) | `tools/droiddeckctl env set --persistent`, or the `droiddeck-env` file | One V8 GC (and a moderate pressure notification) when a game takes focus, again on sustained memory pressure. |
| `DD_STEAM_LITE=2` (`balanced`) | same | Level 1, then the client's cold memory paged out through the zRAM preload; read back the moment the client is in front. Needs the preload to answer on native userland sessions (#3293). |
| `DD_STEAM_LITE=3` (`aggressive`) | same | Level 2 plus a critical pressure notification and freezing pages from outside the client (store or community views). |
| `DD_STEAM_LITE_SWITCHES=+pause,-gc,...` | same | One intervention on or off on top of the level: `gc`, `moderate`, `pageout`, `critical`, `freeze`, and `pause`, which no level turns on (it measured no effect). |
| `agent/steam-lite.json` in the session folder | written at runtime (`tools/steam_lite_bench.py` does) | `{"level": "...", "switches": "..."}` replaces both while the session runs; `{"level": "stock"}` restores everything held and idles. |
| Software compositing (`DD_STEAM_SOFT_COMPOSITING=1`, existing) | KGSL 239 → 26 MiB in the library, about 190 MiB net after +25 MiB PSS; +0.9 points of one core; +176 MiB `MemAvailable` in game on the Duo (median of 3); game frame pacing unchanged; the UI looks the same | **pursue as the default on ≤8 GB devices**, after the checks below |
| The zRAM preload fix (#3293, merged) | the preload never paged anything out on native userland sessions; with the fix the session's own monitor pages 140–400 MiB of the client out during a game launch | **shipped**; the largest win of the work |
| Cold page-out of the client on demand (supervisor level 2) | 447 MB in one pass, client 674 MiB resident against ~900 for stock, +136 MiB `MemAvailable` | mostly redundant: with #3293 the monitor has usually done it already |
| V8 GC when a game takes focus (level 1) | −27 to −40 MiB right after; the same as stock 80 s later | dropped: V8's idle memory reducer gets there anyway |
| Memory pressure notifications (renderer or browser target) | 0 to −2 MiB; the visible UI regrows | dropped |
| Pausing hidden animations | CPU 2.7–2.8 % before and after | dropped: the hidden UI already does not draw |
| V8 small-heap and GPU-budget flags | renderer 160–200 MiB *larger* | dropped |
| Freezing pages from outside the client (level 3) | no such pages existed in the runs | not enough evidence either way |
| `DD_STEAM_CEF_GPU=0` (full software drawing) | saves the same as software compositing and nothing more | kept as a measuring switch |
Unset, `0`, `off` or `stock`: `droiddeck-session` does not start the supervisor. That is the kill
switch: remove the variable and start a new session. It only runs in the gamepad Steam session.
Other findings:
`DD_STEAM_CEF_GPU=0` (new) draws the web helper in software on any device, the way low-RAM Mali
bridge devices already do; `DD_STEAM_SOFT_COMPOSITING=1` (existing) composites in software and
keeps GPU raster. Both are measured below as separately controlled variables; neither changes a
default.
- **Where Steam's memory is:** 0.9–1.1 GiB of PSS in the library, plus **190–260 MiB of KGSL GPU
memory** in the browser process. The GPU runs in-process there. KGSL memory cannot be swapped and
is not counted in PSS.
- PSS by process: renderer 320–530 MiB; browser 300–340 MiB, of which about 80 MiB is the
shared, clean `libcef.so`; client about 220 MiB; network and storage services about 70 MiB.
- **A high-GPU state:** some sessions held 650–1080 MiB of KGSL for the web helper, as untyped
Vulkan allocations from ANGLE. On the Duo Lite Plus, opening the overlay once released it (3 of
3 sessions). On the Duo it did not: 936 → 839 → 911 MiB. The state was not reproducible on
demand.
- **Arcade Paradise's out-of-memory kill is not Steam's:** loading a save made the game allocate
1.7 GB of KGSL memory in 22 s, and lmkd killed the session on a PSI stall. That happened in every
arm and also with no tooling at all.
## How it works
## Next research
```mermaid
flowchart LR
subgraph guest[Session guest]
agent[droiddeck-agent<br/>publishes focus.json<br/>loopback CDP client]
lite[droiddeck-steam-lite run]
zram[zRAM monitor<br/>in droiddeck-session]
subgraph steam[Steam client]
client[steam]
browser[steamwebhelper browser<br/>in-process GPU]
renderer[renderer: SharedJSContext<br/>+ window popups]
end
end
agent -- focus.json --> lite
lite -- imports WebSocket / cdp_targets --> agent
lite -- HeapProfiler / Memory / Animation / Page<br/>127.0.0.1, guarded port --> renderer
lite -- /tmp/.dd-zram.hold: empty, or a 2 &lt;kB&gt; / 0 request --> zram
lite -- SIGURG with the request in the hold --> steam
zram -- SIGURG trims --> steam
```
1. **Validate software compositing as a default on ≤8 GB devices.** Scroll and animation
smoothness in the library, store and friends views have not been measured yet. Also measure
the CPU cost when hidden UI work runs (one in-game run spent 11.4 % of a core), on a Mali or
vkbridge device, and on a 3–4 GB device.
2. **The 650–1080 MiB ANGLE/Vulkan state:**
- what allocates it and when;
- why the overlay releases it on one device and not the other;
- whether a CEF or ANGLE setting bounds it.
3. **Artwork:** how the library decodes and caches artwork, and whether right-sized assets would
shrink the renderer. This was not explored.
4. **Arcade Paradise's GPU memory,** independently of Steam. Options include the game's texture
settings and a cap in the translation layer.
- **Signals reused:** gamescope focus from `agent/focus.json` (written by `droiddeck-agent`, the
same file `droiddeck-launcher-cores` and the zRAM monitor read), `/proc/meminfo`, and the
client's swap from `/proc/<pid>/status`.
- **DevTools reused:** the supervisor loads `droiddeck-agent` as a module and uses its
loopback-only `WebSocket` and `cdp_targets`, on the port `droiddeck-session` already opens for
the agent and guards to guest processes. No new port, listener or protocol.
- **States:** `ui` (the client is in front or no game is running: nothing runs), `launching` (a game
is focusable but not in front), `game` (in front for 4 s: passes may run), `back` (the client came
in front of a running game: page-out is read back and everything held is restored at once).
- **Passes:** an `enter` pass when a game takes focus, not repeated within 120 s, so opening and
closing the overlay does not cycle GC, page-out and read-back. A `pressure` pass when
`MemAvailable` has stayed below the zRAM monitor's floor (one eighth of RAM, 640–1280 MiB) for 10 s,
at most every 120 s and four times per game. A pass has a 12 s budget and every DevTools call 5 s,
and before every step it re-reads focus and stops if the client came to the front.
- **zRAM coordination:** a GC walks the whole V8 heap, so after the client has been paged out it
would read it back. A pass skips reclaim when more than 32 MiB of the client is already in swap,
and holds the monitor off with an empty `/tmp/.dd-zram.hold` while it runs. Page-out writes its
request (`2 <kB>`, the monitor's own cold-only trim) into that hold, signals the client's
processes and collects their `.trim.<pid>` answers. Read-back writes `0` the same way. The hold
is created exclusively and removed only while it is still the same file with what was written in
it: the app writes its suspend requests into that file and deletes it itself
(`SessionSuspendController`).
- **Rollback:** pause, freeze and page-out are undone when the client comes to the front, the game
exits, the level is switched to stock at runtime, or the supervisor gets SIGTERM, SIGHUP, SIGINT
or loses its parent. GC and pressure notifications need no undo.
- **No DevTools:** a missing port, target or method makes a pass record an error and change
nothing. A method the client answers with JSON-RPC `-32601` is remembered and not called again.
The supervisor never restarts Steam.
## What the client supports
## Interventions
The probe (`droiddeck-steam-lite probe`) found Chrome 126 / V8 12.6. These methods all answered:
| Name | Mechanism | Targets | Level |
- `Runtime.getHeapUsage`, `Memory.getDOMCounters` and `Performance.getMetrics`
- `HeapProfiler.collectGarbage`
- `Memory.simulatePressureNotification`, on the renderer and on the browser target
- `Animation.*`
- `Emulation.setEmulatedMedia`
- `Page.setWebLifecycleState`
`Browser.getWindowForTarget` answers "Browser window not found" for every client window, because
Steam's CEF windows are not Chrome browser windows.
The client's windows (`Steam Big Picture Mode`, `MainMenu`, `QuickAccess`, notification toasts)
are `about:blank?browserviewpopup…` popups of `SharedJSContext`. They share its renderer and V8
heap. The client starts the web helper itself with `--remote-debugging-address=127.0.0.1`.
## Interventions tried
`droiddeck-steam-lite apply ACTION` runs one of these in a running session:
| Action | Mechanism | Targets | Supervisor level |
| --- | --- | --- | --- |
| `gc` | `HeapProfiler.collectGarbage` | `SharedJSContext` (every client window is one of its popups and shares its renderer) and each page from outside the client | 1 |
| `gc` | `HeapProfiler.collectGarbage` | `SharedJSContext` and each page from outside the client | 1 |
| `moderate` | `Memory.simulatePressureNotification` `moderate` | same | 1 |
| `pause` | `Animation.setPlaybackRate 0`, undone with `1` | client window popups, not `SharedJSContext` | switch only |
| `pageout` | zRAM preload request `2 <kB>` (cold pages only, 1 GiB budget), read back with `0` | `steam` and every `steamwebhelper` process | 2 |
| `critical` | `Memory.simulatePressureNotification` `critical` (replaces `moderate`) | same as `gc` | 3 |
| `freeze` | `Page.setWebLifecycleState frozen`, undone with `active` | only pages outside `steamloopback.host` and `about:blank` popups | 3 |
| `pageout` | zRAM preload request `2 <kB>` (cold pages only, 1 GiB budget); `readback` sends `0` | `steam` and every `steamwebhelper` process | 2 |
| `critical` | `Memory.simulatePressureNotification` `critical` | same as `gc` | 3 |
| `freeze`, `thaw` | `Page.setWebLifecycleState` `frozen` / `active` | only pages outside `steamloopback.host` and the `about:blank` popups | 3 |
| `pause`, `resume` | `Animation.setPlaybackRate` 0 / 1 | client window popups, not `SharedJSContext` | switch only |
| `browser-moderate`, `browser-critical` | pressure on the browser target | browser | — |
| `hide`, `show` | `Browser.setWindowBounds` | client windows | — |
| `motion`, `nomotion` | `prefers-reduced-motion` emulation | client windows | — |
`droiddeck-steam-lite apply` also has one-shot actions that are not part of any level, kept to
reproduce the negative results below: `browser-moderate`, `browser-critical` (pressure on the
browser target), `hide`/`show` (`Browser.setWindowBounds`), `motion`/`nomotion`
(`prefers-reduced-motion` emulation).
Page-out uses the session's own zRAM protocol:
The main UI target and the browser process are never frozen or killed: Steam Input, the overlay
and notifications run through them.
1. It creates `/tmp/.dd-zram.hold` exclusively and writes the request into it.
2. It sends `SIGURG` to the client's processes.
3. It collects their `.trim.<pid>` answers.
The hold is removed only while it is still the same file with the same content. The app writes
its suspend requests into that file and deletes it itself (`SessionSuspendController`).
The supervisor ran these as follows:
- Passes ran 4 s after a game took focus, and when `MemAvailable` stayed below the monitor's floor
for 10 s.
- Each pass had a 12 s budget, and it stopped as soon as the client came back in front.
- Pause, freeze and page-out were undone when the client returned.
- Reclaim was skipped when more than 32 MiB of the client was already swapped, because a GC walks
the whole heap and would read it back.
## Findings
Every number below comes from `docs/development/evidence/steam-lite/data` (raw JSON and JSONL)
through `tools/steam_lite_charts.py`, which also writes the complete tables
([Duo Lite Plus](evidence/steam-lite/duo-lite-plus-tables.md), [Duo](evidence/steam-lite/duo-tables.md)).
Charts start at zero and show every run as a dot beside the median bar.
### What the client supports
The probe (`droiddeck-steam-lite probe`) found Chrome 126 / V8 12.6 with `Runtime.getHeapUsage`,
`Memory.getDOMCounters`, `Performance.getMetrics`, `HeapProfiler.collectGarbage`,
`Memory.simulatePressureNotification` (renderer and browser target), `Animation.*`,
`Emulation.setEmulatedMedia` and `Page.setWebLifecycleState` all answering. `Browser.getWindowForTarget`
answers "Browser window not found" for every client window: Steam's CEF windows are not Chrome
browser windows. The client's windows (`Steam Big Picture Mode`, `MainMenu`, `QuickAccess`,
notification toasts) are `about:blank?browserviewpopup…` popups of `SharedJSContext` and share its
renderer and V8 heap. The client starts the web helper itself with
`--remote-debugging-address=127.0.0.1`.
Every number below comes from `evidence/steam-lite/data`, through `tools/steam_lite_charts.py`. The
same script writes the complete tables:
[Duo Lite Plus](evidence/steam-lite/duo-lite-plus-tables.md),
[Duo](evidence/steam-lite/duo-tables.md). Charts start at zero and show every run as a dot beside
the median bar. L1, L2 and L3 are the removed supervisor's levels.
### Where the memory is
Library idle on the Duo Lite Plus, renderer by mapping: V8 heap 105 MiB, `libcef.so` 79 MiB (file,
clean, shared with the other helpers), other anonymous 48 MiB, malloc heap 25 MiB, PartitionAlloc
20 MiB. `Runtime.getHeapUsage` reported 117 MiB used of a 142 MiB JS heap, so most of the renderer
is outside JavaScript. With a game in front the web helper uses 2–3 % of one core: DroidDeck's
Library idle on the Duo Lite Plus, renderer by mapping:
| Mapping | MiB |
| --- | --- |
| V8 heap | 105 |
| `libcef.so` (file, clean, shared with the other helpers) | 79 |
| Other anonymous | 48 |
| malloc heap | 25 |
| PartitionAlloc | 20 |
`Runtime.getHeapUsage` reported 117 MiB used of a 142 MiB JS heap, so most of the renderer is
outside JavaScript. With a game in front the web helper uses 2–3 % of one core, because DroidDeck's
composition already keeps the hidden UI from drawing.
### One intervention at a time
![ablation in game](evidence/steam-lite/duo-lite-plus-ablate-bully-ingame.svg)
With Bully in front, a GC freed 40 MiB of renderer within 20 s and kept it for the 40 s measured;
moderate and critical pressure afterwards changed nothing, and neither did pausing the hidden
windows' animations (CPU 2.7–2.8 % before and after). In the library a GC freed 27 MiB only after
20 s (V8 releases pages lazily), and critical pressure was followed by the visible UI growing 23 MiB
back. Pressure on the browser target ([chart](evidence/steam-lite/duo-lite-plus-ablate-bully-browser-target.svg))
changed nothing, KGSL included. In the `hide` ablation ([chart](evidence/steam-lite/duo-lite-plus-ablate-bully-hide.svg))
the `Browser.setWindowBounds` call itself failed; the −39 MiB 20 s later is the supervisor's own
GC from the game launch arriving. `SteamClient.Window.HideWindow` made the window report
`hidden` but freed 2 MiB of KGSL, and `ShowWindow` did not report it visible again until the
overlay was opened, so it was not pursued.
- **With Bully in front:**
- A GC freed 40 MiB of renderer within 20 s and kept it for the 40 s measured.
- Moderate and critical pressure afterwards changed nothing.
- Pausing the hidden windows' animations changed nothing either: CPU was 2.7–2.8 % before and
after.
- **In the library:**
- A GC freed 27 MiB, but only after 20 s, because V8 releases pages lazily.
- After critical pressure, the visible UI grew 23 MiB back.
- **Pressure on the browser target** ([chart](evidence/steam-lite/duo-lite-plus-ablate-bully-browser-target.svg))
changed nothing, KGSL included.
- **Minimizing the window** ([chart](evidence/steam-lite/duo-lite-plus-ablate-bully-hide.svg)): the
`Browser.setWindowBounds` call itself failed. The −39 MiB 20 s later is the supervisor's own GC
from the game launch arriving.
- **`SteamClient.Window.HideWindow`** made the window report `hidden` but freed only 2 MiB of KGSL.
After `ShowWindow`, the window did not report visible again until the overlay was opened.
### Steady state with a game in front
![steady state](evidence/steam-lite/duo-lite-plus-steady.svg)
Nine fresh sessions on the Duo Lite Plus with #3293 in the build, three per profile, interleaved
(stock, L1, L2), Bully in front, sampled 80 s after it took focus. What paged the client out varied
run to run: the session's monitor pages the client out when the launch makes memory fall fast, so
resident PSS alone mixes in the monitor's decisions; the table lists both.
(stock, L1, L2), Bully in front, sampled 80 s after it took focus.
The session's zRAM monitor pages the client out when a launch makes memory fall fast, so what got
paged out varied from run to run. Resident PSS alone would mix in the monitor's decisions, so the
table lists both.
| Profile | Resident PSS (MiB) | Paged out (MiB) | Renderer (MiB) | Web helper CPU (% of a core) | What the supervisor did |
| --- | --- | --- | --- | --- | --- |
@@ -199,19 +178,20 @@ resident PSS alone mixes in the monitor's decisions; the table lists both.
| L1 | 883, 875, 889 | 0, 0, 0 | 310, 297, 305 | 2.2, 2.6, 2.6 | GC 293–376 ms |
| L2 | 785, 796, 674 | 172, 216 (monitor), 226 (its own) | 283, 283, 235 | 2.4, 2.7, 2.8 | skipped twice (client already in zRAM), once GC + 447 MB page-out in 3.5 s |
Overlay round trips opened and closed in 4.0–4.1 s in every profile; that figure is almost all the
tool (a fresh virtual pad per press and 0.2 s focus polling), so it only shows that no profile added
a delay the tool could see. The overlay looked the same in every profile
([stock](evidence/steam-lite/overlay-stock.jpg), [L1](evidence/steam-lite/overlay-l1.jpg),
[L2](evidence/steam-lite/overlay-l2.jpg)), and controller input, notifications and Resume game kept
working.
Overlay round trips opened and closed in 4.0–4.1 s in every profile. That figure is almost all the
tool (a fresh virtual pad per press and 0.2 s focus polling), so it only shows that no profile
added a delay the tool could see.
The overlay looked the same in every profile ([stock](evidence/steam-lite/overlay-stock.jpg),
[L1](evidence/steam-lite/overlay-l1.jpg), [L2](evidence/steam-lite/overlay-l2.jpg)). Controller
input, notifications and Resume game kept working.
### Frame pacing with a light game (Duo, Sonic Mania)
![steady state, Duo](evidence/steam-lite/duo-steady.svg)
Ten fresh sessions on the rooted Duo with #3293 in the build, Sonic Mania (584400) on its animated
title in front, a 20 s SurfaceFlinger capture 60 s after it took focus:
Ten fresh sessions on the rooted Duo with #3293 in the build. Sonic Mania (584400) was on its
animated title in front, with a 20 s SurfaceFlinger capture 60 s after it took focus:
| Profile | Runs | FPS | p95 / p99 (ms) | Frames off cadence | MemAvailable in game (MiB) | KGSL (MiB) | Web helper CPU (% of a core) |
| --- | --- | --- | --- | --- | --- | --- | --- |
@@ -220,25 +200,29 @@ title in front, a 20 s SurfaceFlinger capture 60 s after it took focus:
| L2 | 2 | 59.2, 58.5 | 16 / 25 | 1.7–5.2 % | 2587 (KGSL 936), 3169 | 239–936 | 2.0–3.6 |
| soft compositing | 3 | 59.3, 59.2, 59.2 | 16 / 25 | 1.8–3.0 % | 3435, 3373, 3367 | 26 | 1.7–2.9, once 11.4 |
No measured profile changed the game's frame rate or p95, and the off-cadence spread is run-to-run
noise. In all four L1 and L2 runs, though, the supervisor did nothing, because the monitor had
already put 165–404 MB of the client in zRAM before the game took focus, so these runs show an
idle supervisor; pacing while a GC or page-out pass runs, and under L3, is untested. Soft compositing left the most memory available
(median 3373 against 3197 MiB for stock). One soft-compositing run spent 11.4 % of a core in the web
helper while the renderer grew 43 MiB: some UI work ran while hidden, and drawing in software makes
that cost CPU instead of GPU; the other two runs used 1.7 and 2.9 %.
- **Frame rate:** no profile changed the game's frame rate or p95. The off-cadence spread is
run-to-run noise.
- **L1 and L2 runs:** in all four, the supervisor did nothing, because the monitor had already put
165–404 MB of the client in zRAM.
- **Memory:** soft compositing left the most memory available, a median of 3373 against 3197 MiB
for stock.
- **CPU:** one soft-compositing run spent 11.4 % of a core in the web helper while the renderer
grew 43 MiB. Some UI work ran while hidden, and drawing in software makes that cost CPU instead
of GPU. The other two runs used 1.7 and 2.9 %.
With root, KGSL's per-process `memtype` showed all of the web helper's GPU memory as untyped Vulkan
allocations (`any(0)`, ANGLE on Vulkan), 942 MB in the session that held the high state. Marking the
process `background` in `/sys/class/kgsl/kgsl/proc/<pid>/state`, which Qualcomm's process reclaim
uses, reclaimed nothing in 15 s (`gpumem_reclaimed` stayed 0).
allocations (`any(0)`, ANGLE on Vulkan): 942 MB in the session that held the high state.
Qualcomm's process reclaim works by marking a process `background` in
`/sys/class/kgsl/kgsl/proc/<pid>/state`. Doing that reclaimed nothing in 15 s: `gpumem_reclaimed`
stayed 0.
### Web helper variants (session restarts)
![flag variants](evidence/steam-lite/duo-flags.svg)
The Duo, library idle, one fresh session per run. The renderer is bimodal from session to session
(319–529 MiB on default flags), which is why every run is shown:
The Duo, library idle, one fresh session per run. Every run is shown because the renderer size is
bimodal from session to session (319–529 MiB on default flags). Sizes are in MiB, as a median with
the range:
| Variant | Runs | Client tree PSS | Renderer | KGSL |
| --- | --- | --- | --- | --- |
@@ -248,113 +232,146 @@ The Duo, library idle, one fresh session per run. The renderer is bimodal from s
| `--js-flags=--optimize-for-size,--max-semi-space-size=2` | 5 | 1114 (1098–1134) | 519 (497–542) | 202 (194–277) |
| `--force-gpu-mem-available-mb=96 --force-gpu-mem-discardable-limit-mb=32` | 2 | 1157 (1156–1158) | 568 (553–584) | 246 (236–256) |
On the Duo Lite Plus, 90–110 s after start, soft compositing cost 2.6 against 1.7 % of one core in
both pairs of runs and saved 213–218 MiB of KGSL ([library, GPU](evidence/steam-lite/library-gpu-compositing.jpg),
[library, software](evidence/steam-lite/library-soft-compositing.jpg)).
On the Duo Lite Plus, 90–110 s after start, both pairs of runs gave the same result:
- **CPU:** soft compositing used 2.6 % of one core, against 1.7 % with GPU compositing.
- **GPU memory:** it saved 213–218 MiB of KGSL.
- **Screenshots:** [library, GPU](evidence/steam-lite/library-gpu-compositing.jpg),
[library, software](evidence/steam-lite/library-soft-compositing.jpg).
### Arcade Paradise's save load
![oom trials](evidence/steam-lite/duo-lite-plus-1388870-oom.svg)
Each trial started a fresh session, launched the game, loaded the save from its menu and watched
for 90 s; a trial counted only once `MemAvailable` fell 400 MiB or the session died. Every loaded
trial was killed 17–33 s after Continue, in every arm. Android recorded `LOW_MEMORY`; lmkd's
`killinfo` gave reason 1 (`NOT_RESPONDING`, its PSI stall trigger) with 13–264 MB free,
3.5–3.8 GB cached and 4.7–5.3 GB of swap free.
Each trial:
1. started a fresh session and launched the game;
2. loaded the save from its menu;
3. counted only once `MemAvailable` fell 400 MiB or the session died;
4. watched for 90 s.
Every loaded trial was killed 17–33 s after Continue, in every arm (stock, L1, soft compositing,
both). Android recorded `LOW_MEMORY`. lmkd's `killinfo` gave reason 1 (`NOT_RESPONDING`, its PSI
stall trigger), with 13–264 MB free, 3.5–3.8 GB cached and 4.7–5.3 GB of swap free.
![what fills memory](evidence/steam-lite/duo-lite-plus-burst-arcade-paradise.svg)
Sampling every half second shows why: during the load the game's own KGSL allocation grew from
835 MiB to 2513 MiB, and system unevictable memory with it, while the Steam web helper stayed at
167 MiB. GPU memory can neither be compressed nor reclaimed, so the stall grows until lmkd steps
in. This is the same unevictable/shmem growth `low-memory.md` records for the Caravan save load, there left unattributed.
The fix belongs with the game's GPU memory (its texture settings, or a cap in the translation
layer), not with Steam.
Sampling every half second shows why:
- During the load, the game's own KGSL allocation grew from 835 MiB to 2513 MiB.
- System unevictable memory grew with it, from 1.37 to 3.05 GiB.
- The Steam web helper stayed at 167 MiB.
GPU memory can neither be compressed nor reclaimed, so the stall grows until lmkd steps in. This is
the same unevictable/shmem growth that `low-memory.md` records, unattributed, for the Caravan save
load.
### zRAM preload on native userland sessions
`SigCgt` showed `SIGURG` unhandled in every Steam and Wine process of a native session although
`libddsession.so` was loaded: its constructor looked for `/tmp/.dd-zram` with a raw `openat` that the
native hook does not map, found nothing and installed no handler. The monitor's requests were
ignored and the client was never paged out. #3293 resolves the control files under `DDNATV_ROOT`;
with it every client process answered (690 MB paged out in one request, all read back).
On a native session, `SigCgt` showed `SIGURG` unhandled in every Steam and Wine process, although
`libddsession.so` was loaded:
### Negative results kept
- The preload's constructor looked for `/tmp/.dd-zram` with a raw `openat`.
- The native hook does not map raw system calls, so the preload found nothing and installed no
handler.
- The monitor's requests were therefore ignored, and the client was never paged out.
#3293 resolves the control files under `DDNATV_ROOT`. With it, on the Duo, every client process
answered:
- A single request paged out 690 MB.
- The Steam tree went from 1,182 to 552 MiB PSS.
- `MemAvailable` rose from 3,251 to 3,660 MiB.
- The read-back request brought it all back.
### Negative results
| Idea | Result | Why it was dropped |
| --- | --- | --- |
| Moderate or critical pressure notification, renderer | 0 to −2 MiB, visible UI regrows | nothing to reclaim that GC does not |
| Pressure notification on the browser target | 0, KGSL unchanged | CEF's browser listener releases no GPU memory here |
| GC on entering a game | gone 80 s later | V8's idle memory reducer does the same |
| Pausing hidden animations | CPU 2.7–2.8 % before and after | the hidden UI already does not draw |
| Minimizing the window (`Browser.setWindowBounds`) | "Browser window not found" | not a Chrome browser window |
| `SteamClient.Window.HideWindow` | −2 MiB KGSL; window stayed `hidden` after `ShowWindow` | private client API, no gain |
| V8 small-heap flags | renderer +160 MiB (median of 5 against 5) | larger, not smaller; not investigated further |
| V8 small-heap flags | renderer +160 MiB (median of 5 against 5) | larger, not smaller |
| GPU memory budget flags | renderer +200 MiB, KGSL unchanged (2 runs) | larger, not smaller |
| GC after the monitor paged the client out | read ~200 MiB back in | the supervisor skips reclaim when >32 MiB of the client is swapped |
| GC after the monitor paged the client out | read ~200 MiB back in | the walk touches the whole heap |
| KGSL process reclaim (root: `state` = `background`) | 0 bytes reclaimed in 15 s | the Vulkan allocations are not reclaimable this way, and it needs root |
## Failure modes and rollback
- Every intervention is off unless `DD_STEAM_LITE` names a level; `droiddeck-session` does not start
the supervisor otherwise. `{"level": "stock"}` in `agent/steam-lite.json` undoes pause, freeze and
page-out in the running session.
- No DevTools port, target or method: the pass records the error in
`agent/steam-lite-status.json` and the session log and changes nothing.
- The preload not answering (any build without #3293 on a native session): page-out returns 0 kB
and nothing else changes.
- A Steam update that renames `SharedJSContext`, changes the popup URLs or drops a DevTools method
would make passes do less, not break the client: the targets are found by title and URL every
pass, and errors are recorded, not retried. That cannot be noticed without reading the status
file, so it should stay an experiment.
- What is safe to promote: software compositing on 8 GB devices (an existing switch), after a
smoothness check. What should stay experimental: all three levels.
## Measuring
`tools/steam_lite_bench.py` drives a device through `tools/droiddeckctl`; samples are taken inside
the guest with `droiddeck-steam-lite record`/`sample`.
`tools/steam_lite_bench.py` drives a device through `tools/droiddeckctl`. Samples are taken inside
the guest with `droiddeck-steam-lite record` and `sample`.
- **Memory:** per-process `Pss`, `Pss_Anon`, `Pss_File`, `Pss_Shmem` and `SwapPss` from
`/proc/<pid>/smaps_rollup`, summed over the client tree (`steam`, the web helper browser, renderer
and utility processes). PSS is additive; RSS would count shared pages more than once. A process
whose `smaps_rollup` cannot be read is reported as unreadable, never as zero.
`/proc/<pid>/smaps_rollup`, summed over the client tree: `steam` and the web helper's browser,
renderer and utility processes.
- PSS is additive; RSS would count shared pages more than once.
- A process whose `smaps_rollup` cannot be read is reported as unreadable, never as zero.
- **GPU:** `/sys/class/kgsl/kgsl/proc/<pid>/gpumem_{mapped,unmapped}`, reported separately. KGSL
allocations are system RAM on these SoCs, cannot be swapped, and are not in PSS.
- **System:** `MemAvailable`, `MemFree`, PSI `some`/`full`, `/sys/block/zram0/mm_stat` (system-wide,
never added to PSS), `pswpin`/`pswpout`; lmkd's `killinfo` and `ApplicationExitInfo` for kills.
- **CPU:** `utime + stime` deltas from `/proc/<pid>/stat` as percent of one core. The sampler and
the supervisor are listed as `steam-lite` and excluded from the client tree.
- **System:**
- `MemAvailable`, `MemFree` and PSI `some`/`full`.
- `/sys/block/zram0/mm_stat`, which is system-wide and never added to PSS.
- `pswpin`/`pswpout`.
- lmkd's `killinfo` and `ApplicationExitInfo` for kills.
- **CPU:** `utime + stime` deltas from `/proc/<pid>/stat`, as percent of one core. The measuring
tool is listed as `sampler` and left out of the client tree. The removed supervisor appears as
`steam-lite` in the recorded data.
- **Frames:** `tools/droiddeckctl pacing` (SurfaceFlinger timestats).
An arm is a set of persistent session variables (`ARMS` in the harness): `stock`, `softcomp` and
`cef-software`. Each run starts a fresh session with its arm's variables.
```sh
tools/droiddeckctl env set --persistent DD_STEAM_LITE=1 # any level, so the supervisor runs
tools/droiddeckctl start steam --wait
tools/steam_lite_bench.py info --out results/<device>
tools/steam_lite_bench.py ablate --actions gc,moderate,critical,pause --waits 3,20,40 \
--out results/<device> --label ablate-<game>
tools/steam_lite_bench.py steady --app 584400 --arms stock,softcomp,stock,softcomp,stock,softcomp \
--out results/<device>/steady
tools/steam_lite_bench.py library --order 1,0,1,0 --out results/<device>/ui
tools/steam_lite_bench.py flags --variants default,soft-compositing,cef-software --repeat 3 \
--out results/<device>/flags
tools/steam_lite_bench.py oom --app 1388870 --arms stock,l1,softcomp,softcomp+l1 --repeat 4 \
--out results/<device>
tools/steam_lite_bench.py steady --app 12200 --levels stock,1,2,stock,1,2,stock,1,2 --out results/<device>/steady
tools/steam_lite_bench.py library --order 1,0,1,0 --out results/<device>/ui
tools/steam_lite_bench.py oom --app 1388870 --arms stock,softcomp --repeat 4 --out results/<device>
tools/steam_lite_bench.py ablate --actions gc,moderate,critical,pause --waits 3,20,40 \
--out results/<device> --label ablate-<game>
tools/steam_lite_charts.py results docs/development/evidence/steam-lite
```
- `ablate` applies one intervention at a time with a sample before it and after each wait.
- `flags` sets the session environment (`DD_WEBHELPER_ARGS`, `DD_STEAM_SOFT_COMPOSITING`,
`DD_STEAM_CEF_GPU`), starts a fresh session per run and samples the idle library after it settles.
- `oom` starts a fresh session per trial, launches the game, loads the save, confirms the load by
a ≥400 MiB `MemAvailable` drop or the session dying, and records whether it survives 90 s.
- `steady` starts a fresh session per level, samples the library, launches the game, samples it 60
and 80 s after it took focus, times three overlay round trips and samples the library after quitting.
What each command does:
- `steady`, per arm:
1. starts a fresh session and samples the library;
2. launches the game and samples it 60 and 80 s after it took focus, with a 20 s frame capture
between the two samples;
3. times three overlay round trips;
4. samples the library after quitting.
- `library` starts a fresh session with GPU or software compositing and samples the library 90 and
110 s later.
- `cycle` switches the profile at runtime within one session instead; it was not used for the
numbers above because a device set to leave Steam when a game exits ends the session after
every run.
- `flags` sets `DD_WEBHELPER_ARGS`, `DD_STEAM_SOFT_COMPOSITING` and `DD_STEAM_CEF_GPU`, starts a
fresh session per run, and samples the idle library after it settles.
- `oom`, per trial:
1. starts a fresh session and launches the game;
2. loads the save;
3. confirms the load by a ≥400 MiB `MemAvailable` drop or by the session dying;
4. records whether the session survives 90 s.
- `ablate` applies one action at a time in the running session, with a sample before it and one
after each wait.
- `cycle` runs a game launch, an overlay round trip and the return to the library in one recorded
session per arm.
Game inputs: virtual gamepad presses create a new controller each time (Steam shows "Controller
Disconnected" after each) and the game can miss the first press while it enumerates it; Arcade
Paradise's title and menu take keyboard Enter reliably. The trial matrix used an A hold and a tap on
Continue, retried until the load showed in `MemAvailable`; the hand-driven control runs used Enter.
Game inputs need care:
- Each virtual gamepad press creates a new controller; Steam shows "Controller Disconnected" after
each one.
- The game can miss the first press while it enumerates the new controller.
- Arcade Paradise's title and menu take keyboard Enter reliably.
- The trial matrix therefore used an A hold and a tap on Continue, retried until the load showed in
`MemAvailable`. The hand-driven control runs used Enter.
Not measured:
- A 3–4 GB device or a Mali/vkbridge device; none was available.
- The x86_64 client.
- Frame pacing with a heavy game; only Sonic Mania was measured.
- Scroll smoothness.
- Suspend and resume, downloads, store pages, and friends and chat.
@@ -1132,16 +1132,6 @@ case $mode in
&& [ "${DD_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then
/usr/local/bin/droiddeck-launcher-cores "$DD_LAUNCH_DIR/agent/focus.json" 2>&1 &
fi
case ${DD_STEAM_LITE:-0} in
0|stock|off) ;;
*)
if [ -n "${DD_LAUNCH_DIR:-}" ] && [ -z "${DD_DESKTOP:-}" ] && [ "${DD_STEAM_UI:-}" != desktop ] &&
command -v droiddeck-steam-lite >/dev/null 2>&1; then
step "Steam Lite Runtime experiment: ${DD_STEAM_LITE}${DD_STEAM_LITE_SWITCHES:+ ($DD_STEAM_LITE_SWITCHES)}"
droiddeck-steam-lite run 2>&1 &
fi
;;
esac
if [ "${DD_PACE_CORES:-1}" != 0 ] && [ -n "${DROIDDECK_HUD_FRAMES:-}" ] && [ -z "${DD_DESKTOP:-}" ] \
&& [ -x /usr/local/bin/droiddeck-pace-cores ]; then
/usr/local/bin/droiddeck-pace-cores "$DROIDDECK_HUD_FRAMES" 2>&1 &
@@ -1,7 +1,6 @@
#!/usr/bin/python3
"""Opt-in Steam web helper resource experiments (docs/development/steam-lite-runtime.md).
"""Measuring tool for the Steam web helper (docs/development/steam-lite-runtime.md).
droiddeck-steam-lite run supervisor, started by droiddeck-session when DD_STEAM_LITE is set
droiddeck-steam-lite probe CEF version, targets and which DevTools methods answer
droiddeck-steam-lite sample [--cdp] one JSON sample of the client's memory and CPU
droiddeck-steam-lite record SECONDS INTERVAL OUT.jsonl [--cdp] [--mark FILE]
@@ -22,33 +21,11 @@ import time
import urllib.request
from pathlib import Path
STEAM_CLIENT = 769
LEVELS = {"0": 0, "stock": 0, "off": 0, "1": 1, "conservative": 1, "2": 2, "balanced": 2, "3": 3, "aggressive": 3}
LEVEL_NAMES = ("stock", "conservative", "balanced", "aggressive")
# Each intervention and the lowest level that turns it on (None: only a switch turns it on);
# DD_STEAM_LITE_SWITCHES (+name/-name) overrides.
INTERVENTIONS = {
"gc": 1,
"moderate": 1,
"pageout": 2,
"pause": None,
"critical": 3,
"freeze": 3,
}
SETTLE = 4.0
POLL = 1.0
IDLE_POLL = 2.0
PRESSURE_HOLD = 10.0
COOLDOWN = 120.0
PASSES_PER_GAME = 4
CALL_TIMEOUT = 5.0
PASS_BUDGET = 12.0
SWAPPED_SKIP_KB = 32 * 1024
PAGEOUT_BUDGET_KB = 1024 * 1024
PAGEOUT_TIMEOUT = 6.0
READBACK_TIMEOUT = 8.0
READBACK_ATTEMPTS = 3
GC_RELEASE_WAIT = 2.0
HOLD = Path("/tmp/.dd-zram.hold")
UI_ORIGIN = "https://steamloopback.host/"
@@ -68,27 +45,6 @@ def load_agent():
raise ImportError("droiddeck-agent is not installed")
def resolve(level=None, switches=None):
"""The interventions a level and a switch list turn on."""
raw = (level if level is not None else os.environ.get("DD_STEAM_LITE", "")).strip().lower()
number = LEVELS.get(raw or "0")
if number is None:
log("unknown DD_STEAM_LITE %r; stock" % raw)
number = 0
on = {name for name, lowest in INTERVENTIONS.items() if lowest is not None and number >= lowest}
spec = switches if switches is not None else os.environ.get("DD_STEAM_LITE_SWITCHES", "")
for token in spec.replace(",", " ").split():
name = token[1:] if token[:1] in "+-" else token
if name not in INTERVENTIONS:
log("unknown switch %r ignored" % token)
continue
if token.startswith("-"):
on.discard(name)
else:
on.add(name)
return number, on
# ---- process accounting -------------------------------------------------------------------------
def read_text(path):
@@ -103,8 +59,8 @@ def process_role(argv):
if not argv:
return None
name = argv[0].rsplit("/", 1)[-1]
if name.startswith("python") and len(argv) > 2 and argv[1].endswith("/droiddeck-steam-lite") and argv[2] == "run":
return "steam-lite"
if name.startswith("python") and len(argv) > 1 and argv[1].endswith("/droiddeck-steam-lite"):
return "sampler"
if name in ("FEX", "FEXInterpreter") and len(argv) > 1:
argv = argv[1:]
name = argv[0].rsplit("/", 1)[-1]
@@ -526,12 +482,7 @@ class Actions:
return bool(self.paused or self.frozen or self.hidden or self.motion)
# ---- supervisor ---------------------------------------------------------------------------------
def focused(snapshot):
app = snapshot.get("focusedApp")
return None if app in (None, 0) else app
# ---- zRAM preload requests -----------------------------------------------------------------------
class ZramHold:
"""Holds droiddeck-session's zRAM monitor off for one pass, optionally carrying a preload request.
@@ -594,7 +545,7 @@ class Pager:
self.clock = clock
self.nap = nap
self.signal_pid = signal_pid or (lambda pid: os.kill(pid, signal.SIGURG))
self.pids = pids or (lambda: [pid for pid, role in steam_processes(proc) if role not in ("steam-lite", "sampler")])
self.pids = pids or (lambda: [pid for pid, role in steam_processes(proc) if role != "sampler"])
self.out_kb = 0
def ack_path(self, pid):
@@ -666,277 +617,6 @@ class Pager:
return {"before kB": before, "after kB": last}
class Supervisor:
"""Turns focus and memory transitions into bounded, reversible passes.
States: ui (the client is in front, nothing runs), launching (a game started but has not taken
focus), game (a game has had focus for SETTLE seconds: passes may run), back (the client came
to the front over a running game: everything held is restored first).
"""
def __init__(self, agent_dir, actions, interventions, clock=time.monotonic, memory=system_memory,
client_swap=None, status_path=None, hold=None, pager=None, nap=time.sleep):
self.agent_dir = Path(agent_dir)
self.focus_path = self.agent_dir / "focus.json"
self.control_path = self.agent_dir / "steam-lite.json"
self.status_path = status_path or self.agent_dir / "steam-lite-status.json"
self.actions = actions
self.on = set(interventions)
self.level = None
self.clock = clock
self.memory = memory
self.client_swap = client_swap or (lambda: sum(r.get("VmSwap") or 0 for r in sample_processes()
if r["role"] not in ("steam-lite", "sampler")))
self.hold = hold or ZramHold
self.pager = pager or Pager()
self.nap = nap
self.state = "ui"
self.app = None
self.since = clock()
self.focus = {}
self.focus_seen = None
self.control_seen = None
self.low_since = None
self.last_pass = None
self.passes = 0
self.entered = False
self.history = []
self.errors = 0
def read_focus(self):
try:
stamp = self.focus_path.stat().st_mtime_ns
except OSError:
return None
if stamp == self.focus_seen:
return False
try:
snap = json.loads(self.focus_path.read_text())
except (OSError, ValueError):
return None
self.focus_seen = stamp
self.focus = snap
return True
def read_control(self):
try:
stamp = self.control_path.stat().st_mtime_ns
except OSError:
stamp = None
if stamp == self.control_seen:
return False
self.control_seen = stamp
if stamp is None:
return False
try:
body = json.loads(self.control_path.read_text())
level, on = resolve(str(body.get("level", "")), str(body.get("switches", "")))
except (OSError, ValueError, AttributeError):
log("unreadable %s ignored" % self.control_path.name)
return False
self.level = level
if on != self.on:
self.on = on
log("interventions now %s" % (",".join(sorted(on)) or "none (stock)"))
return True
return False
def game_app(self):
app = focused(self.focus)
games = [a for a in self.focus.get("focusableApps") or [] if a not in (0, STEAM_CLIENT)]
return app, games
def transition(self, state, app=None):
if state == self.state and app == self.app:
return
log("%s -> %s%s" % (self.state, state, " (app %s)" % app if app else ""))
self.state, self.app, self.since = state, app, self.clock()
if state != "game":
self.entered = False
self.low_since = None
if state in ("ui", "back"):
self.passes = 0
def tick(self, targets):
self.read_control()
self.read_focus()
app, games = self.game_app()
if not games:
self.transition("ui")
elif app in (None, STEAM_CLIENT):
self.transition("back" if self.state in ("game", "back") else "launching")
elif app in games:
if self.state != "game" or self.app != app:
self.transition("game", app)
else:
self.transition("launching")
if self.state != "game" or not self.on:
if self.pager.out_kb:
self.record("readback", self.pager.readback())
if self.actions.holding():
self.record("restore", self.actions.restore(targets()))
return
if self.clock() - self.since < SETTLE:
return
memory = self.memory()
available, total = memory.get("MemAvailable"), memory.get("MemTotal")
if available is not None and total:
floor = min(max(total // 8, 640 * 1024), 1280 * 1024)
if available < floor:
self.low_since = self.low_since if self.low_since is not None else self.clock()
else:
self.low_since = None
if not self.entered:
self.entered = True
if self.last_pass is None or self.clock() - self.last_pass >= COOLDOWN:
self.run_pass("enter", targets, visual=True)
elif self.on & {"pause", "freeze"}:
self.run_pass("return", targets, visual=True, reclaim=False)
return
pressed = self.low_since is not None and self.clock() - self.low_since >= PRESSURE_HOLD
cooled = self.last_pass is None or self.clock() - self.last_pass >= COOLDOWN
if pressed and cooled and self.passes < PASSES_PER_GAME:
self.run_pass("pressure", targets, visual=False)
self.low_since = None
def still_hidden(self):
if self.read_focus() is None:
return False
app, games = self.game_app()
return app is not None and app in games and app != STEAM_CLIENT
def run_pass(self, why, targets, visual, reclaim=True):
start = self.clock()
self.last_pass = start
self.passes += 1
try:
found = targets()
except Exception as error:
self.record(why, {"error": "targets: %s" % error})
return
if not found:
self.record(why, {"skipped": "no DevTools targets"})
return
steps = []
swapped = self.client_swap() if reclaim else 0
if reclaim and swapped >= SWAPPED_SKIP_KB:
reclaim = False
self.record(why, {"skipped-reclaim": "%d MB of the client is already in zRAM" % (swapped // 1024)})
if reclaim and "gc" in self.on:
steps.append(("gc", lambda: self.actions.gc(found)))
if reclaim and "moderate" in self.on and "critical" not in self.on:
steps.append(("moderate", lambda: self.actions.pressure(found, "moderate")))
if reclaim and "critical" in self.on:
steps.append(("critical", lambda: self.actions.pressure(found, "critical")))
if visual and "pause" in self.on:
steps.append(("pause", lambda: self.actions.pause(found)))
if visual and "freeze" in self.on:
steps.append(("freeze", lambda: self.actions.freeze(found)))
outcome = {}
deadline = start + PASS_BUDGET
self.actions.deadline = deadline
try:
with self.hold():
for name, step in steps:
if not self.still_hidden():
outcome["cancelled"] = "the client came to the front before %s" % name
break
if self.clock() > deadline:
outcome["cancelled"] = "pass budget spent before %s" % name
break
outcome[name] = step()
finally:
self.actions.deadline = None
if reclaim and "pageout" in self.on and "cancelled" not in outcome:
if "gc" in outcome:
self.nap(GC_RELEASE_WAIT)
left = deadline - self.clock()
if left <= 0:
outcome["cancelled"] = "pass budget spent before pageout"
elif self.still_hidden():
outcome["pageout"] = self.pager.pageout(PAGEOUT_BUDGET_KB, timeout=min(PAGEOUT_TIMEOUT, left))
else:
outcome["cancelled"] = "the client came to the front before pageout"
if not self.still_hidden():
if self.pager.out_kb:
outcome["readback"] = self.pager.readback()
if self.actions.holding():
outcome["restore"] = self.actions.restore(found)
outcome["ms"] = round((self.clock() - start) * 1000)
self.record(why, outcome)
def record(self, why, outcome):
entry = {"t": round(time.time(), 3), "state": self.state, "app": self.app, "why": why, "outcome": outcome}
self.history = (self.history + [entry])[-20:]
log("%s: %s" % (why, json.dumps(outcome, separators=(",", ":"))))
self.publish()
def publish(self):
body = {"state": self.state, "app": self.app, "level": self.level, "interventions": sorted(self.on),
"passes": self.passes,
"history": self.history, "unsupported": sorted(self.actions.client.unsupported)}
try:
tmp = self.status_path.with_name(self.status_path.name + ".tmp")
tmp.write_text(json.dumps(body, separators=(",", ":")))
os.replace(tmp, self.status_path)
except OSError:
pass
def run(agent_dir):
agent = load_agent()
level, on = resolve()
if level == 0 and not on:
log("DD_STEAM_LITE is stock; not supervising")
return 0
client = Client(agent, agent_dir)
actions = Actions(client)
supervisor = Supervisor(agent_dir, actions, on)
log("level %s (%s), interventions %s" % (level, LEVEL_NAMES[level], ",".join(sorted(on)) or "none"))
cached = {"at": None, "targets": []}
def targets():
now = time.monotonic()
if cached["at"] is None or now - cached["at"] > 2:
cached["targets"] = client.targets()
cached["at"] = now
return cached["targets"]
def stop(*_):
try:
if supervisor.pager.out_kb:
log("read back on exit: %s" % json.dumps(supervisor.pager.readback()))
except Exception as error:
log("read back on exit failed: %s" % error)
try:
if actions.holding():
cached["at"] = None
log("restore on exit: %s" % json.dumps(actions.restore(targets())))
except Exception as error:
log("restore on exit failed: %s" % error)
client.close()
sys.exit(0)
for sig in (signal.SIGTERM, signal.SIGHUP, signal.SIGINT):
signal.signal(sig, stop)
supervisor.publish()
parent = os.getppid()
while True:
if os.getppid() != parent:
stop()
try:
supervisor.tick(targets)
supervisor.errors = 0
except Exception as error:
supervisor.errors += 1
client.close()
cached["at"] = None
if supervisor.errors in (1, 10) or supervisor.errors % 100 == 0:
log("tick failed (%d): %s" % (supervisor.errors, error))
time.sleep(POLL if supervisor.state in ("game", "back") else IDLE_POLL)
# ---- command line -------------------------------------------------------------------------------
def agent_dir():
@@ -951,8 +631,6 @@ def main(argv):
print(__doc__.strip())
return 0 if argv else 2
command, rest = argv[0], argv[1:]
if command == "run":
return run(agent_dir())
if command == "probe":
client = Client(load_agent(), agent_dir())
try:
+50 -96
View File
@@ -1,15 +1,17 @@
#!/usr/bin/env python3
"""Benchmark the Steam Lite Runtime profiles on a device (docs/development/steam-lite-runtime.md).
"""Measure the Steam web helper on a device (docs/development/steam-lite-runtime.md).
tools/steam_lite_bench.py info --out runs/thor
tools/steam_lite_bench.py cycle --app 1234 --profiles stock,1,2,3 --repeat 3 --out runs/thor
tools/steam_lite_bench.py report runs/thor
tools/steam_lite_bench.py info --out runs/duo
tools/steam_lite_bench.py steady --app 584400 --arms stock,softcomp,stock,softcomp --out runs/duo/steady
tools/steam_lite_bench.py cycle --app 584400 --arms stock,softcomp --repeat 3 --out runs/duo
tools/steam_lite_bench.py ablate --actions gc,moderate,pageout --label gc --out runs/duo
tools/steam_lite_bench.py report runs/duo
Needs a DroidDeck build with debugging tools on, a Steam session started with DD_STEAM_LITE set
(any level: the profile under test is switched at runtime through agent/steam-lite.json), and
tools/droiddeckctl. Each cycle samples the client's process tree inside the guest (smaps_rollup
PSS and SwapPss, CPU ticks, MemAvailable, PSI) through idle, a game launch, the game in front,
an overlay round trip and the return to the library.
Needs a DroidDeck build with debugging tools on and tools/droiddeckctl. An arm is a set of
persistent session variables (ARMS); every run starts a fresh session with them. Samples come from
droiddeck-steam-lite inside the guest: the client's process tree (smaps_rollup PSS and SwapPss, CPU
ticks), KGSL GPU memory, MemAvailable and PSI. `ablate` applies single DevTools or zRAM actions to
a running session and samples around each one.
"""
from __future__ import annotations
@@ -29,20 +31,14 @@ from pathlib import Path
TOOLS = Path(__file__).resolve().parent
CTL = TOOLS / "droiddeckctl"
PROFILES = {
"stock": {"level": "stock"},
"1": {"level": "1"},
"2": {"level": "2"},
"3": {"level": "3"},
"gc": {"level": "stock", "switches": "+gc"},
"moderate": {"level": "stock", "switches": "+moderate"},
"critical": {"level": "stock", "switches": "+critical"},
"pause": {"level": "stock", "switches": "+pause"},
"freeze": {"level": "stock", "switches": "+freeze"},
"gc+critical": {"level": "stock", "switches": "+gc +critical"},
ARMS = {
"stock": {"DD_STEAM_SOFT_COMPOSITING": "0", "DD_STEAM_CEF_GPU": "1"},
"softcomp": {"DD_STEAM_SOFT_COMPOSITING": "1", "DD_STEAM_CEF_GPU": "1"},
"cef-software": {"DD_STEAM_SOFT_COMPOSITING": "0", "DD_STEAM_CEF_GPU": "0"},
}
WEB = ("browser", "renderer", "gpu-process", "zygote")
# The supervisor ("steam-lite") and the sampler measuring ("sampler") are not part of the client.
# Not part of the client: the measuring tool ("sampler"), and the supervisor ("steam-lite") in the
# recordings made while it existed.
NOT_CLIENT = ("steam-lite", "sampler")
REMOTE = "/root/.cache/steam-lite-bench"
LITE = os.environ.get("DD_STEAM_LITE_BIN", "droiddeck-steam-lite")
@@ -75,21 +71,9 @@ class Device:
cmd = ["adb"] + (["-s", self.serial] if self.serial else []) + list(args)
return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout
def profile(self, name: str) -> None:
body = json.dumps(PROFILES[name])
reply = self.guest("sh", "-c", 'printf %s "$1" > "$DD_LAUNCH_DIR/agent/steam-lite.json"', "sh", body)
if reply.get("exitCode") != 0:
raise RuntimeError("could not switch the profile to %s: %s" % (name, json.dumps(reply)[:300]))
def mark(self, text: str) -> None:
self.sh('printf %s "$1" > ' + REMOTE + "/mark", text)
def status(self) -> dict:
try:
return json.loads(self.sh('cat "$DD_LAUNCH_DIR/agent/steam-lite-status.json"') or "{}")
except ValueError:
return {}
def fetch(self, path: str) -> str:
text = self.sh("gzip -c \"$1\" | base64 -w0", path, timeout=120)
return gzip.decompress(base64.b64decode(text)).decode() if text else ""
@@ -104,7 +88,7 @@ def info(dev: Device, out: Path) -> dict:
probe = dev.sh(LITE + " probe", timeout=60)
zram = dev.sh("cat /proc/swaps; ls /sys/block | grep zram; cat /sys/block/zram0/mm_stat 2>&1 | head -1;"
" cat /proc/pressure/memory 2>&1 | head -2; ls /sys/class/kgsl/kgsl/proc 2>&1 | head -3")
env = dev.sh("env | grep -E '^(DD_STEAM_LITE|DD_ZRAM|DD_WEBHELPER_ARGS|DD_STEAM_CLIENT_ARCH|DD_VKBRIDGE|"
env = dev.sh("env | grep -E '^(DD_STEAM_CEF_GPU|DD_ZRAM|DD_WEBHELPER_ARGS|DD_STEAM_CLIENT_ARCH|DD_VKBRIDGE|"
"DD_STEAM_SOFT_COMPOSITING|DD_OPEN_DRIVER)=' | sort")
body = {"props": props, "meminfo": mem, "package": package, "env": env, "counters": zram}
try:
@@ -231,35 +215,30 @@ def recorder(dev: Device, seconds: float, interval: float, name: str) -> subproc
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# A trial arm: the supervisor profile plus the session environment it needs (set before the session starts).
ARMS = {
"stock": ("stock", {"DD_STEAM_SOFT_COMPOSITING": "0"}),
"l1": ("1", {"DD_STEAM_SOFT_COMPOSITING": "0"}),
"l3": ("3", {"DD_STEAM_SOFT_COMPOSITING": "0"}),
"softcomp": ("stock", {"DD_STEAM_SOFT_COMPOSITING": "1"}),
"softcomp+l1": ("1", {"DD_STEAM_SOFT_COMPOSITING": "1"}),
}
def system_available(dev: Device) -> int | None:
text = dev.sh("grep MemAvailable /proc/meminfo")
parts = text.split()
return int(parts[1]) // 1024 if len(parts) >= 2 and parts[1].isdigit() else None
def oom_trial(dev: Device, app: str, profile: str, run_dir: Path, args, arm: str | None = None) -> dict:
def set_arm(dev: Device, arm: str) -> dict:
for key, value in ARMS[arm].items():
set_env(dev, key, value)
return ARMS[arm]
def oom_trial(dev: Device, app: str, arm: str, run_dir: Path, args) -> dict:
"""Fresh Steam, launch, load the save, and see whether the session survives."""
run_dir.mkdir(parents=True, exist_ok=True)
env = set_arm(dev, arm)
ensure_steam(dev, fresh=True)
dev.profile(profile)
name = "oom-%s.jsonl" % run_dir.name
dev.sh("mkdir -p " + REMOTE + " && rm -f " + REMOTE + "/" + name)
dev.mark("idle")
before_exit = last_exit(dev).get("timestamp")
total = args.idle + 60 + args.title + 10 + args.watch + 20
rec = recorder(dev, total, args.interval, name)
events = {"profile": profile, "app": app, "started": time.time(), "kind": "oom", "env": args.env or [],
"arm": arm or profile}
events = {"profile": arm, "app": app, "started": time.time(), "kind": "oom", "env": env, "arm": arm}
time.sleep(args.idle)
dev.mark("launch")
t0 = time.monotonic()
@@ -272,7 +251,6 @@ def oom_trial(dev: Device, app: str, profile: str, run_dir: Path, args, arm: str
raise RuntimeError("app %s did not launch: %s" % (app, events["launch_error"]))
dev.mark("game")
time.sleep(args.title)
events["status_in_game"] = dev.status()
load_attempts = []
base = system_available(dev)
for attempt in range(args.load_attempts):
@@ -336,7 +314,6 @@ def oom_trial(dev: Device, app: str, profile: str, run_dir: Path, args, arm: str
except (KeyError, ValueError):
pass
if alive:
events["status_after_load"] = dev.status()
dev.ctl("screenshot", str(run_dir / "loaded.png"), timeout=60)
dev.ctl("quit", app, "--timeout", "30", timeout=40)
rec.wait(timeout=total + 120) if alive else rec.kill()
@@ -407,10 +384,10 @@ def flags_run(dev: Device, variant: str, run_dir: Path, args) -> dict:
**{k: round(statistics.median([r[k] for r in rows]), 1) for k in ("total", "renderer", "browser", "gpu")}}
def cycle(dev: Device, app: str, profile: str, run_dir: Path, args) -> dict:
def cycle(dev: Device, app: str, arm: str, run_dir: Path, args) -> dict:
run_dir.mkdir(parents=True, exist_ok=True)
ensure_steam(dev)
dev.profile(profile)
env = set_arm(dev, arm)
ensure_steam(dev, fresh=True)
dev.sh("mkdir -p " + REMOTE + " && rm -f " + REMOTE + "/samples.jsonl")
dev.mark("idle")
total = args.idle + args.launch_timeout + args.game + args.overlay + args.back + 30
@@ -420,7 +397,7 @@ def cycle(dev: Device, app: str, profile: str, run_dir: Path, args) -> dict:
["guest", "--timeout", str(total + 30), "--", LITE, "record", str(total),
str(args.interval), REMOTE + "/samples.jsonl", "--mark", REMOTE + "/mark"] + cdp,
stdout=open(run_dir / "recorder.json", "w"), stderr=subprocess.STDOUT)
events = {"profile": profile, "app": app, "started": time.time()}
events = {"profile": arm, "env": env, "app": app, "started": time.time()}
try:
time.sleep(args.idle)
dev.mark("launch")
@@ -435,7 +412,6 @@ def cycle(dev: Device, app: str, profile: str, run_dir: Path, args) -> dict:
pacing = dev.ctl("pacing", "--seconds", str(args.pacing), timeout=args.pacing + 30)
events["pacing"] = {k: pacing.get(k) for k in ("fpsOnScreen", "presentToPresentMs", "cadenceMs",
"offCadencePercent", "frames", "error")}
events["status_in_game"] = dev.status()
if args.overlay:
dev.mark("overlay")
opens = []
@@ -466,7 +442,6 @@ def cycle(dev: Device, app: str, profile: str, run_dir: Path, args) -> dict:
raise RuntimeError("the guest recorder failed (exit %s, %d samples); see %s"
% (reply.get("exitCode", recorder.returncode), len(samples), run_dir / "recorder.json"))
events["finished"] = time.time()
events["status_after"] = dev.status()
(run_dir / "events.json").write_text(json.dumps(events, indent=1))
return events
@@ -503,8 +478,7 @@ def snapshot(dev: Device, label: str) -> dict | None:
"swappss": sum(r.get("SwapPss") or 0 for r in rows) // 1024,
"gpu": sum((d.get("gpu") or {}).values()) // 1048576,
"avail": d["memory"]["MemAvailable"] // 1024,
"ticks": {str(r["pid"]): r.get("ticks") or 0 for r in rows if r["role"] in WEB},
"lite": [{k: r.get(k) for k in ("pid", "Pss", "ticks")} for r in d["processes"] if r["role"] == "steam-lite"]}
"ticks": {str(r["pid"]): r.get("ticks") or 0 for r in rows if r["role"] in WEB}}
print(time.strftime("%H:%M:%S"), label, *("%s %s" % (k, out[k]) for k in
("pss", "renderer", "swappss", "gpu", "avail")), flush=True)
return out
@@ -541,14 +515,12 @@ def pacing_summary(pace: dict) -> dict:
return out
def steady(dev: Device, level: str, app: str, out: Path) -> dict:
"""One fresh session at one level: library, a game in front for 80 s, three overlay round trips, library."""
def steady(dev: Device, arm: str, app: str, out: Path) -> dict:
"""One fresh session per arm: library, a game in front for 80 s, three overlay round trips, library."""
out.mkdir(parents=True, exist_ok=True)
soft = level == "softcomp"
run = {"level": level, "app": app, "started": fresh_session(dev, {
"DD_STEAM_LITE": "stock" if soft else level, "DD_STEAM_SOFT_COMPOSITING": "1" if soft else "0"})}
run = {"level": arm, "env": ARMS[arm], "app": app, "started": fresh_session(dev, ARMS[arm])}
if not run["started"]:
raise RuntimeError("Steam did not start for level %s" % level)
raise RuntimeError("Steam did not start for arm %s" % arm)
time.sleep(30)
run["idle"] = snapshot(dev, "library idle")
t0 = time.monotonic()
@@ -562,7 +534,6 @@ def steady(dev: Device, level: str, app: str, out: Path) -> dict:
run["pacing"] = pacing_summary(dev.ctl("pacing", "--seconds", "20", timeout=60))
run["game"] = snapshot(dev, "game +80s")
run["web_cpu_pct"] = web_cpu(a, run["game"])
run["status"] = dev.status()
opens, closes = [], []
for i in range(3):
t1 = time.monotonic()
@@ -720,7 +691,7 @@ def main(argv=None) -> int:
p_info.add_argument("--out", type=Path, required=True)
p_cycle = sub.add_parser("cycle")
p_cycle.add_argument("--app", required=True)
p_cycle.add_argument("--profiles", default="stock,1,2,3")
p_cycle.add_argument("--arms", default="stock,softcomp", help="comma-separated names from ARMS")
p_cycle.add_argument("--repeat", type=int, default=3)
p_cycle.add_argument("--out", type=Path, required=True)
p_cycle.add_argument("--idle", type=float, default=40)
@@ -740,8 +711,7 @@ def main(argv=None) -> int:
p_ablate.add_argument("--label", required=True)
p_oom = sub.add_parser("oom")
p_oom.add_argument("--app", required=True)
p_oom.add_argument("--profiles", default="stock,1")
p_oom.add_argument("--arms", help="comma-separated arms from ARMS; replaces --profiles and --env")
p_oom.add_argument("--arms", default="stock,softcomp", help="comma-separated names from ARMS")
p_oom.add_argument("--repeat", type=int, default=3)
p_oom.add_argument("--out", type=Path, required=True)
p_oom.add_argument("--idle", type=float, default=20)
@@ -752,9 +722,6 @@ def main(argv=None) -> int:
p_oom.add_argument("--watch", type=float, default=90)
p_oom.add_argument("--interval", type=float, default=1)
p_oom.add_argument("--seed", type=int, default=1)
p_oom.add_argument("--env", action="append", metavar="KEY=VALUE",
help="persistent session environment for these trials (set before the first one)")
p_oom.add_argument("--arm", help="name for this set of trials in charts (default: the profile)")
p_flags = sub.add_parser("flags")
p_flags.add_argument("--variants", default="default,v8-small,gpu-budget")
p_flags.add_argument("--repeat", type=int, default=2)
@@ -764,8 +731,8 @@ def main(argv=None) -> int:
p_flags.add_argument("--out", type=Path, required=True)
p_steady = sub.add_parser("steady")
p_steady.add_argument("--app", required=True)
p_steady.add_argument("--levels", default="stock,1,2,softcomp,stock,1,2,softcomp,stock,1,2,softcomp",
help="one fresh session per entry, in this order (softcomp: stock with software compositing)")
p_steady.add_argument("--arms", default="stock,softcomp,stock,softcomp,stock,softcomp",
help="one fresh session per entry, in this order (names from ARMS)")
p_steady.add_argument("--out", type=Path, required=True)
p_library = sub.add_parser("library")
p_library.add_argument("--order", default="1,0,1,0", help="DD_STEAM_SOFT_COMPOSITING per fresh session")
@@ -773,6 +740,9 @@ def main(argv=None) -> int:
p_report = sub.add_parser("report")
p_report.add_argument("root", type=Path)
args = parser.parse_args(argv)
unknown = [n for n in (getattr(args, "arms", None) or "").split(",") if n and n not in ARMS]
if unknown:
parser.error("unknown arms: %s (known: %s)" % (", ".join(unknown), ", ".join(ARMS)))
dev = Device(args.serial)
failed = 0
if args.command == "info":
@@ -780,12 +750,12 @@ def main(argv=None) -> int:
return 0
if args.command == "steady":
counts: dict[str, int] = {}
for level in args.levels.split(","):
counts[level] = counts.get(level, 0) + 1
name = "%s-%d" % (level if level in ("stock", "softcomp") else "l" + level, counts[level])
for arm in args.arms.split(","):
counts[arm] = counts.get(arm, 0) + 1
name = "%s-%d" % (arm, counts[arm])
print("== steady", name, flush=True)
try:
steady(dev, level, args.app, args.out / name)
steady(dev, arm, args.app, args.out / name)
except Exception as error:
failed += 1
print("run failed: %r" % error, flush=True)
@@ -817,14 +787,7 @@ def main(argv=None) -> int:
set_variant(dev, "default")
return 1 if failed else 0
if args.command in ("cycle", "oom"):
for item in getattr(args, "env", None) or []:
key, _, value = item.partition("=")
set_env(dev, key, value)
arms = (getattr(args, "arms", None) or "").split(",") if getattr(args, "arms", None) else None
names = arms or args.profiles.split(",")
unknown = [n for n in names if n not in (ARMS if arms else PROFILES)]
if unknown:
parser.error("unknown profiles: %s" % ", ".join(unknown))
names = args.arms.split(",")
order = []
rng = random.Random(args.seed)
for i in range(args.repeat):
@@ -836,17 +799,8 @@ def main(argv=None) -> int:
print("== %s run %d" % (name, i + 1), flush=True)
try:
if args.command == "oom":
profile = name
if arms:
profile, env = ARMS[name]
for key, value in env.items():
set_env(dev, key, value)
args.arm, args.env = name, ["%s=%s" % kv for kv in env.items()]
arm = args.arm or name
if args.arm and not arms and len(names) > 1:
arm = "%s-%s" % (args.arm, name)
run_dir = args.out / ("oom-%s-%s-r%d" % (args.app, arm, i + 1))
events = oom_trial(dev, args.app, profile, run_dir, args, arm)
run_dir = args.out / ("oom-%s-%s-r%d" % (args.app, name, i + 1))
events = oom_trial(dev, args.app, name, run_dir, args)
print(json.dumps({k: events.get(k) for k in ("arm", "profile", "loaded", "survived",
"died_after_s", "exit", "launch_s")}), flush=True)
else:
+5 -295
View File
@@ -1,5 +1,3 @@
import json
import os
from pathlib import Path
import runpy
import tempfile
@@ -8,20 +6,14 @@ import unittest
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
MODULE = runpy.run_path(str(BIN / 'droiddeck-steam-lite'))
resolve = MODULE['resolve']
process_role = MODULE['process_role']
sample_processes = MODULE['sample_processes']
renderer_groups = MODULE['renderer_groups']
Actions = MODULE['Actions']
Client = MODULE['Client']
CdpError = MODULE['CdpError']
Supervisor = MODULE['Supervisor']
Pager = MODULE['Pager']
ZramHold = MODULE['ZramHold']
SETTLE = MODULE['SETTLE']
PRESSURE_HOLD = MODULE['PRESSURE_HOLD']
COOLDOWN = MODULE['COOLDOWN']
PASSES_PER_GAME = MODULE['PASSES_PER_GAME']
UI = 'https://steamloopback.host/routes/library/home'
SHARED = {'id': 's', 'title': 'SharedJSContext', 'type': 'page', 'url': 'https://steamloopback.host/index.html',
@@ -79,25 +71,6 @@ def client(log, agent=None, unsupported=(), broken=()):
return Client(agent or FakeAgent(), '/agent', opener=lambda url: FakeSession(url, log, unsupported, broken))
class ResolveTest(unittest.TestCase):
def test_stock_by_default(self):
self.assertEqual(resolve('', ''), (0, set()))
self.assertEqual(resolve('off', ''), (0, set()))
def test_levels_are_cumulative(self):
self.assertEqual(resolve('1', '')[1], {'gc', 'moderate'})
self.assertEqual(resolve('balanced', '')[1], {'gc', 'moderate', 'pageout'})
self.assertEqual(resolve('3', '')[1], {'gc', 'moderate', 'pageout', 'critical', 'freeze'})
def test_switches_toggle_single_interventions(self):
self.assertEqual(resolve('0', '+gc')[1], {'gc'})
self.assertEqual(resolve('3', '-freeze,-pageout +pause')[1], {'gc', 'moderate', 'critical', 'pause'})
self.assertEqual(resolve('3', '+motion')[1], resolve('3', '')[1])
def test_unknown_values_fall_back_to_stock(self):
self.assertEqual(resolve('turbo', '+warp'), (0, set()))
class RoleTest(unittest.TestCase):
def test_web_helper_processes(self):
helper = '/home/u/.local/share/Steam/ubuntu12_64/steamwebhelper'
@@ -113,9 +86,10 @@ class RoleTest(unittest.TestCase):
self.assertIsNone(process_role(['/usr/lib/heroic/heroic', '--type=renderer']))
self.assertIsNone(process_role([]))
def test_the_supervisor_is_its_own_role(self):
self.assertEqual(process_role(['/usr/bin/python3', '/usr/local/bin/droiddeck-steam-lite', 'run']), 'steam-lite')
self.assertIsNone(process_role(['/usr/bin/python3', '/usr/local/bin/droiddeck-steam-lite', 'probe']))
def test_the_measuring_tool_is_not_counted_as_steam(self):
self.assertEqual(process_role(['/usr/bin/python3', '/usr/local/bin/droiddeck-steam-lite', 'record']), 'sampler')
self.assertEqual(process_role(['/usr/bin/python3', '/usr/local/bin/droiddeck-steam-lite', 'apply', 'gc']),
'sampler')
class SampleTest(unittest.TestCase):
@@ -251,270 +225,6 @@ class ActionsTest(unittest.TestCase):
self.assertEqual([t['id'] for t in self.client.targets()], ['s', 'b', 'q', 'w'])
class FakeHold:
entered = 0
def __enter__(self):
FakeHold.entered += 1
return self
def __exit__(self, *_):
pass
class FakePager:
def __init__(self):
self.out_kb = 0
self.calls = []
def pageout(self, budget, timeout=None):
self.calls.append(('pageout', budget))
self.out_kb = 100 * 1024
return {'kB': self.out_kb}
def readback(self):
self.calls.append(('readback',))
self.out_kb = 0
return {'after kB': 0}
class SupervisorTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.dir = Path(temp.name)
self.now = 100.0
self.available = 4 << 20
self.swapped = 0
self.log = []
self.client = client(self.log)
self.actions = Actions(self.client, clock=lambda: self.now)
self.targets = lambda: TARGETS
self.seq = 0
self.pager = FakePager()
FakeHold.entered = 0
def make(self, level='3', switches=''):
return Supervisor(self.dir, self.actions, resolve(level, switches)[1], clock=lambda: self.now,
memory=lambda: {'MemAvailable': self.available, 'MemTotal': 8 << 20},
client_swap=lambda: self.swapped, hold=FakeHold, pager=self.pager, nap=lambda s: None)
def focus(self, app, apps=()):
self.seq += 1
path = self.dir / 'focus.json'
path.write_text(json.dumps({'focusedApp': app, 'focusableApps': list(apps), 'seq': self.seq}))
os.utime(path, ns=(self.seq * 10 ** 9, self.seq * 10 ** 9))
def methods(self):
return [m for _, m, _ in self.log]
def test_nothing_runs_while_the_client_is_in_front(self):
sup = self.make()
self.focus(769, [769])
for _ in range(5):
sup.tick(self.targets)
self.now += 10
self.assertEqual(sup.state, 'ui')
self.assertEqual(self.log, [])
def test_one_enter_pass_after_the_game_settles(self):
sup = self.make('2', '+pause')
self.focus(769, [769, 1234])
sup.tick(self.targets)
self.assertEqual(sup.state, 'launching')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.assertEqual((sup.state, self.log), ('game', []))
self.now += SETTLE
sup.tick(self.targets)
self.assertEqual(self.methods().count('HeapProfiler.collectGarbage'), 2)
self.assertIn('Animation.setPlaybackRate', self.methods())
self.assertNotIn('Page.setWebLifecycleState', self.methods())
self.assertEqual(FakeHold.entered, 1)
self.log.clear()
for _ in range(10):
self.now += 10
sup.tick(self.targets)
self.assertEqual(self.log, [])
def test_the_overlay_restores_at_once(self):
sup = self.make('3', '+pause')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
self.assertTrue(self.actions.holding())
self.log.clear()
self.focus(769, [769, 1234])
sup.tick(self.targets)
self.assertEqual(sup.state, 'back')
self.assertFalse(self.actions.holding())
self.assertIn(('w', 'Page.setWebLifecycleState', {'state': 'active'}), self.log)
self.assertIn(('b', 'Animation.setPlaybackRate', {'playbackRate': 1}), self.log)
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
self.log.clear()
sup.tick(self.targets)
self.assertIn('Animation.setPlaybackRate', self.methods())
def test_a_pass_stops_when_the_client_comes_to_the_front(self):
sup = self.make('3')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
def gc_then_overlay(targets):
self.focus(769, [769, 1234])
return {}
self.actions.gc = gc_then_overlay
sup.tick(self.targets)
self.assertIn('cancelled', sup.history[-1]['outcome'])
self.assertFalse(self.actions.holding())
self.assertNotIn('Memory.simulatePressureNotification', self.methods())
def test_sustained_pressure_repeats_with_cooldown_and_a_cap(self):
sup = self.make('1')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
self.log.clear()
self.available = 300 << 10
passes = 0
for _ in range(int((COOLDOWN * (PASSES_PER_GAME + 3)) // 5)):
self.now += 5
sup.tick(self.targets)
passes = self.methods().count('HeapProfiler.collectGarbage') // 2
self.assertEqual(passes, PASSES_PER_GAME - 1)
self.assertIn(('s', 'Memory.simulatePressureNotification', {'level': 'moderate'}), self.log)
def test_brief_dips_do_not_trigger(self):
sup = self.make('1')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
self.log.clear()
for _ in range(20):
self.available = 300 << 10
self.now += PRESSURE_HOLD / 2
sup.tick(self.targets)
self.available = 4 << 20
self.now += 1
sup.tick(self.targets)
self.assertEqual(self.log, [])
def test_no_reclaim_once_the_client_is_in_zram(self):
sup = self.make('3', '+pause')
self.swapped = 200 * 1024
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
self.assertNotIn('HeapProfiler.collectGarbage', self.methods())
self.assertNotIn('Memory.simulatePressureNotification', self.methods())
self.assertIn('Animation.setPlaybackRate', self.methods())
def test_runtime_control_file_switches_to_stock_and_restores(self):
sup = self.make('3')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
self.assertTrue(self.actions.holding())
(self.dir / 'steam-lite.json').write_text(json.dumps({'level': 'stock'}))
sup.tick(self.targets)
self.assertEqual(sup.on, set())
self.assertFalse(self.actions.holding())
def test_no_devtools_keeps_stock(self):
log = []
dead = client(log, agent=FakeAgent(fail='DevTools unreachable'))
actions = Actions(dead, clock=lambda: self.now)
sup = Supervisor(self.dir, actions, resolve('3')[1], clock=lambda: self.now,
memory=lambda: {}, client_swap=lambda: 0, hold=FakeHold, pager=self.pager, nap=lambda s: None)
self.focus(1234, [769, 1234])
sup.tick(dead.targets)
self.now += SETTLE
sup.tick(dead.targets)
self.assertIn('error', sup.history[-1]['outcome'])
self.assertEqual(log, [])
self.assertEqual(json.loads((self.dir / 'steam-lite-status.json').read_text())['state'], 'game')
def test_pageout_follows_the_gc_and_reads_back_when_the_client_returns(self):
sup = self.make('2')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
self.assertEqual(self.pager.calls, [('pageout', MODULE['PAGEOUT_BUDGET_KB'])])
self.assertIn('pageout', sup.history[-1]['outcome'])
self.focus(769, [769, 1234])
sup.tick(self.targets)
self.assertEqual(self.pager.calls[-1], ('readback',))
self.assertEqual(self.pager.out_kb, 0)
def test_closing_the_overlay_does_not_repeat_reclaim_within_the_cooldown(self):
sup = self.make('2', '+pause')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
for _ in range(3):
self.focus(769, [769, 1234])
sup.tick(self.targets)
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
self.assertEqual(self.methods().count('HeapProfiler.collectGarbage'), 2)
self.assertEqual([c[0] for c in self.pager.calls], ['pageout', 'readback'])
self.assertEqual(sum(1 for t, m, p in self.log if m == 'Animation.setPlaybackRate' and p == {'playbackRate': 0}),
4 * 2)
self.now += COOLDOWN
self.focus(769, [769, 1234])
sup.tick(self.targets)
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
self.assertEqual(self.methods().count('HeapProfiler.collectGarbage'), 4)
def test_no_pageout_at_level_one(self):
sup = self.make('1')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
self.assertEqual(self.pager.calls, [])
def test_unreadable_focus_cancels_a_pass(self):
sup = self.make('3', '+pause')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
def gc_then_lose_focus(targets):
(self.dir / 'focus.json').unlink()
return {}
self.actions.gc = gc_then_lose_focus
sup.tick(self.targets)
self.assertIn('cancelled', sup.history[-1]['outcome'])
self.assertNotIn('Animation.setPlaybackRate', self.methods())
def test_game_exit_returns_to_ui(self):
sup = self.make('2')
self.focus(1234, [769, 1234])
sup.tick(self.targets)
self.now += SETTLE
sup.tick(self.targets)
self.focus(769, [769])
sup.tick(self.targets)
self.assertEqual(sup.state, 'ui')
self.assertFalse(self.actions.holding())
class PagerTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
@@ -599,7 +309,7 @@ class ZramHoldTest(unittest.TestCase):
def test_a_suspend_request_written_over_our_hold_is_left_to_the_app(self):
with tempfile.TemporaryDirectory() as temp:
path = Path(temp) / '.dd-zram.hold'
with ZramHold(path) as hold:
with ZramHold(path):
self.assertEqual(path.read_bytes(), b'')
path.write_text('1')
self.assertEqual(path.read_text(), '1')
+19 -2
View File
@@ -18,9 +18,9 @@ def row(pid, role, pss, ticks, swap=0):
class AccountingTest(unittest.TestCase):
def test_tree_sums_pss_and_leaves_out_the_supervisor(self):
def test_tree_sums_pss_and_leaves_out_the_measuring_tools(self):
s = sample(0, 'idle', [row(1, 'client', 100, 0), row(2, 'renderer', 300, 0, swap=20),
row(3, 'steam-lite', 9000, 0)])
row(3, 'steam-lite', 9000, 0), row(4, 'sampler', 7000, 0)])
self.assertEqual(bench.tree(s)['pss'], 400)
self.assertEqual(bench.tree(s)['swap'], 20)
self.assertEqual(bench.tree(s, bench.WEB)['pss'], 300)
@@ -64,6 +64,23 @@ class HarnessTest(unittest.TestCase):
bench.time.sleep = lambda s: None
self.addCleanup(setattr, bench.time, 'sleep', self.sleep)
def test_unknown_arms_are_refused_before_touching_the_device(self):
with self.assertRaises(SystemExit):
bench.main(['steady', '--app', '1', '--arms', 'stock,turbo', '--out', 'unused'])
def test_an_arm_sets_every_variable_it_names(self):
class Recording(FakeDevice):
def __init__(self):
super().__init__([{'ok': True}] * 2)
self.calls = []
def ctl(self, *args, timeout=0):
self.calls.append(args)
return super().ctl(*args, timeout=timeout)
dev = Recording()
bench.set_arm(dev, 'softcomp')
self.assertEqual([c[-1] for c in dev.calls], ['DD_STEAM_SOFT_COMPOSITING=1', 'DD_STEAM_CEF_GPU=1'])
def test_an_unanswered_state_query_is_not_a_stopped_session(self):
self.assertIsNone(bench.running(FakeDevice([{'ok': False}] * 3)))
self.assertIs(bench.running(FakeDevice([{'ok': False}, {'ok': True, 'session': {'running': False}}])), False)