From 40ce69f28eaf0ec6050834c6f2d0498e36961ea0 Mon Sep 17 00:00:00 2001 From: axoineo Date: Tue, 17 Nov 2026 00:27:43 +0530 Subject: [PATCH 1/7] Add the benchmark design, Android 12 phones and the D-017 design - docs/benchmark.md: the phone fidelity benchmark (D-016, accepted), with BM-01 results for A-17 (Android Emulator) and A-21 (reference phone, Android 12) and the two-set plan (Android 12 and 14). - Android 12 phones: redroid 12.0.0-latest pinned by digest; Android 14 stays the default. Tested on the reference laptop (A-22). - docs/design/android-12-power.md: how restart and power-off inside Android 12 will work (D-017, accepted). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + crates/verone-engine-container/src/engine.rs | 5 +- crates/verone-engine-container/src/images.rs | 45 +++- docs/README.md | 2 + docs/assumptions.md | 103 ++++++++ docs/benchmark.md | 261 +++++++++++++++++++ docs/decisions.md | 16 ++ docs/design/android-12-power.md | 122 +++++++++ docs/roadmap.md | 4 + docs/user-guide/cli.md | 7 +- 10 files changed, 557 insertions(+), 13 deletions(-) create mode 100644 docs/benchmark.md create mode 100644 docs/design/android-12-power.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a3e11b..255c514 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,11 @@ All notable changes to Verone are recorded here. The format follows - The Verone logo, in `docs/brand`. - `verone --version` shows the logo beside the version when run in a terminal, in colour unless `NO_COLOR` is set. Piped or redirected output is unchanged. +- Android 12 phones: `verone create NAME --android 12`, using + `redroid/redroid:12.0.0-latest` pinned by digest. Android 14 stays the default. + Known limit: on Android 12, "Restart" and "Power off" inside Android do nothing, and + `verone stop` forces the phone off after 20 seconds. +- The phone fidelity benchmark design, in `docs/benchmark.md` (decision D-016). ## [0.1.0] - 2026-11-15 diff --git a/crates/verone-engine-container/src/engine.rs b/crates/verone-engine-container/src/engine.rs index cb50b87..4d8220a 100644 --- a/crates/verone-engine-container/src/engine.rs +++ b/crates/verone-engine-container/src/engine.rs @@ -1196,9 +1196,10 @@ exec*) [ -f "$(dirname "$0")/software" ] && echo 1 ;; ); let statuses = absent.engine(&[]).image_statuses().unwrap(); - assert_eq!(statuses.len(), 1); + assert_eq!(statuses.len(), 2); assert_eq!(statuses[0].android, "14"); - assert!(!statuses[0].present); + assert_eq!(statuses[1].android, "12"); + assert!(statuses.iter().all(|status| !status.present)); } #[test] diff --git a/crates/verone-engine-container/src/images.rs b/crates/verone-engine-container/src/images.rs index f46e528..056a72a 100644 --- a/crates/verone-engine-container/src/images.rs +++ b/crates/verone-engine-container/src/images.rs @@ -30,13 +30,25 @@ impl Image { } } -/// Every image this version of Verone supports. x86-64 only in Phase 1. -pub const IMAGES: &[Image] = &[Image { - android: "14", - repository: "redroid/redroid", - tag: "14.0.0-latest", - digest: "sha256:a3e654caad74faed03cd5ead057a989e06f507778cda678e5d3b9772e0092f1c", -}]; +/// Every image this version of Verone supports. x86-64 only. +/// +/// The first entry is the default Android version: `verone doctor` checks the space +/// needed to download it. Android 12 was added for the benchmark's like-for-like set +/// (`docs/benchmark.md`, assumption A-22). +pub const IMAGES: &[Image] = &[ + Image { + android: "14", + repository: "redroid/redroid", + tag: "14.0.0-latest", + digest: "sha256:a3e654caad74faed03cd5ead057a989e06f507778cda678e5d3b9772e0092f1c", + }, + Image { + android: "12", + repository: "redroid/redroid", + tag: "12.0.0-latest", + digest: "sha256:52332b2d74f337982d5ac281a8020ec297fb1ea05cbdcdaaa9c19a2065ae1adc", + }, +]; /// A small image used to run file operations on root-owned phone data. pub const HELPER_IMAGE: &str = @@ -75,13 +87,28 @@ mod tests { assert_eq!(image.display_name(), "redroid/redroid:14.0.0-latest"); } + #[test] + fn android_12_resolves_to_the_tested_digest() { + let image = image_for("12").unwrap(); + assert_eq!( + image.reference(), + "redroid/redroid@sha256:52332b2d74f337982d5ac281a8020ec297fb1ea05cbdcdaaa9c19a2065ae1adc" + ); + assert_eq!(image.display_name(), "redroid/redroid:12.0.0-latest"); + } + + #[test] + fn the_default_android_version_comes_first() { + assert_eq!(IMAGES[0].android, verone_core::profile::DEFAULT_ANDROID); + } + #[test] fn an_unsupported_version_is_not_found_and_lists_what_exists() { let error = image_for("9").unwrap_err(); assert_eq!(error.kind(), ErrorKind::NotFound); assert_eq!(error.exit_code(), 4); assert!(error.message().contains("Android 9")); - assert!(error.hint().unwrap().contains("14")); + assert!(error.hint().unwrap().contains("14, 12")); } #[test] @@ -91,6 +118,6 @@ mod tests { assert_eq!(image.digest.len(), "sha256:".len() + 64, "{image:?}"); } assert!(HELPER_IMAGE.contains("@sha256:")); - assert_eq!(supported_versions(), ["14"]); + assert_eq!(supported_versions(), ["14", "12"]); } } diff --git a/docs/README.md b/docs/README.md index 4bd64a6..ee42644 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,6 +15,8 @@ work from it. | [phases/phase-0.md](phases/phase-0.md) | Step-by-step proof tests for Phase 0. | Ready for owner review | | [phases/phase-1.md](phases/phase-1.md) | Executable task plan for Phase 1: 18 tasks with acceptance tests. | Built 2026-11-15 | | [user-guide/cli.md](user-guide/cli.md) | Every command, option, exit code and known limit of version 0.1. | Current | +| [benchmark.md](benchmark.md) | How close Verone and other virtual Android systems are to a real phone, and how that is measured. | Accepted (D-016); not built yet | +| [design/android-12-power.md](design/android-12-power.md) | How restart and power-off inside Android 12 are made to work. | Accepted (D-017) | | [future-ideas.md](future-ideas.md) | Ideas not yet scheduled. Not to be built until approved. | Live backlog | ## Still to be written diff --git a/docs/assumptions.md b/docs/assumptions.md index a853676..bbe2cf0 100644 --- a/docs/assumptions.md +++ b/docs/assumptions.md @@ -28,6 +28,13 @@ the design is changed. | A-14 | adb can be reached without publishing any port, fast enough for screen streaming. | Phase 1 | no | **pass** 2026-11-15 | | A-15 | With Google apps added, a fresh phone starts with the standard first-boot setup wizard. | Phase 3 | no | **fail** 2026-11-15 | | A-16 | The computer's webcam can be presented to Android as its camera on the container engine with a prebuilt image. | Phase 3 | no | untested | +| A-17 | The Android Emulator runs an Android 14 x86-64 image without Google apps on the owner's laptop, and its `adb` works for the benchmark checks. | Benchmark | no | **pass** 2026-11-16 | +| A-18 | Cuttlefish runs Android 14 on the owner's laptop (8 GB RAM) on Arch Linux. Google documents Debian-based hosts and heavy memory use, so a fail here is likely; the alternative is a borrowed or rented larger machine. | Benchmark | no | untested | +| A-19 | Waydroid runs on the owner's laptop, and its image's Android version is recorded. It may not offer Android 14. | Benchmark | no | untested | +| A-20 | The chosen CTS modules can be run over `adb` on every contender, including the container ones. | Benchmark | no | untested | +| A-21 | The owner has a real Android phone (ideally Android 14) that can be used with USB debugging as the reference. | Benchmark | yes | **partial** 2026-11-16 (phone is Android 12) | +| A-22 | redroid's Android 12 image (`redroid/redroid:12.0.0-latest`, 769 MiB compressed for amd64 on Docker Hub, last updated 2024-05-28) boots on the owner's laptop and reaches the home screen. Needed for benchmark set A, and before Verone can offer Android 12. | Benchmark | yes | **pass** 2026-11-16 (restart and power-off from inside do not work) | +| A-23 | The Android Emulator runs the Android 12 image without Google apps (`x86_64-31_r05.zip`, 626 MiB from `dl.google.com`) on the owner's laptop. | Benchmark | no | untested | ## Evidence @@ -214,6 +221,102 @@ desktop app provides its own first-run steps (language, optional Google sign-in, screen lock) and starts Android already provisioned; (3) solve it in Verone's own image in Phase 5. +**A-17 pass.** 2026-11-16, owner's laptop: Arch Linux, kernel 7.3.4-arch1-2, Intel Core +i5-6500T, 7.6 GB RAM, `/dev/kvm` usable. Benchmark task BM-01. + +- Installed without Google's command-line tools or Java: the emulator package + `emulator-linux_x64-16740729.zip` (emulator 37.2.13, stable channel) and the system + image `x86_64-34_r04.zip` (`system-images;android-34;default;x86_64`, no Google apps) + were downloaded from `dl.google.com/android/repository/`, their SHA-1 checked against + Google's catalogue, and unpacked with `bsdtar` into `~/Android/Sdk`. `adb` is linked + from the system package. The phone `bench34` was written by hand to + `~/.android/avd/` (2 cores, 2048 MB, 720×1280 at 320 dpi, GPU `auto`, emulated + cameras), because `avdmanager` needs Java. +- Started with `emulator -avd bench34 -no-window -no-snapshot-save -no-boot-anim + -port 5560`, with the phone 'work' stopped. First boot to `sys.boot_completed=1`: 37 s. +- Over `adb` these benchmark checks ran and gave a result: build properties, setup + state, declared features, a posted notification, battery, cameras (2), sensors + (accelerometer, gyroscope, proximity), network type, internet ping, rotation, app + launch time (`am start -W`: Settings 1019 ms), `monkey`, and a 200 MiB push + (213 MB/s as reported by `adb`). +- Notes for the check runner (BM-03): rotation must be set with + `cmd window user-rotation lock 1` and read from `mCurrentOrientation` in + `dumpsys display`; changing `user_rotation` in settings did nothing. The network type + is in `dumpsys connectivity` as `Transports:`; the emulator shows WIFI and also + CELLULAR. Use a fresh data partition (`-wipe-data`) for every benchmark run, because + the checks change settings. +- Early observations, not yet scored: no setup wizard (`user_setup_complete=1` on first + boot); `userdebug` build with test keys; model "Android SDK built for x86_64" and + `ro.kernel.qemu=1`, so it identifies itself honestly as an emulator; it declares + telephony. On the host the emulator used about 3.3 GB of memory (resident) and the + phone's files took 678 MB. + +**A-18 untested.** 2026-11-16: skipped on the owner's laptop by the owner's choice. It +has 7.6 GB of memory and runs Arch, while Google supports Cuttlefish hosts on +Debian-based systems only. To be tested on a larger or rented Debian machine. + +**A-19 untested.** 2026-11-16: not attempted. Waydroid itself is in Arch's `extra` +repository (version 1.6.3), but its first-time setup downloads an Android image (about +1 GB) to the system partition, which had only 2.7 GB free. The owner did not approve +it for now. Free space on `/` first, or find a way to keep Waydroid's images on `/home`. + +**A-20 untested.** 2026-11-16: not attempted. Google's Android 14 test suite, +`android-cts-14_r14-linux_x86-x86.zip`, is 10.7 GiB (size read from +`dl.google.com`). It also needs Java. Waiting for the owner's approval of the download. +Since set A uses Android 12, the Android 12 suite is needed first; the Android 14 suite +is only for set B. Look up the size of the Android 12 suite before asking. + +**A-22 pass, with a limit.** 2026-11-16, owner's laptop (as for A-17). The image +`redroid/redroid@sha256:52332b2d74f337982d5ac281a8020ec297fb1ea05cbdcdaaa9c19a2065ae1adc` +(tag `12.0.0-latest`) is 2.78 GB once pulled. To make room on `/`, the Phase 0 images +`redroid/redroid:14.0.0_mindthegapps`, `verone-p0-gcfs` and `verone-p0-crypt` were +deleted with the owner's approval (they can be rebuilt from `tests/phase-0/`), and the +owner trimmed the system journal; `/` had 1.4 GB free afterwards. + +- Plain redroid with the Phase 0 baseline command (software rendering, 720×1280): + `sys.boot_completed=1` after 7 s, then the Launcher3 home screen; Android 12 (API 31), + `userdebug`, ARM translation listed (`arm64-v8a`, `armeabi-v7a`); internet ping + works; about 717 MB memory and under 1% CPU when idle; `user_setup_complete=1` once + settled, no setup wizard. +- Through Verone, built from this branch: `verone create bench12 --android 12` and + `verone start bench12` booted in 4.7 to 7.0 s using the GPU. A file written to + shared storage survived stops and starts. +- **Shared storage is ready a few seconds after boot.** Writing to `/sdcard` right + after `sys.boot_completed=1` failed with "Operation not permitted"; a few seconds + later it worked. Scripts must wait for storage, not only for boot. +- **Restart and power-off from inside Android do not end the container.** After + `reboot` or `reboot -p` inside, `sys.powerctl` is set (`reboot,shell`) but the + container keeps running for at least 60 s, with restart count 0. Android 14 exits + with code 129 or 130 instead (A-03 addendum). Effects on Verone with Android 12: + `verone stop` waits its full 20 s and then kills the phone (exit code 137); a restart + chosen inside Android is ignored and the phone keeps running normally (same system + process, home screen and storage still working, checked 2026-11-17). Data survived + three such kills. +- Cause, as far as found: the kernel log shows init receiving the request + ("Got shutdown_command 'reboot,shell' Calling HandlePowerctlMessage()") and then + logging nothing more; it never starts shutting down. The deeper reason inside + Android 12's init was not found. A fix that does not depend on it is designed in + `design/android-12-power.md`. + +**A-21 partial.** 2026-11-16: the owner's phone, a vivo V2027, connected over USB with +USB debugging and was reached by `adb` without problems. It runs **Android 12** (API +31), not 14: a `user` build with release keys, ARM 64-bit, 720×1600 screen. Only +read-only checks were run, because it is the owner's personal phone. All gave results: +build properties, declared features (camera, front camera, telephony, Wi-Fi, +Bluetooth, GPS, accelerometer, gyroscope, proximity), battery, cameras (5), sensors, +network type (mobile data and Wi-Fi), screen orientation, and setup state. `monkey`, +`cmd` and `am` are present. No root (`adb shell` runs as the `shell` user), as expected +on a retail phone. + +Consequence for the benchmark: the reference phone is two Android versions older than +the virtual contenders. Feature and behaviour checks can still be compared, but +Google's compatibility tests (B3-03) are made per Android version and cannot run the +same suite on Android 12 and 14. Options for the owner: (1) also run the virtual +contenders on Android 12 (redroid and the emulator both offer it) for a like-for-like +comparison; (2) keep Android 14 and record the version gap next to every result; +(3) use an Android 14 phone as the reference. Checks that change settings, post +notifications or copy files must ask the owner first when run on this phone. + ## Other Phase 0 findings **T-14, name check (2026-11-15): no conflict found, formal trademark search not done.** diff --git a/docs/benchmark.md b/docs/benchmark.md new file mode 100644 index 0000000..8e7088d --- /dev/null +++ b/docs/benchmark.md @@ -0,0 +1,261 @@ +# Phone fidelity benchmark + +Status: **accepted** (2026-11-16, decision D-016). Not built yet; work starts from the +build plan at the end of this file. + +## Why this exists + +Verone's first product principle is "behave like a phone". Today nothing measures how +far Verone, or any other virtual Android system, is from that goal. + +Published comparisons of virtual Android systems measure speed, mostly for games. No +public test puts the Android Emulator, Cuttlefish, redroid and Waydroid side by side +and scores them against a **real phone**. Google states that Cuttlefish aims to behave +like a physical device, but that is a design goal, not a measurement. (Search done +2026-11-16; if a comparable benchmark turns up later, record it here and compare.) + +This benchmark fills that gap. It answers three questions: + +1. How close is each virtual Android system to a real phone, area by area? +2. Where does Verone add something over the redroid it is built on? +3. After each phase, did Verone move closer to a real phone? + +The method is written so that anyone can run it on any of the systems compared, not +only on Verone. A fair, repeatable and public measuring stick is useful to other +projects too, and gives people outside Verone a reason to trust the results. + +## What to expect from the first run + +Verone 0.1 runs redroid underneath. On app compatibility and speed it will score about +the same as plain redroid. That is expected and must be published as it is. Verone's +difference shows in the checks that depend on Verone's own work: clean shutdown, +automatic return after a restart, and later the setup wizard, the lock, the camera and +backups. Each failed check is a candidate item for the roadmap. + +## What is compared + +| Contender | What it is | Configuration used | +|---|---|---| +| **Real phone** | The reference. Its result counts as 100%. | The owner's vivo V2027, Android 12, USB debugging on. | +| **Verone** | This project. | `verone create` and `verone start` with default options. | +| **redroid** | The container Android Verone is built on. | `redroid/redroid:14.0.0-latest` with the baseline command from `phases/phase-0.md`. | +| **Android Emulator** | Google's emulator from the Android SDK. | Android 14 (API 34) x86-64 image without Google apps, default device settings. | +| **Cuttlefish** | Google's virtual-machine Android device. | Android 14 build from Google's published builds, default launch options. | +| **Waydroid** | Container Android for Linux desktops, LineageOS based. | Its standard image, whatever Android version that is (record it). | + +### Two Android versions + +The reference phone runs **Android 12** (assumption A-21). On 2026-11-16 the owner chose +to run the benchmark in two sets: + +| Set | Android | Contenders | Used for | +|---|---|---|---| +| **A (main)** | 12 | Real phone, Verone, redroid (`redroid/redroid:12.0.0-latest`), Android Emulator (`system-images;android-31;default;x86_64`), Cuttlefish where it runs | The phone fidelity score: like-for-like with the real phone, including the compatibility tests (B3-03) | +| **B** | 14 | Verone, redroid, Android Emulator, Cuttlefish, Waydroid | Where Verone's default version stands; checks that do not depend on the Android version are compared with the real phone's Android 12 result, marked so | + +Notes: + +- **Verone in set A** uses Android 12 support added on 2026-11-16 with the owner's + approval (`crates/verone-engine-container/src/images.rs`, assumption A-22). It is + expected to fail B1-03 and B1-04 on Android 12 until the restart problem in A-22 is + fixed, and the report must say so. +- Waydroid offers LineageOS images (Android 11 and 13 at the time of writing; to be + confirmed in A-19), not Android 12. It is in set B only, with its version recorded. +- The headline numbers in the README come from set A. Set B is published beside it. + +Rules for a fair comparison: + +- Every contender runs on the **same computer** in the same run, one at a time, with + nothing else heavy running. +- Within a set, every contender uses that set's Android version. Where one cannot, + record the version used next to every result. +- Use each contender **as a new user would get it**: default settings, no tuning. Any + setting changed to make a check possible is written in the results. +- **Without Google apps** for every virtual contender, so they match Verone's default + mode. The real phone will have Google apps; this is recorded, not corrected. +- Verone is never tuned for the benchmark in a way the others could not be. +- Results are published in full, including every check Verone fails. + +Not every contender may run on the owner's laptop (8 GB RAM). See assumptions A-17 to +A-21. A contender that cannot run is listed as "not run" with the reason, never left out +silently. + +## How it works + +Every contender, including the real phone, can be controlled with `adb`. That is what +makes a fair comparison possible: one set of checks, sent over `adb`, runs unchanged on +all of them. Only starting, stopping and resetting differ per contender, and each +contender gets a small adapter for those three actions. + +A few checks cannot be judged by a script (for example "is the phone's sound heard on +the computer"). These are marked **manual**. The script stops, tells the person running +it exactly what to do and what to look for, and records their answer. + +## Scoring + +Each check gives one result: + +| Result | Points | Meaning | +|---|---|---| +| pass | 1 | Behaves as on the real phone. | +| partial | 0.5 | Works with a limit that the check's own rule describes. | +| fail | 0 | Does not work, or claims to work and does not. | +| not applicable | none | The check does not apply to this contender (written reason required). | + +**Area score** = points earned ÷ number of checks that pass on the real phone, as a +percentage. Checks the real phone itself fails are reported but left out of the score. + +**Phone fidelity score** = the average of the area scores for areas 1 to 4, with equal +weight. Area 5 (cost and speed) is reported as raw numbers and is not part of the +fidelity score, because a computer's memory use cannot be compared with a phone's. + +Every result carries the reason for a partial or failed check, so a reader can see what +is missing, not only that something is. + +## The checks + +Check IDs (`B1-03` and so on) stay fixed once published, so results from different +dates can be compared. New checks get new IDs. A removed check keeps its ID, marked +retired. + +### Area 1 — Behaves like a phone + +| ID | Check | Pass rule | +|---|---|---| +| B1-01 | First boot shows a setup wizard | A fresh phone starts in a setup flow, not straight on the home screen. | +| B1-02 | Screen lock | A PIN can be set; after the screen turns off and on, the lock screen asks for it. | +| B1-03 | Restart from inside | A restart chosen inside Android brings the phone back to the home screen by itself. | +| B1-04 | Power off from inside | A power-off chosen inside Android shuts it down cleanly; the next start works. | +| B1-05 | Notifications | A posted notification appears in Android's notification list. | +| B1-06 | Rotation | Switching to landscape turns the display and apps follow. | +| B1-07 | Camera | Android reports at least one camera, and the standard "take a picture" action returns an image. Partial if the image is a test pattern rather than a real camera. | +| B1-08 | Microphone (manual) | A recording app records sound spoken near the computer. | +| B1-09 | Sound out (manual) | A sound played on the phone is heard on the computer. | +| B1-10 | Battery | Android reports a battery level and charging state without errors. | +| B1-11 | Location | An app asking for the location receives a position. Partial if only a manually set position is possible. | +| B1-12 | Sensors | Android lists an accelerometer, gyroscope and proximity sensor. Partial if some are listed. | +| B1-13 | Clipboard with the computer | Text copied on the computer can be pasted on the phone and back. Partial if one direction only. | +| B1-14 | Files from the computer | A file can be moved onto the phone without command-line tools. Partial if only with `adb`. | + +For a real phone B1-13 and B1-14 mean "with the computer it is connected to". Real phones +need a helper app for B1-13, so B1-13 counts as pass on the phone if any common tool does it. + +### Area 2 — Keeps your things + +| ID | Check | Pass rule | +|---|---|---| +| B2-01 | Stop and start | A file, an installed app and a changed setting are all still there after a normal stop and start. | +| B2-02 | Computer restart | The same three survive a restart of the computer itself (for a real phone: a phone restart). | +| B2-03 | Unexpected stop | After the contender is killed without warning, it starts again and the three are intact. Partial if it starts but something is lost. | +| B2-04 | Factory reset | Reset removes the file, the app and the setting, and the next boot behaves like a first boot. | +| B2-05 | Backup and restore | A backup made with the contender's own tool restores the three onto a fresh phone. Not applicable if the contender has no backup tool; the real phone uses its built-in backup. | + +### Area 3 — Runs apps + +| ID | Check | Pass rule | +|---|---|---| +| B3-01 | App list | Each app in the fixed app list installs, opens, and survives a short automatic tapping run (Android's `monkey` tool) without crashing. Score is the share of apps that pass. | +| B3-02 | ARM-only apps | Same as B3-01 for the ARM-only part of the list. | +| B3-03 | Compatibility tests | A fixed selection of modules from Google's Compatibility Test Suite (CTS). Score is the share of tests passed, relative to the real phone's share. | +| B3-04 | Installs from an app store | F-Droid installs and can install an app from inside itself. | + +The app list is about 20 open-source apps from F-Droid across browsers, maps, media, +messaging, office and games, plus at least three apps that ship only ARM code. The list +and the CTS module selection are fixed in `tests/bench/apps.txt` and +`tests/bench/cts-modules.txt` and change only with a new benchmark version. + +### Area 4 — Tells the truth + +A virtual phone that claims hardware it does not have breaks apps in confusing ways. +These checks reward honesty, not disguise (decision D-005). + +| ID | Check | Pass rule | +|---|---|---| +| B4-01 | Declared hardware works | Every hardware feature Android declares (camera, telephony, Wi-Fi, Bluetooth, NFC, sensors) actually works. Fail for each feature declared but not working; the score is the share that is consistent. | +| B4-02 | Network type | The network is presented as Wi-Fi or another type apps handle normally, and apps see the internet as available. | +| B4-03 | Identity is honest | Build properties describe the system truthfully: no copied retail fingerprint. Pass for the real phone by definition. | +| B4-04 | Missing features are explained | Settings that cannot work (SIM, mobile data) are hidden or say why. Partial if they are present but fail quietly. | + +**Not scored:** Play Integrity, SafetyNet and hardware key attestation. Their results are +recorded for information only. Improving them is a non-goal (see `vision-and-scope.md`). + +### Area 5 — Cost and speed + +Raw numbers, not scored. Each timing is run three times; the middle value is reported. + +| ID | Measure | +|---|---| +| B5-01 | Steps and time from nothing installed to a booted phone, following the contender's own documentation | +| B5-02 | First boot time (start command to `sys.boot_completed=1`) | +| B5-03 | Later boot time | +| B5-04 | Memory used on the computer, idle at the home screen after 2 minutes | +| B5-05 | Processor use on the computer, idle, averaged over 60 seconds | +| B5-06 | Disk space used: system plus one phone | +| B5-07 | App launch time for three apps from the app list (`am start -W`) | +| B5-08 | Frame rate while scrolling a long list, with and without graphics acceleration | +| B5-09 | Copy speed of a 200 MiB file onto the phone and back | + +For the real phone B5-04 to B5-06 are left empty; the rest are measured. + +## Results + +Each run produces: + +- `docs/benchmark-results/.md`: the readable report. It has a summary table + (contenders across, area scores down), then every check with its result and reason. +- `tests/bench/results/.json`: the same data for scripts and charts. + +Every report starts with what was used: the computer (processor, memory, graphics, +kernel, distribution), each contender's version and Android version, the benchmark +version, and the real phone's model. + +The benchmark is run at the end of every roadmap phase, and the result is linked from +the phase's exit notes. A drop in any area score is a bug to explain. + +### Showing the results in the README + +The README gets a short "How Verone compares" section, filled **only from a real run**. +No chart or claim is drawn before there is measured data behind it. + +| Visual | What it shows | Why | +|---|---|---| +| Phone fidelity bar chart | One bar per contender, real phone at 100% | The headline: how phone-like each one is | +| Area chart | Areas 1 to 4 side by side for each contender | Shows *where* each one is strong or weak | +| Comparison table with ✓, ½ and ✗ | The ten most telling checks, per contender | Readable at a glance, works everywhere | +| Cost chart | Boot time and memory use per contender | The "light" side of Verone, in numbers | +| Progress chart (from Phase 2 on) | Verone's score after each phase | Shows the project moving towards a real phone | + +How they are made: + +- The report generator draws the charts as **SVG files** from the JSON results, in + `docs/benchmark-results/charts/`. GitHub shows SVG images in a README without any + extra service. Each chart has a light and a dark version, shown with `` like + the logo, in the brand colours from `docs/brand/`. +- Every chart has a caption with the date, the computer and the benchmark version, and + links to the full report. +- Contenders that win a check are shown winning. Where the Android Emulator or + Cuttlefish is better, the chart says so. A reader who sees that Verone's results are + fair will believe the places where Verone is ahead. +- The section links to "Run it yourself" instructions, so anyone can check the numbers. + +The benchmark itself has a version (starting at 1.0). Changing a check, the app list or +the CTS selection makes a new version; results are only compared within one version. + +## Build plan + +D-016 was accepted on 2026-11-16. One commit per task, one pull request for the whole +plan. + +| ID | Task | Acceptance test | +|---|---|---| +| BM-01 | Test assumptions A-17 to A-21 on the owner's laptop and record the results. | Each has a result and evidence in `assumptions.md`. | +| BM-02 | Adapters: start, stop, kill and reset for each contender that runs, in both sets, under `tests/bench/contenders/`. The real phone's adapter never resets or changes the phone without asking. | Each adapter boots its contender to `sys.boot_completed=1` and stops it, three times in a row. | +| BM-03 | The check runner: runs every automatic check over `adb`, prompts for manual ones, writes the JSON result. | A full run on Verone completes and the JSON lists every check ID. | +| BM-04 | Fix the app list and the CTS module selection. | Both files exist; every app installs on the real phone; the CTS selection runs on the real phone. | +| BM-05 | Report generator: JSON to the Markdown report with the summary table, plus the SVG charts (light and dark) described in "Showing the results in the README". | For a sample JSON the report matches the format above and every chart opens in a browser in both themes. | +| BM-06 | First full run of sets A and B on all contenders that run; publish the report and charts as the Verone 0.1 starting point. | `docs/benchmark-results/.md` exists and the owner has read it. | +| BM-07 | "How Verone compares" section in the README: fidelity chart, area chart, comparison table, cost chart, links to the full report and to "Run it yourself". | The section shows correctly on GitHub in light and dark mode, and every number matches the published report. | + +How the runner is written (shell scripts like `tests/e2e/`, or part of the Rust +workspace) is decided in BM-03; shell is the default because every check is an `adb` +command. diff --git a/docs/decisions.md b/docs/decisions.md index 194550b..8f18bda 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -24,6 +24,8 @@ stop and raise it with the owner. | D-013 | 2026-11-14 | The project licence is Apache-2.0, replacing the MIT licence the repository started with. The copyright notice is in `NOTICE`. | accepted | | D-014 | 2026-11-14 | Google apps are optional. First-run offers "with Google" or "without Google"; a Google-free phone is a fully supported mode, not a fallback. | accepted | | D-015 | 2026-11-14 | Verone collects no usage data. | accepted | +| D-016 | 2026-11-16 | Progress towards "behave like a phone" is measured with a public, repeatable benchmark (`benchmark.md`) that scores Verone, redroid, the Android Emulator, Cuttlefish and Waydroid against a real phone. It runs at the end of every phase and all results are published, including unfavourable ones. | accepted | +| D-017 | 2026-11-17 | On Android versions whose init ignores restart and power-off requests (Android 12 today), a small helper container, `verone-power`, notices the request and ends the phone with the same exit codes Android 14 produces. Design: `design/android-12-power.md`. | accepted | ## Reasons @@ -52,3 +54,17 @@ must not be copied into Verone. **D-014.** Widens the audience (privacy-minded users, testers who need a clean system) and removes the hard dependency on Google's acceptance of the device. + +**D-016.** Without a measurement, "behave like a phone" cannot be checked, and claims +about Verone cannot be shown to others. A search on 2026-11-16 found speed comparisons +of virtual Android systems but no test that scores them against a real phone, so the +benchmark is also something new that other projects can use. Every contender is driven +through `adb`, which keeps the comparison fair. Publishing unfavourable results is what +makes the favourable ones believable. + +**D-017.** Measured on 2026-11-17 (A-22): Android 12's init receives the request and +does nothing, and the cause was not found. A helper outside the phone can read the +request and make the real `reboot` system call, which the kernel turns into the same +exit codes 129 and 130 that Verone already handles for Android 14. It needs no new +download. The cost is one more privileged container and a shutdown that is abrupt +(after a `sync`) rather than clean; both are stated in the design. diff --git a/docs/design/android-12-power.md b/docs/design/android-12-power.md new file mode 100644 index 0000000..dbf2e17 --- /dev/null +++ b/docs/design/android-12-power.md @@ -0,0 +1,122 @@ +# Restart and power-off on Android 12 + +Status: **accepted** (2026-11-17, decision D-017). Being built: tasks P12-01 to P12-05. + +## The problem + +On Android 14, choosing "Restart" or "Power off" inside Android ends the phone's +container with exit code 129 (restart) or 130 (power off). Verone relies on that. +Docker's restart policy brings a restarted phone back, and `verone stop` waits for +code 130 (A-03 addendum). + +On Android 12 (`redroid/redroid:12.0.0-latest`), init receives the request and then +does nothing (A-22). As a result: + +| What the user does | What happens now on Android 12 | +|---|---| +| "Restart" inside Android | Nothing. The phone keeps running. | +| "Power off" inside Android | Nothing. The phone keeps running. | +| `verone stop` | Waits the full 20 seconds, then kills the phone (exit code 137). | + +This fails benchmark checks B1-03 and B1-04, and makes `verone stop` slow and abrupt. +The deeper cause inside Android 12's init was not found. + +## What was measured + +All on 2026-11-17, owner's laptop, phone `bench12` (Android 12) created with Verone. + +1. After a request inside Android, the property `sys.powerctl` holds the request + (`reboot,shell` or `shutdown,shell`) and keeps it. +2. A process outside the phone can read it. A helper container started with + `--privileged --pid=host` from Verone's existing helper image (alpine, pinned by + digest) ran `nsenter -t -m -u -i -n -p -r -w /system/bin/getprop + sys.powerctl` and saw the value. +3. The same helper can end the phone exactly as Android 14 would. The kernel ends a + container when any process inside its process namespace makes the real `reboot` + system call: code 129 for a restart, 130 for a power-off. + - `nsenter -t -p reboot -f`: Docker's restart policy brought the phone back; + Android was booted again within about 3 s; the request was cleared; files kept. + - `nsenter -t -p poweroff -f` with the restart policy off: the phone stopped + with exit code 130, 2 s after the request. + +## Options considered + +| Option | Verdict | +|---|---| +| **A. Power watcher: one small helper container per computer** that notices requests and makes the real call. | **Recommended.** Uses only what Verone already ships and pulls; tested by hand above; works for any Android version with the same fault. | +| B. A watcher started inside each phone at `verone start` (`docker exec`) | Rejected. It disappears when Docker restarts the phone, so only the first restart would work. Android 12 also has no tool that makes the real call. | +| C. Wait for a long-running Verone process (desktop app in Phase 2, local API in Phase 4) to do the watching | Rejected for now: Android 12 is needed for the benchmark sooner. The watcher's job can move into that process later. | +| D. Find and fix the cause inside Android 12's init, by changing the image on the user's machine (allowed by D-004) | Not chosen: unknown cost, and a debug build of init would be needed. Worth a time-limited look later; if it succeeds, option A can be switched off for Android 12. | +| E. Make `verone list`, `info` and `stop` notice a pending request and act then | Rejected: nothing happens until the user runs a command, which does not behave like a phone. | + +## Design of option A + +### What runs + +One container per computer, named `verone-power`: + +- Image: Verone's helper image (`HELPER_IMAGE`, alpine pinned by digest). No new + download. +- Options: `--privileged --pid=host --network none --read-only + --restart unless-stopped`, label `io.verone.role=power-watcher`. +- Command: a short shell script kept in the Verone source and passed to the container + at creation. Once a second it: + 1. Finds Verone phones: processes that are the first process of their own process + namespace, and whose mount table contains Verone's phone data folder + (`…/verone/phones//data` mounted on `/data`). This matches Verone's phones and + nothing else, including other redroid containers the user runs. + 2. Reads `sys.powerctl` in each one with `nsenter … /system/bin/getprop`. + 3. If it starts with `reboot`: runs `sync` inside the phone, then + `nsenter -t -p reboot -f`. If it starts with `shutdown`: `sync`, then + `nsenter -t -p poweroff -f`. + 4. Writes one line per action to its log (`docker logs verone-power`): time, phone, + request. + +### Which phones it acts on + +Only phones whose Android version is marked in `images.rs` as ignoring power requests. +A new field on `Image`, `power_watcher: bool`, is true for Android 12 and false for 14. +Verone builds the script with the list of those versions (today just `12`), and the +script reads each phone's `ro.build.version.release` and skips any other version. +Android 14 phones are never touched, so their tested behaviour does not change. + +### Lifecycle + +- `verone start` of a phone that needs it: create and start `verone-power` if it is + not running. +- `verone delete` of the last phone that needs it: remove `verone-power`. +- `verone doctor`: shows whether the watcher is running when an Android 12 phone exists. +- `verone stop` is unchanged: restart policy off, power-off request, wait up to 20 s, + kill as a last resort. With the watcher it ends in about 2 s with code 130. + +### What it costs + +- A busybox shell that wakes once a second and reads a few `/proc` files: well under + 1% of one core and a few MB of memory. To be measured in task P12-04. +- No new download, no new dependency. + +### Honest limits + +- **It is not a clean Android shutdown.** On Android 14, Android stops its services and + apps before the container ends. On Android 12 with the watcher, apps are not told; + files are flushed to disk (`sync`) and then the phone ends at once, like pulling the + power after saving. This is better than today's kill after 20 s, but it is not equal + to Android 14 and must say so in the user guide and the benchmark (B1-04: partial). +- **Power off inside Android turns the phone back on**, as on Android 14 today, because + Docker's restart policy brings back any phone that ends while it is on. This is the + existing known limit, not a new one. +- **Security.** `verone-power` can see and enter every process on the computer, like + the phones themselves (privileged containers already give root on the host). It has + no network, a read-only file system and a fixed script. `SECURITY.md` must list it. + +## Tasks + +One commit per task; one pull request for all of them. + +| ID | Task | Acceptance test | +|---|---|---| +| P12-01 | Add `power_watcher` to `Image` (true for 12, false for 14) and the watcher script as a constant, with unit tests for the script text and the phone matching rule. | `cargo test` passes; the script is shown in the test output for review. | +| P12-02 | Start, check and remove `verone-power` from the container engine as described in "Lifecycle". | Unit tests with the stub runtime cover start when missing, no second copy, removal after the last Android 12 phone is deleted. | +| P12-03 | Integration test on a real Android 12 phone: restart from inside, power-off through `verone stop`. | Restart: the phone is booted again within 30 s with a marker file intact. Stop: finishes within 5 s with exit code 130. Android 14 phone in the same run: behaviour unchanged. | +| P12-04 | Measure the watcher's CPU and memory over 10 minutes with one Android 12 phone. | Numbers recorded in `assumptions.md`. | +| P12-05 | Docs: user guide known limits, `SECURITY.md`, `architecture.md`, changelog. | The owner has read the changes. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 1e744ee..1a8cefb 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,6 +29,10 @@ Status: **in use** (updated 2026-11-15). Phase 0 is mostly complete, Phase 1 is Packaging, user documentation and release work run inside every phase from Phase 1 on. +The [phone fidelity benchmark](benchmark.md) (D-016) is run at the end of +every phase, so each phase's progress towards "behave like a phone" is measured against +a real phone and against other virtual Android systems. + --- ## Phase 0 — Proof diff --git a/docs/user-guide/cli.md b/docs/user-guide/cli.md index 83ff742..16270d3 100644 --- a/docs/user-guide/cli.md +++ b/docs/user-guide/cli.md @@ -34,7 +34,7 @@ Creates a phone. It is not started, and nothing is downloaded. | Option | Default | Meaning | |---|---|---| | `--name TEXT` | the id | The name shown in windows and lists. | -| `--android VERSION` | `14` | Android version. Only 14 is available in version 0.1. | +| `--android VERSION` | `14` | Android version: `14` or `12`. Version 0.1.0 offers 14 only; 12 comes in the next version. | | `--size WIDTHxHEIGHT` | `720x1280` | Screen size in pixels, each side from 240 to 4096. | | `--dpi NUMBER` | `320` | Screen density, from 72 to 640. | | `--graphics auto\|software\|gpu` | `auto` | How the screen is drawn. See "Graphics" below. | @@ -141,7 +141,10 @@ Docker. - **"Power off" inside Android turns the phone back on.** Use `verone stop`. - **No Google apps or Play Store.** Install apps from APK files. -- **One Android version (14), x86-64 computers, Docker only.** +- **Android 14 and 12 only, x86-64 computers, Docker only.** +- **Android 12: "Restart" and "Power off" inside Android do nothing.** The phone keeps + running. Use `verone restart` or `verone stop`. On Android 12 `verone stop` takes about 20 seconds + and ends by forcing the phone off; your files were kept in tests. - **No sound has been verified.** scrcpy forwards audio on Android 11 and later, but it has not been tested with Verone. - **Phone data is not encrypted.** See [SECURITY.md](../../SECURITY.md). From e96c9ba6756a14b9d999affc26ed740231636897 Mon Sep 17 00:00:00 2001 From: axoineo Date: Tue, 17 Nov 2026 00:30:05 +0530 Subject: [PATCH 2/7] Add the power watcher script and mark Android 12 as needing it (P12-01) Co-Authored-By: Claude Opus 5.5 --- crates/verone-engine-container/src/images.rs | 19 + crates/verone-engine-container/src/lib.rs | 1 + crates/verone-engine-container/src/power.rs | 354 +++++++++++++++++++ 3 files changed, 374 insertions(+) create mode 100644 crates/verone-engine-container/src/power.rs diff --git a/crates/verone-engine-container/src/images.rs b/crates/verone-engine-container/src/images.rs index 056a72a..bcc382e 100644 --- a/crates/verone-engine-container/src/images.rs +++ b/crates/verone-engine-container/src/images.rs @@ -16,6 +16,9 @@ pub struct Image { pub tag: &'static str, /// The content digest the image is pulled and run by. pub digest: &'static str, + /// True if Android in this image ignores restart and power-off requests made + /// inside it, so the power watcher must carry them out (decision D-017). + pub power_watcher: bool, } impl Image { @@ -41,12 +44,14 @@ pub const IMAGES: &[Image] = &[ repository: "redroid/redroid", tag: "14.0.0-latest", digest: "sha256:a3e654caad74faed03cd5ead057a989e06f507778cda678e5d3b9772e0092f1c", + power_watcher: false, }, Image { android: "12", repository: "redroid/redroid", tag: "12.0.0-latest", digest: "sha256:52332b2d74f337982d5ac281a8020ec297fb1ea05cbdcdaaa9c19a2065ae1adc", + power_watcher: true, }, ]; @@ -67,6 +72,15 @@ pub fn image_for(android: &str) -> Result<&'static Image> { }) } +/// The Android versions whose phones need the power watcher. +pub fn power_watcher_versions() -> Vec<&'static str> { + IMAGES + .iter() + .filter(|image| image.power_watcher) + .map(|image| image.android) + .collect() +} + /// The Android versions that have an image. pub fn supported_versions() -> Vec<&'static str> { IMAGES.iter().map(|image| image.android).collect() @@ -97,6 +111,11 @@ mod tests { assert_eq!(image.display_name(), "redroid/redroid:12.0.0-latest"); } + #[test] + fn only_android_12_needs_the_power_watcher() { + assert_eq!(power_watcher_versions(), ["12"]); + } + #[test] fn the_default_android_version_comes_first() { assert_eq!(IMAGES[0].android, verone_core::profile::DEFAULT_ANDROID); diff --git a/crates/verone-engine-container/src/lib.rs b/crates/verone-engine-container/src/lib.rs index 631c1d6..d9b2c92 100644 --- a/crates/verone-engine-container/src/lib.rs +++ b/crates/verone-engine-container/src/lib.rs @@ -6,6 +6,7 @@ pub mod adb; pub mod engine; pub mod host; pub mod images; +pub mod power; pub mod runtime; pub use engine::ContainerEngine; diff --git a/crates/verone-engine-container/src/power.rs b/crates/verone-engine-container/src/power.rs new file mode 100644 index 0000000..e736dc0 --- /dev/null +++ b/crates/verone-engine-container/src/power.rs @@ -0,0 +1,354 @@ +//! The power watcher (decision D-017, `docs/design/android-12-power.md`). +//! +//! On some Android versions (Android 12 today), init receives a restart or power-off +//! request made inside Android and then does nothing. The watcher is one small helper +//! container per computer that notices such a request and ends the phone with the +//! real `reboot` system call. The kernel turns that into the same container exit +//! codes Android 14 produces itself: 129 for a restart, 130 for a power-off. + +use std::path::Path; + +use crate::images::HELPER_IMAGE; + +/// The watcher's container name. +pub const WATCHER_NAME: &str = "verone-power"; + +/// Label that marks Verone's helper containers by role. +pub const LABEL_ROLE: &str = "io.verone.role"; + +/// The watcher's role label value. +pub const ROLE: &str = "power-watcher"; + +/// The watcher's shell script, run by busybox `sh` in the helper image. +/// +/// Arguments: the phones folder, then the Android versions to act on. +/// `VERONE_PROC` and `VERONE_ONCE` exist for the unit tests only. +pub const SCRIPT: &str = r#"PHONES="$1"; shift; VERSIONS=" $* " +PROC="${VERONE_PROC:-/proc}" +known=" " +log() { echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) $*"; } +prop() { nsenter -t "$1" -m -u -i -n -p -r -w /system/bin/getprop "$2" 2>/dev/null; } +log "watching phones in $PHONES with Android$VERSIONS" +while :; do + for status in "$PROC"/[0-9]*/status; do + pid=${status%/status}; pid=${pid##*/} + case "$known" in *" $pid=no "*) continue ;; esac + case "$known" in *" $pid=yes "*) ;; *) + # A phone is the first process of its own process namespace... + first=no + while read -r key outer inner deeper; do + if [ "$key" = "NSpid:" ]; then + [ "$inner" = 1 ] && [ -z "$deeper" ] && first=yes + break + fi + done < "$status" 2>/dev/null + [ "$first" = yes ] || continue + # ...whose /data is //data, and whose Android version + # is one the watcher acts on. + root=$(awk '$5 == "/data" { print $4; exit }' "$PROC/$pid/mountinfo" 2>/dev/null) + id=${root%/data}; id=${id##*/} + verdict=no + case "$root" in */phones/*/data) + case "$PHONES/$id/data" in *"$root") + case "$VERSIONS" in *" $(prop "$pid" ro.build.version.release) "*) verdict=yes ;; esac ;; + esac ;; + esac + known="$known$pid=$verdict " + [ "$verdict" = yes ] || continue + log "watching phone $id (process $pid)" ;; + esac + request=$(prop "$pid" sys.powerctl) + case "$request" in + reboot*) action=reboot ;; + shutdown*) action=poweroff ;; + *) continue ;; + esac + log "phone in process $pid asked for '$request': $action" + sync + nsenter -t "$pid" -p "$action" -f || log "could not $action process $pid" + done + [ -n "$VERONE_ONCE" ] && exit 0 + sleep 1 +done +"#; + +/// Everything needed to create the watcher's container. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WatcherSpec { + /// Options placed before the image, without labels. + pub options: Vec, + /// The image reference. + pub image: String, + /// The command placed after the image. + pub command: Vec, +} + +impl WatcherSpec { + /// The spec for a phones folder and the Android versions to act on. + pub fn new(phones_dir: &Path, versions: &[&str]) -> Self { + let options = [ + "--privileged", + "--pid", + "host", + "--network", + "none", + "--read-only", + "--restart", + "unless-stopped", + ] + .map(str::to_string) + .to_vec(); + let mut command = vec![ + "sh".to_string(), + "-c".to_string(), + SCRIPT.to_string(), + WATCHER_NAME.to_string(), + phones_dir.display().to_string(), + ]; + command.extend(versions.iter().map(|version| (*version).to_string())); + Self { + options, + image: HELPER_IMAGE.to_string(), + command, + } + } + + /// A short value that changes whenever any part of the spec changes. Stored as + /// a label so a later start can tell whether the watcher is current. + pub fn fingerprint(&self) -> String { + // FNV-1a, 64 bits: stable across Rust versions, unlike the std hasher. + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + let parts = self + .options + .iter() + .chain(std::iter::once(&self.image)) + .chain(&self.command); + for part in parts { + for byte in part.bytes().chain(std::iter::once(0)) { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(0x0100_0000_01b3); + } + } + format!("{hash:016x}") + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::path::PathBuf; + use std::process::Command; + + #[test] + fn the_spec_runs_the_script_with_the_folder_and_versions() { + let spec = WatcherSpec::new(Path::new("/home/a/.local/share/verone/phones"), &["12"]); + assert_eq!(spec.image, HELPER_IMAGE); + assert!(spec.options.contains(&"--privileged".to_string())); + assert!(spec.options.windows(2).any(|w| w == ["--pid", "host"])); + assert!(spec.options.windows(2).any(|w| w == ["--network", "none"])); + assert!(spec.options.contains(&"--read-only".to_string())); + assert_eq!(spec.command[..2], ["sh", "-c"]); + assert_eq!( + spec.command[3..], + ["verone-power", "/home/a/.local/share/verone/phones", "12"] + ); + } + + #[test] + fn the_fingerprint_follows_the_spec() { + let a = WatcherSpec::new(Path::new("/p"), &["12"]); + assert_eq!( + a.fingerprint(), + WatcherSpec::new(Path::new("/p"), &["12"]).fingerprint() + ); + assert_eq!(a.fingerprint().len(), 16); + assert_ne!( + a.fingerprint(), + WatcherSpec::new(Path::new("/q"), &["12"]).fingerprint() + ); + assert_ne!( + a.fingerprint(), + WatcherSpec::new(Path::new("/p"), &["11", "12"]).fingerprint() + ); + } + + #[test] + fn the_script_is_valid_shell() { + let status = Command::new("sh") + .args(["-n", "-c", SCRIPT]) + .status() + .unwrap(); + assert!(status.success()); + } + + /// A fake host: a `/proc` folder and an `nsenter` that answers from files and + /// records what it was asked to do. + struct FakeHost { + temp: tempfile::TempDir, + } + + impl FakeHost { + fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let bin = temp.path().join("bin"); + fs::create_dir_all(&bin).unwrap(); + fs::create_dir_all(temp.path().join("props")).unwrap(); + // Run through `sh` so no freshly written file is executed directly. + let nsenter = format!( + r#"#!/bin/sh +pid="$2"; last=""; for a in "$@"; do prev="$last"; last="$a"; done +case "$*" in + *getprop*) cat "{props}/$pid.$last" 2>/dev/null ;; + *) echo "$pid $prev" >> "{log}" ;; +esac +"#, + props = temp.path().join("props").display(), + log = temp.path().join("actions.log").display(), + ); + fs::write(bin.join("nsenter.sh"), nsenter).unwrap(); + fs::write( + bin.join("nsenter"), + format!( + "#!/bin/sh\nexec sh {} \"$@\"\n", + bin.join("nsenter.sh").display() + ), + ) + .unwrap(); + fs::write(bin.join("sync"), "#!/bin/sh\n").unwrap(); + for name in ["nsenter", "sync"] { + Command::new("chmod") + .args(["+x", &bin.join(name).display().to_string()]) + .status() + .unwrap(); + } + Self { temp } + } + + fn proc(&self) -> PathBuf { + self.temp.path().join("proc") + } + + /// A process with an `NSpid` line and an optional `/data` mount root. + fn process(&self, pid: u32, nspid: &str, data_root: Option<&str>) { + let dir = self.proc().join(pid.to_string()); + fs::create_dir_all(&dir).unwrap(); + fs::write( + dir.join("status"), + format!("Name:\tinit\nNSpid:\t{nspid}\n"), + ) + .unwrap(); + let mut mounts = "22 1 0:21 / /proc rw - proc proc rw\n".to_string(); + if let Some(root) = data_root { + mounts.push_str(&format!("40 30 259:3 {root} /data rw - ext4 /dev/x rw\n")); + } + fs::write(dir.join("mountinfo"), mounts).unwrap(); + } + + fn prop(&self, pid: u32, name: &str, value: &str) { + fs::write( + self.temp.path().join("props").join(format!("{pid}.{name}")), + format!("{value}\n"), + ) + .unwrap(); + } + + /// Runs one pass of the script and returns the actions taken. + fn run_once(&self, phones: &str) -> Vec { + let path = format!( + "{}:{}", + self.temp.path().join("bin").display(), + std::env::var("PATH").unwrap_or_default() + ); + let output = Command::new("sh") + .args(["-c", SCRIPT, WATCHER_NAME, phones, "12"]) + .env("PATH", path) + .env("VERONE_PROC", self.proc()) + .env("VERONE_ONCE", "1") + .output() + .unwrap(); + assert!(output.status.success(), "{output:?}"); + fs::read_to_string(self.temp.path().join("actions.log")) + .unwrap_or_default() + .lines() + .map(str::to_string) + .collect() + } + } + + const PHONES: &str = "/home/a/.local/share/verone/phones"; + + #[test] + fn a_restart_request_restarts_the_phone_and_a_shutdown_powers_it_off() { + let host = FakeHost::new(); + host.process( + 100, + "100\t1", + Some("/a/.local/share/verone/phones/one/data"), + ); + host.prop(100, "ro.build.version.release", "12"); + host.prop(100, "sys.powerctl", "reboot,shell"); + host.process( + 200, + "200\t1", + Some("/a/.local/share/verone/phones/two/data"), + ); + host.prop(200, "ro.build.version.release", "12"); + host.prop(200, "sys.powerctl", "shutdown,userrequested"); + let mut actions = host.run_once(PHONES); + actions.sort(); + assert_eq!(actions, ["100 reboot", "200 poweroff"]); + } + + #[test] + fn a_phone_without_a_request_is_left_alone() { + let host = FakeHost::new(); + host.process( + 100, + "100\t1", + Some("/a/.local/share/verone/phones/one/data"), + ); + host.prop(100, "ro.build.version.release", "12"); + host.prop(100, "sys.powerctl", ""); + assert!(host.run_once(PHONES).is_empty()); + } + + #[test] + fn only_verone_phones_with_a_listed_version_are_touched() { + let host = FakeHost::new(); + // Android 14: handles its own requests. + host.process(1, "1", None); + host.process( + 100, + "100\t1", + Some("/a/.local/share/verone/phones/new/data"), + ); + host.prop(100, "ro.build.version.release", "14"); + host.prop(100, "sys.powerctl", "reboot,shell"); + // Another redroid container, not Verone's. + host.process(200, "200\t1", Some("/a/redroid-data")); + host.prop(200, "ro.build.version.release", "12"); + host.prop(200, "sys.powerctl", "reboot,shell"); + // A phone folder of another Verone data home. + host.process(300, "300\t1", Some("/b/other/verone/phones/x/data")); + host.prop(300, "ro.build.version.release", "12"); + host.prop(300, "sys.powerctl", "reboot,shell"); + // A process inside a phone, not its first one. + host.process( + 400, + "400\t57", + Some("/a/.local/share/verone/phones/one/data"), + ); + host.prop(400, "ro.build.version.release", "12"); + host.prop(400, "sys.powerctl", "reboot,shell"); + // A phone two namespaces deep. + host.process( + 500, + "500\t9\t1", + Some("/a/.local/share/verone/phones/one/data"), + ); + host.prop(500, "ro.build.version.release", "12"); + host.prop(500, "sys.powerctl", "reboot,shell"); + assert!(host.run_once(PHONES).is_empty()); + } +} From ef5c1a50ca625b4fc431a3465a114d178c663e46 Mon Sep 17 00:00:00 2001 From: axoineo Date: Tue, 17 Nov 2026 00:32:23 +0530 Subject: [PATCH 3/7] Start, check and remove the power watcher with Android 12 phones (P12-02) Each Verone data folder gets its own watcher, verone-power-, so a test run with a temporary folder never replaces the user's watcher. Co-Authored-By: Claude Opus 5.5 --- crates/verone-engine-container/src/engine.rs | 267 +++++++++++++++++- crates/verone-engine-container/src/power.rs | 53 +++- crates/verone-engine-container/src/runtime.rs | 20 ++ 3 files changed, 321 insertions(+), 19 deletions(-) diff --git a/crates/verone-engine-container/src/engine.rs b/crates/verone-engine-container/src/engine.rs index 4d8220a..37db26a 100644 --- a/crates/verone-engine-container/src/engine.rs +++ b/crates/verone-engine-container/src/engine.rs @@ -11,12 +11,13 @@ use verone_core::engine::{ }; use verone_core::process::Runner; use verone_core::profile::{EngineKind, GraphicsMode, GraphicsUsed, LastBoot, Profile, State}; -use verone_core::storage::{PhoneDir, PhoneId}; +use verone_core::storage::{PhoneDir, PhoneId, Storage}; use verone_core::{Error, Result}; use crate::adb::Adb; use crate::host::HostProbe; use crate::images::{self, HELPER_IMAGE, IMAGES}; +use crate::power::{self, LABEL_ROLE, ROLE, WatcherSpec}; use crate::runtime::{Container, Docker}; /// How long Android may take to boot. @@ -273,6 +274,16 @@ impl ContainerEngine { ) -> Result<()> { let name = Self::container_name(&profile.id); let spec = self.spec(profile, phone, graphics)?; + if images::image_for(&profile.android)?.power_watcher { + self.ensure_power_watcher().map_err(|error| { + Error::failed(format!( + "could not start the power watcher that Android {} phones need: {}", + profile.android, + error.message() + )) + .with_hint("Run verone doctor, then try again.") + })?; + } self.ensure_container(profile, &spec)?; self.docker.update_restart(&name, RESTART_ON)?; self.docker.start(&name).map_err(|error| { @@ -369,6 +380,96 @@ impl ContainerEngine { }) } + /// The folder that holds every phone, resolved the way the kernel reports it in + /// mount tables, which the power watcher matches against. + fn phones_dir(&self) -> PathBuf { + let dir = Storage::new(&self.data_home).phones_dir(); + dir.canonicalize().unwrap_or(dir) + } + + /// Makes sure the power watcher for this data folder exists, is current and + /// runs (decision D-017). + fn ensure_power_watcher(&self) -> Result<()> { + let phones_dir = self.phones_dir(); + let name = power::watcher_name(&phones_dir); + let spec = WatcherSpec::new(&phones_dir, &images::power_watcher_versions()); + let fingerprint = spec.fingerprint(); + if let Some(existing) = self.docker.inspect(&name)? { + if existing.labels.get(LABEL_SPEC) == Some(&fingerprint) { + if existing.status != "running" { + self.docker.start(&name)?; + } + return Ok(()); + } + self.docker.remove(&name)?; + } + if !self.docker.image_present(HELPER_IMAGE)? { + self.docker.pull(HELPER_IMAGE)?; + } + let mut options = vec![ + "--label".to_string(), + format!("{LABEL_ROLE}={ROLE}"), + "--label".to_string(), + format!("{LABEL_SPEC}={fingerprint}"), + ]; + options.extend(spec.options); + self.docker + .create(&name, &options, &spec.image, &spec.command)?; + self.docker.start(&name) + } + + /// True if any phone's container runs an image that needs the power watcher. + fn power_watcher_needed(&self) -> Result { + let needing: Vec = IMAGES + .iter() + .filter(|image| image.power_watcher) + .map(images::Image::reference) + .collect(); + Ok(self + .docker + .images_with_label(LABEL_PHONE)? + .iter() + .any(|image| needing.contains(image))) + } + + /// Removes the power watcher once no phone needs it. + fn remove_unused_power_watcher(&self) -> Result<()> { + if self.power_watcher_needed()? { + return Ok(()); + } + let name = power::watcher_name(&self.phones_dir()); + if self.docker.inspect(&name)?.is_some() { + self.docker.remove(&name)?; + } + Ok(()) + } + + /// The `verone doctor` line for the power watcher, if any phone needs it. + fn power_watcher_check(&self) -> Option { + const NAME: &str = "Power watcher for Android 12"; + if !self.power_watcher_needed().unwrap_or(false) { + return None; + } + let name = power::watcher_name(&self.phones_dir()); + let running = self + .docker + .inspect(&name) + .ok() + .flatten() + .is_some_and(|container| container.status == "running"); + Some(if running { + HostCheck::ok(NAME, format!("{name} is running")) + } else { + HostCheck::warning( + NAME, + format!( + "{name} is not running, so Restart and Power off inside Android 12 do nothing" + ), + "Start any Android 12 phone with verone start; it starts the watcher again.", + ) + }) + } + /// Every supported image and whether it is downloaded. pub fn image_statuses(&self) -> Result> { IMAGES @@ -421,9 +522,11 @@ impl Engine for ContainerEngine { .unwrap_or(false) }) .unwrap_or(false); - Ok(self + let mut checks = self .probe - .check_all(&self.docker, image_present, &self.data_home)) + .check_all(&self.docker, image_present, &self.data_home); + checks.extend(self.power_watcher_check()); + Ok(checks) } fn prepare_image(&self, android: &str) -> Result<()> { @@ -447,7 +550,7 @@ impl Engine for ContainerEngine { if self.docker.inspect(&name)?.is_some() { self.docker.remove(&name)?; } - Ok(()) + self.remove_unused_power_watcher() } fn start(&self, profile: &Profile, phone: &PhoneDir) -> Result { @@ -1170,7 +1273,161 @@ exec*) [ -f "$(dirname "$0")/software" ] && echo 1 ;; let f = Fixture::new(NO_CONTAINER); f.engine(&[]).destroy(f.id()).unwrap(); - assert_eq!(f.stub.calls().len(), 1); + assert!(f.stub.calls().iter().all(|call| !call.starts_with("rm"))); + } + + // ---- power watcher (D-017) ---- + + const ANDROID_12_IMAGE: &str = + "redroid/redroid@sha256:52332b2d74f337982d5ac281a8020ec297fb1ea05cbdcdaaa9c19a2065ae1adc"; + + fn watcher_name(f: &Fixture) -> String { + let dir = f.temp.path().join("phones"); + power::watcher_name(&dir.canonicalize().unwrap_or(dir)) + } + + fn watcher_fingerprint(f: &Fixture) -> String { + let dir = f.temp.path().join("phones"); + WatcherSpec::new(&dir.canonicalize().unwrap_or(dir), &["12"]).fingerprint() + } + + /// A stub answer for inspecting the watcher only. + fn watcher_arm(f: &Fixture, status: &str) -> String { + format!( + r#""inspect --type container {}"*) echo '[{{"State":{{"Status":"{status}","ExitCode":0}},"Config":{{"Labels":{{"io.verone.spec":"{}"}}}}}}]' ;;"#, + watcher_name(f), + watcher_fingerprint(f) + ) + } + + /// A fixture whose stub runtime is chosen after the fixture exists, because the + /// answers depend on its temporary folder. + fn fixture_with(arms: impl Fn(&Fixture) -> String) -> Fixture { + let mut f = Fixture::new(""); + f.stub = Stub::new(&arms(&f)); + f + } + + #[test] + fn starting_an_android_12_phone_starts_the_watcher_first() { + let mut f = fixture_with(|_| format!("{NO_CONTAINER}\nexec*) echo 1 ;;")); + f.profile.android = "12".to_string(); + f.engine(&[]).start(&f.profile, &f.phone).unwrap(); + let name = watcher_name(&f); + let calls = f.stub.calls(); + let create = calls + .iter() + .position(|call| call.starts_with(&format!("create --name {name} "))) + .expect("the watcher is created"); + assert!(calls[create].contains("--label io.verone.role=power-watcher")); + assert!(calls[create].contains("--pid host")); + let started = |who: &str| { + calls + .iter() + .position(|call| call == &format!("start {who}")) + .unwrap_or_else(|| panic!("{who} is started: {calls:?}")) + }; + assert!(started(&name) < started("verone-work")); + } + + #[test] + fn starting_an_android_14_phone_never_touches_the_watcher() { + let f = Fixture::new(&format!("{NO_CONTAINER}\nexec*) echo 1 ;;")); + f.engine(&[]).start(&f.profile, &f.phone).unwrap(); + assert!( + f.stub + .calls() + .iter() + .all(|call| !call.contains("verone-power")) + ); + } + + #[test] + fn a_current_watcher_is_never_created_twice() { + for (status, start_expected) in [("running", false), ("exited", true)] { + let mut f = fixture_with(|f| { + format!( + "{}\n{NO_CONTAINER}\nexec*) echo 1 ;;", + watcher_arm(f, status) + ) + }); + f.profile.android = "12".to_string(); + f.engine(&[]).start(&f.profile, &f.phone).unwrap(); + let name = watcher_name(&f); + let calls = f.stub.calls(); + assert!( + calls + .iter() + .all(|call| !call.starts_with(&format!("create --name {name}"))), + "{calls:?}" + ); + assert!( + calls + .iter() + .all(|call| !call.starts_with(&format!("rm --force {name}"))) + ); + assert_eq!( + calls.contains(&format!("start {name}")), + start_expected, + "{status}" + ); + } + } + + #[test] + fn deleting_the_last_android_12_phone_removes_the_watcher() { + let f = fixture_with(|f| { + format!( + "{}\n{}", + watcher_arm(f, "running"), + inspect_arm("exited", "") + ) + }); + f.engine(&[]).destroy(f.id()).unwrap(); + assert!( + f.stub + .calls() + .contains(&format!("rm --force {}", watcher_name(&f))) + ); + + let f = fixture_with(|f| { + format!( + "{}\nps*) echo '{ANDROID_12_IMAGE}' ;;\n{}", + watcher_arm(f, "running"), + inspect_arm("exited", "") + ) + }); + f.engine(&[]).destroy(f.id()).unwrap(); + let calls = f.stub.calls(); + assert!(calls.contains(&"rm --force verone-work".to_string())); + assert!(!calls.contains(&format!("rm --force {}", watcher_name(&f)))); + } + + #[test] + fn doctor_reports_the_watcher_only_when_a_phone_needs_it() { + let check = |arms: &dyn Fn(&Fixture) -> String| { + let f = fixture_with(arms); + f.engine(&[]) + .check_host() + .unwrap() + .into_iter() + .find(|check| check.name == "Power watcher for Android 12") + }; + assert!(check(&|_| String::new()).is_none()); + + let missing = check(&|_| format!("ps*) echo '{ANDROID_12_IMAGE}' ;;\n{NO_CONTAINER}")) + .expect("a check when an Android 12 phone exists"); + assert!(missing.detail.contains("not running"), "{missing:?}"); + assert!(missing.fix.is_some()); + + let running = check(&|f| { + format!( + "ps*) echo '{ANDROID_12_IMAGE}' ;;\n{}", + watcher_arm(f, "running") + ) + }) + .unwrap(); + assert!(running.detail.contains("is running"), "{running:?}"); } #[test] diff --git a/crates/verone-engine-container/src/power.rs b/crates/verone-engine-container/src/power.rs index e736dc0..d682811 100644 --- a/crates/verone-engine-container/src/power.rs +++ b/crates/verone-engine-container/src/power.rs @@ -10,8 +10,8 @@ use std::path::Path; use crate::images::HELPER_IMAGE; -/// The watcher's container name. -pub const WATCHER_NAME: &str = "verone-power"; +/// The start of every watcher's container name, also the script's `$0`. +pub const WATCHER_PREFIX: &str = "verone-power-"; /// Label that marks Verone's helper containers by role. pub const LABEL_ROLE: &str = "io.verone.role"; @@ -102,7 +102,7 @@ impl WatcherSpec { "sh".to_string(), "-c".to_string(), SCRIPT.to_string(), - WATCHER_NAME.to_string(), + "verone-power".to_string(), phones_dir.display().to_string(), ]; command.extend(versions.iter().map(|version| (*version).to_string())); @@ -116,21 +116,34 @@ impl WatcherSpec { /// A short value that changes whenever any part of the spec changes. Stored as /// a label so a later start can tell whether the watcher is current. pub fn fingerprint(&self) -> String { - // FNV-1a, 64 bits: stable across Rust versions, unlike the std hasher. - let mut hash: u64 = 0xcbf2_9ce4_8422_2325; - let parts = self + fnv(self .options .iter() .chain(std::iter::once(&self.image)) - .chain(&self.command); - for part in parts { - for byte in part.bytes().chain(std::iter::once(0)) { - hash ^= u64::from(byte); - hash = hash.wrapping_mul(0x0100_0000_01b3); - } + .chain(&self.command) + .map(String::as_str)) + } +} + +/// The watcher's container name for a phones folder. Each Verone data folder gets +/// its own watcher, so a test run with a temporary folder never replaces the one +/// that watches the user's phones. +pub fn watcher_name(phones_dir: &Path) -> String { + let code = fnv(std::iter::once(phones_dir.display().to_string().as_str())); + format!("{WATCHER_PREFIX}{}", &code[..8]) +} + +/// FNV-1a, 64 bits, as 16 hex digits: stable across Rust versions, unlike the +/// std hasher. +fn fnv<'a>(parts: impl Iterator) -> String { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + for part in parts { + for byte in part.bytes().chain(std::iter::once(0)) { + hash ^= u64::from(byte); + hash = hash.wrapping_mul(0x0100_0000_01b3); } - format!("{hash:016x}") } + format!("{hash:016x}") } #[cfg(test)] @@ -155,6 +168,18 @@ mod tests { ); } + #[test] + fn each_phones_folder_gets_its_own_watcher_name() { + let a = watcher_name(Path::new("/home/a/.local/share/verone/phones")); + assert!(a.starts_with("verone-power-")); + assert_eq!(a.len(), "verone-power-".len() + 8); + assert_eq!( + a, + watcher_name(Path::new("/home/a/.local/share/verone/phones")) + ); + assert_ne!(a, watcher_name(Path::new("/tmp/test/phones"))); + } + #[test] fn the_fingerprint_follows_the_spec() { let a = WatcherSpec::new(Path::new("/p"), &["12"]); @@ -261,7 +286,7 @@ esac std::env::var("PATH").unwrap_or_default() ); let output = Command::new("sh") - .args(["-c", SCRIPT, WATCHER_NAME, phones, "12"]) + .args(["-c", SCRIPT, "verone-power", phones, "12"]) .env("PATH", path) .env("VERONE_PROC", self.proc()) .env("VERONE_ONCE", "1") diff --git a/crates/verone-engine-container/src/runtime.rs b/crates/verone-engine-container/src/runtime.rs index 280bd70..6f4a2ac 100644 --- a/crates/verone-engine-container/src/runtime.rs +++ b/crates/verone-engine-container/src/runtime.rs @@ -292,6 +292,26 @@ impl Docker { } } + /// The image of every container, running or not, that carries a label. + pub fn images_with_label(&self, label: &str) -> Result> { + let filter = format!("label={label}"); + let output = self.runner.run_ok(&self.cmd().args([ + "ps", + "--all", + "--filter", + &filter, + "--format", + "{{.Image}}", + ]))?; + Ok(output + .stdout + .lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .map(str::to_string) + .collect()) + } + /// Runs a program inside a running container and returns its output, whatever /// its exit code. pub fn exec(&self, name: &str, args: &[&str], timeout: Duration) -> Result { From 82d18049c704f9968c629d151d11162da4c6bc11 Mon Sep 17 00:00:00 2001 From: axoineo Date: Tue, 17 Nov 2026 00:37:04 +0530 Subject: [PATCH 4/7] Test restart and power-off on a real Android 12 phone (P12-03) On the reference laptop the phone was back 6.2 s after a restart request inside Android, and verone stop took 1.2 s with exit code 130. Co-Authored-By: Claude Opus 5.5 --- .../tests/integration.rs | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/crates/verone-engine-container/tests/integration.rs b/crates/verone-engine-container/tests/integration.rs index 687f4f3..dd8157b 100644 --- a/crates/verone-engine-container/tests/integration.rs +++ b/crates/verone-engine-container/tests/integration.rs @@ -341,3 +341,79 @@ fn an_optional_adb_port_is_published_on_the_loopback_address_only() { ); assert_eq!(android_release(&t), "14"); } + +/// Decision D-017: on Android 12 the power watcher carries out restart and power-off +/// requests made inside Android, which Android 12 itself ignores. +#[test] +fn android_12_restart_and_power_off_work_through_the_power_watcher() { + if !enabled() { + return; + } + let _guard = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut t = TestPhone::new("it-android12"); + t.profile.android = "12".to_string(); + t.profile.save(&t.phone).unwrap(); + let id = t.id().clone(); + let docker = t.engine.docker().clone(); + let phones_dir = t.storage.phones_dir().canonicalize().unwrap(); + let watcher = verone_engine_container::power::watcher_name(&phones_dir); + + t.engine.start(&t.profile, &t.phone).unwrap(); + assert_eq!(android_release(&t), "12"); + let running = |name: &str| { + docker + .inspect(name) + .unwrap() + .is_some_and(|container| container.status == "running") + }; + assert!( + running(&watcher), + "the watcher runs beside an Android 12 phone" + ); + + // Shared storage becomes writable a few seconds after boot (A-22). + let deadline = Instant::now() + Duration::from_secs(30); + while t.exec(&["sh", "-c", "echo kept > /sdcard/marker && echo ok"]) != "ok" { + assert!( + Instant::now() < deadline, + "shared storage never became writable" + ); + thread::sleep(Duration::from_secs(1)); + } + + // A restart requested inside Android: the phone ends and Docker brings it back. + let first_start = docker.inspect(&t.name()).unwrap().unwrap().started_at; + let requested = Instant::now(); + // Android's reboot command waits forever after asking, so its result is ignored. + let _ = docker.exec(&t.name(), &["reboot"], Duration::from_secs(20)); + let deadline = requested + Duration::from_secs(30); + loop { + let restarted = docker + .inspect(&t.name()) + .unwrap() + .is_some_and(|container| container.started_at != first_start); + if restarted && t.engine.status(&id).unwrap() == PhoneStatus::Running { + break; + } + assert!( + Instant::now() < deadline, + "the phone was not back within 30 s of the restart request" + ); + thread::sleep(Duration::from_millis(500)); + } + eprintln!("back after a restart request in {:?}", requested.elapsed()); + assert_eq!(t.exec(&["cat", "/sdcard/marker"]), "kept"); + + // verone stop: Android powers off through the watcher, quickly and with the + // power-off exit code, not the runtime's kill. + let stopping = Instant::now(); + t.engine.stop(&id).unwrap(); + let took = stopping.elapsed(); + eprintln!("stopped in {took:?}"); + assert!(took < Duration::from_secs(5), "stop took {took:?}"); + assert_eq!(docker.inspect(&t.name()).unwrap().unwrap().exit_code, 130); + + // Deleting the last Android 12 phone of this data folder removes its watcher. + t.engine.destroy(&id).unwrap(); + assert!(docker.inspect(&watcher).unwrap().is_none()); +} From feabaf7797832bac3cc7d5f8b8aacb2005c91c24 Mon Sep 17 00:00:00 2001 From: axoineo Date: Tue, 17 Nov 2026 18:42:01 +0530 Subject: [PATCH 5/7] Open phones with uncompressed audio so the window appears redroid images have no Opus encoder, scrcpy's default audio codec. The audio stream failed, scrcpy's helper in the phone was killed and no window appeared. verone open now passes --audio-codec=raw unless the user gives their own audio option. Co-Authored-By: Claude Opus 5.5 --- crates/verone-cli/src/phone.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/verone-cli/src/phone.rs b/crates/verone-cli/src/phone.rs index a0e4d3f..622988c 100644 --- a/crates/verone-cli/src/phone.rs +++ b/crates/verone-cli/src/phone.rs @@ -416,11 +416,23 @@ pub fn open(env: &Env, tools: &Tools, id: &str, extra: &[String]) let Some((program, leading)) = tools.scrcpy.split_first() else { return Err(Error::failed("no screen-mirroring program is configured")); }; + // The redroid images have no Opus audio encoder, scrcpy's default. Without + // this, scrcpy's helper inside the phone fails and no window appears. + // Uncompressed audio needs no encoder. The user's own audio options win. + let audio_chosen = extra + .iter() + .any(|option| option.starts_with("--audio") || option == "--no-audio"); + let audio: &[&str] = if audio_chosen { + &[] + } else { + &["--audio-codec=raw"] + }; let cmd = Cmd::new(program) .args(leading) .arg("--serial") .arg(endpoint.to_string()) .arg(format!("--window-title=Verone – {}", profile.name)) + .args(audio) .args(extra) .no_timeout() .passthrough(); @@ -1118,7 +1130,20 @@ mod tests { ); assert_eq!( f.calls().last().unwrap(), - "scrcpy --serial 127.0.0.1:5555 --window-title=Verone – Work phone --no-window --time-limit=5" + "scrcpy --serial 127.0.0.1:5555 --window-title=Verone – Work phone --audio-codec=raw --no-window --time-limit=5" + ); + + // Audio options given by the user replace the default. + open( + &f.human(), + &tools(&adb, stub_scrcpy(&script)), + "work", + &["--no-audio".to_string()], + ) + .unwrap(); + assert_eq!( + f.calls().last().unwrap(), + "scrcpy --serial 127.0.0.1:5555 --window-title=Verone – Work phone --no-audio" ); } From 0fe5ded5df41b7920a4bfe13a88febc1577cd1ab Mon Sep 17 00:00:00 2001 From: axoineo Date: Tue, 17 Nov 2026 18:49:51 +0530 Subject: [PATCH 6/7] Look for phones every 10 s and record the watcher's cost (P12-04) Reading every process every second cost 21% of one core. Looking for phones every 10 s, and at once when a watched phone ends, brings it to 1.7% on average with at most 3 MB of memory. Also stop a redirection from printing 'can't open' for processes that end mid-read. Co-Authored-By: Claude Opus 5.5 --- crates/verone-engine-container/src/power.rs | 73 +++++++++++++-------- docs/assumptions.md | 7 +- 2 files changed, 52 insertions(+), 28 deletions(-) diff --git a/crates/verone-engine-container/src/power.rs b/crates/verone-engine-container/src/power.rs index d682811..de3e14c 100644 --- a/crates/verone-engine-container/src/power.rs +++ b/crates/verone-engine-container/src/power.rs @@ -25,38 +25,58 @@ pub const ROLE: &str = "power-watcher"; /// `VERONE_PROC` and `VERONE_ONCE` exist for the unit tests only. pub const SCRIPT: &str = r#"PHONES="$1"; shift; VERSIONS=" $* " PROC="${VERONE_PROC:-/proc}" +# Verdicts for processes that start a process namespace: " =yes|no ". known=" " +# The processes of the phones being watched. +phones="" log() { echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) $*"; } prop() { nsenter -t "$1" -m -u -i -n -p -r -w /system/bin/getprop "$2" 2>/dev/null; } -log "watching phones in $PHONES with Android$VERSIONS" -while :; do + +# Looks through every process for phones. Run every 10 seconds, because reading +# every process each second costs a fifth of a processor core. +scan() { + phones="" for status in "$PROC"/[0-9]*/status; do pid=${status%/status}; pid=${pid##*/} - case "$known" in *" $pid=no "*) continue ;; esac - case "$known" in *" $pid=yes "*) ;; *) - # A phone is the first process of its own process namespace... - first=no - while read -r key outer inner deeper; do - if [ "$key" = "NSpid:" ]; then - [ "$inner" = 1 ] && [ -z "$deeper" ] && first=yes - break - fi - done < "$status" 2>/dev/null - [ "$first" = yes ] || continue - # ...whose /data is //data, and whose Android version - # is one the watcher acts on. - root=$(awk '$5 == "/data" { print $4; exit }' "$PROC/$pid/mountinfo" 2>/dev/null) - id=${root%/data}; id=${id##*/} - verdict=no - case "$root" in */phones/*/data) - case "$PHONES/$id/data" in *"$root") - case "$VERSIONS" in *" $(prop "$pid" ro.build.version.release) "*) verdict=yes ;; esac ;; - esac ;; - esac - known="$known$pid=$verdict " - [ "$verdict" = yes ] || continue - log "watching phone $id (process $pid)" ;; + case "$known" in + *" $pid=no "*) continue ;; + *" $pid=yes "*) phones="$phones $pid"; continue ;; esac + # A phone is the first process of its own process namespace... + first=no + while read -r key outer inner deeper; do + if [ "$key" = "NSpid:" ]; then + [ "$inner" = 1 ] && [ -z "$deeper" ] && first=yes + break + fi + done 2>/dev/null < "$status" + [ "$first" = yes ] || continue + # ...whose /data is //data, and whose Android version is + # one the watcher acts on. + root=$(awk '$5 == "/data" { print $4; exit }' "$PROC/$pid/mountinfo" 2>/dev/null) + id=${root%/data}; id=${id##*/} + verdict=no + case "$root" in */phones/*/data) + case "$PHONES/$id/data" in *"$root") + case "$VERSIONS" in *" $(prop "$pid" ro.build.version.release) "*) verdict=yes ;; esac ;; + esac ;; + esac + known="$known$pid=$verdict " + [ "$verdict" = yes ] || continue + phones="$phones $pid" + log "watching phone $id (process $pid)" + done +} + +log "watching phones in $PHONES with Android$VERSIONS" +tick=0 +while :; do + # Look for phones every 10 seconds, and at once when a watched one has ended. + rescan=no + [ $((tick % 10)) -eq 0 ] && rescan=yes + for pid in $phones; do [ -d "$PROC/$pid" ] || rescan=yes; done + [ "$rescan" = yes ] && scan + for pid in $phones; do request=$(prop "$pid" sys.powerctl) case "$request" in reboot*) action=reboot ;; @@ -68,6 +88,7 @@ while :; do nsenter -t "$pid" -p "$action" -f || log "could not $action process $pid" done [ -n "$VERONE_ONCE" ] && exit 0 + tick=$((tick + 1)) sleep 1 done "#; diff --git a/docs/assumptions.md b/docs/assumptions.md index bbe2cf0..c57f058 100644 --- a/docs/assumptions.md +++ b/docs/assumptions.md @@ -295,8 +295,11 @@ owner trimmed the system journal; `/` had 1.4 GB free afterwards. - Cause, as far as found: the kernel log shows init receiving the request ("Got shutdown_command 'reboot,shell' Calling HandlePowerctlMessage()") and then logging nothing more; it never starts shutting down. The deeper reason inside - Android 12's init was not found. A fix that does not depend on it is designed in - `design/android-12-power.md`. + Android 12's init was not found. Fixed without it by the power watcher (D-017, + `design/android-12-power.md`), tested 2026-11-17: restart from inside brought the + phone back in 6.2 s, `verone stop` took 1.2 s with exit code 130. The watcher's + cost over 10 minutes with one Android 12 phone: 1.7% of one core on average (peaks + up to 26% while it looks for phones every 10 s) and at most 3 MB of memory. **A-21 partial.** 2026-11-16: the owner's phone, a vivo V2027, connected over USB with USB debugging and was reached by `adb` without problems. It runs **Android 12** (API From b800ab08808596e0053f2f3f6aeeb540daece1d8 Mon Sep 17 00:00:00 2001 From: axoineo Date: Tue, 17 Nov 2026 18:49:51 +0530 Subject: [PATCH 7/7] Document the Android 12 power watcher (P12-05) User guide, SECURITY.md, architecture, benchmark notes, changelog and the design's results. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++++++-- SECURITY.md | 8 +++++++ docs/architecture.md | 11 +++++++++ docs/benchmark.md | 7 +++--- docs/design/android-12-power.md | 41 +++++++++++++++++++++++---------- docs/user-guide/cli.md | 8 ++++--- 6 files changed, 66 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 255c514..b9f6eac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,10 +13,17 @@ All notable changes to Verone are recorded here. The format follows colour unless `NO_COLOR` is set. Piped or redirected output is unchanged. - Android 12 phones: `verone create NAME --android 12`, using `redroid/redroid:12.0.0-latest` pinned by digest. Android 14 stays the default. - Known limit: on Android 12, "Restart" and "Power off" inside Android do nothing, and - `verone stop` forces the phone off after 20 seconds. + Android 12 ignores "Restart" and "Power off" chosen inside it, so Verone runs a + small helper container, `verone-power-`, while an Android 12 phone exists; it + carries those requests out (decision D-017). `verone doctor` reports it. - The phone fidelity benchmark design, in `docs/benchmark.md` (decision D-016). +### Fixed + +- `verone open` showed no window: scrcpy asks for Opus audio, which the Android + images cannot encode, and then gave up. Verone now asks for uncompressed audio + unless you pass your own audio option after `--`. + ## [0.1.0] - 2026-11-15 First release: a command-line tool that runs Android 14 phones on Linux with Docker. diff --git a/SECURITY.md b/SECURITY.md index 91ffa4d..499b83e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -15,6 +15,14 @@ virtual-machine engine with real isolation is planned for that purpose. hardware-backed keys, strict SELinux) are absent or weakened. A security result observed in Verone does not automatically hold on a real phone, in either direction. +**Android 12 phones bring one more privileged helper.** While an Android 12 phone +exists, Verone runs a small container named `verone-power-` that can see and +enter every process on the computer, so it can restart or power off Android 12 phones +when asked from inside (Android 12 ignores those requests itself). It has no network +and a read-only file system, runs a fixed script from Verone's source, and only acts on +Verone's own Android 12 phones. It is removed when the last Android 12 phone is +deleted. Its log is `docker logs verone-power-`. + **Anyone who can use Docker controls your phones.** Membership of the `docker` group is equivalent to administrator rights on the computer, and that includes every phone's data. diff --git a/docs/architecture.md b/docs/architecture.md index add22b3..97f1b91 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -96,6 +96,17 @@ image `redroid/redroid:14.0.0-latest`): - The stock image is a `userdebug` build with test keys, an old-style launcher and no setup wizard. A phone-like first boot needs image work (Phases 3 and 5). +Android 12 (`redroid/redroid:12.0.0-latest`, added 2026-11-16 for the benchmark, +assumption A-22) boots in about 5 s but ignores restart and power-off requests made +inside Android. The **power watcher** (decision D-017, +`design/android-12-power.md`) fills that gap: one helper container per Verone data +folder, `verone-power-`, running a fixed busybox script from +`crates/verone-engine-container/src/power.rs`. It sees the host's processes, finds +Verone's Android 12 phones by their `/data` mount, and turns a pending request into the +real `reboot` system call, so the container ends with 129 or 130 as Android 14 does. +It is created by `verone start` of an Android 12 phone and removed with the last one. +Images that need it are marked `power_watcher: true` in `images.rs`. + From the redroid documentation (not yet tested here): - Images exist for Android 8.1 through 16. diff --git a/docs/benchmark.md b/docs/benchmark.md index 8e7088d..0f75a71 100644 --- a/docs/benchmark.md +++ b/docs/benchmark.md @@ -56,9 +56,10 @@ to run the benchmark in two sets: Notes: - **Verone in set A** uses Android 12 support added on 2026-11-16 with the owner's - approval (`crates/verone-engine-container/src/images.rs`, assumption A-22). It is - expected to fail B1-03 and B1-04 on Android 12 until the restart problem in A-22 is - fixed, and the report must say so. + approval (`crates/verone-engine-container/src/images.rs`, assumption A-22). Restart + and power-off inside Android 12 work through the power watcher (D-017). Plain + redroid 12 has no watcher and is expected to fail B1-03 and B1-04. Verone's power-off + is abrupt rather than clean, which the report must state against B1-04. - Waydroid offers LineageOS images (Android 11 and 13 at the time of writing; to be confirmed in A-19), not Android 12. It is in set B only, with its version recorded. - The headline numbers in the README come from set A. Set B is published beside it. diff --git a/docs/design/android-12-power.md b/docs/design/android-12-power.md index dbf2e17..ef96af1 100644 --- a/docs/design/android-12-power.md +++ b/docs/design/android-12-power.md @@ -1,6 +1,6 @@ # Restart and power-off on Android 12 -Status: **accepted** (2026-11-17, decision D-017). Being built: tasks P12-01 to P12-05. +Status: **accepted and built** (2026-11-17, decision D-017). Tasks P12-01 to P12-05 are done; results under "Results". ## The problem @@ -53,23 +53,27 @@ All on 2026-11-17, owner's laptop, phone `bench12` (Android 12) created with Ver ### What runs -One container per computer, named `verone-power`: +One container per Verone data folder, named `verone-power-`, where `` is +8 hex digits derived from the phones folder. Normally there is one. Tests run phones +from temporary folders; with a single shared name, a test run would replace the +watcher of the user's own phones. - Image: Verone's helper image (`HELPER_IMAGE`, alpine pinned by digest). No new download. - Options: `--privileged --pid=host --network none --read-only --restart unless-stopped`, label `io.verone.role=power-watcher`. - Command: a short shell script kept in the Verone source and passed to the container - at creation. Once a second it: - 1. Finds Verone phones: processes that are the first process of their own process + at creation. It works in two rhythms: + 1. Every 10 seconds, and at once when a watched phone's process has ended, it finds + Verone phones: processes that are the first process of their own process namespace, and whose mount table contains Verone's phone data folder (`…/verone/phones//data` mounted on `/data`). This matches Verone's phones and nothing else, including other redroid containers the user runs. - 2. Reads `sys.powerctl` in each one with `nsenter … /system/bin/getprop`. + 2. Every second, it reads `sys.powerctl` in each phone found with `nsenter … /system/bin/getprop`. 3. If it starts with `reboot`: runs `sync` inside the phone, then `nsenter -t -p reboot -f`. If it starts with `shutdown`: `sync`, then `nsenter -t -p poweroff -f`. - 4. Writes one line per action to its log (`docker logs verone-power`): time, phone, + 4. Writes one line per action to its log (`docker logs verone-power-`): time, phone, request. ### Which phones it acts on @@ -82,17 +86,20 @@ Android 14 phones are never touched, so their tested behaviour does not change. ### Lifecycle -- `verone start` of a phone that needs it: create and start `verone-power` if it is +- `verone start` of a phone that needs it: create and start the watcher if it is not running. -- `verone delete` of the last phone that needs it: remove `verone-power`. +- `verone delete` of the last phone that needs it: remove the watcher. - `verone doctor`: shows whether the watcher is running when an Android 12 phone exists. - `verone stop` is unchanged: restart policy off, power-off request, wait up to 20 s, kill as a last resort. With the watcher it ends in about 2 s with code 130. ### What it costs -- A busybox shell that wakes once a second and reads a few `/proc` files: well under - 1% of one core and a few MB of memory. To be measured in task P12-04. +- Measured in task P12-04 (see "Results"): 1.7% of one core on average and at most + 3 MB of memory. The first version looked through every process every second and + used 21%; finding phones only every 10 seconds brought it down. Most of what is left + is starting Android's `getprop` once a second per phone. Reading Android's property + file directly could lower it further; not tried yet. - No new download, no new dependency. ### Honest limits @@ -105,7 +112,7 @@ Android 14 phones are never touched, so their tested behaviour does not change. - **Power off inside Android turns the phone back on**, as on Android 14 today, because Docker's restart policy brings back any phone that ends while it is on. This is the existing known limit, not a new one. -- **Security.** `verone-power` can see and enter every process on the computer, like +- **Security.** The watcher can see and enter every process on the computer, like the phones themselves (privileged containers already give root on the host). It has no network, a read-only file system and a fixed script. `SECURITY.md` must list it. @@ -116,7 +123,17 @@ One commit per task; one pull request for all of them. | ID | Task | Acceptance test | |---|---|---| | P12-01 | Add `power_watcher` to `Image` (true for 12, false for 14) and the watcher script as a constant, with unit tests for the script text and the phone matching rule. | `cargo test` passes; the script is shown in the test output for review. | -| P12-02 | Start, check and remove `verone-power` from the container engine as described in "Lifecycle". | Unit tests with the stub runtime cover start when missing, no second copy, removal after the last Android 12 phone is deleted. | +| P12-02 | Start, check and remove the watcher from the container engine as described in "Lifecycle". | Unit tests with the stub runtime cover start when missing, no second copy, removal after the last Android 12 phone is deleted. | | P12-03 | Integration test on a real Android 12 phone: restart from inside, power-off through `verone stop`. | Restart: the phone is booted again within 30 s with a marker file intact. Stop: finishes within 5 s with exit code 130. Android 14 phone in the same run: behaviour unchanged. | | P12-04 | Measure the watcher's CPU and memory over 10 minutes with one Android 12 phone. | Numbers recorded in `assumptions.md`. | | P12-05 | Docs: user guide known limits, `SECURITY.md`, `architecture.md`, changelog. | The owner has read the changes. | + +## Results + +Owner's laptop (4 cores, 7.6 GB RAM), 2026-11-17. + +| Task | Result | +|---|---| +| P12-01, P12-02 | Unit tests pass: the matching rule (only Verone's Android 12 phones, never Android 14, other redroid containers or processes inside a phone), start before the phone, no second copy, removal with the last Android 12 phone, `verone doctor` line. | +| P12-03 | Real Android 12 phone: back 6.2 s after a restart request inside Android, with a file kept; `verone stop` in 1.2 s with exit code 130; watcher removed with the phone. The Android 14 tests in the same run passed. The adb port test failed for the known, unrelated reason (`xt_tcpudp` not loaded). | +| P12-04 | 10 minutes, one Android 12 phone, sampled every 10 s: CPU 1.7% of one core on average, short peaks up to 26% during the scan every 10 s; memory at most 3 MB; nothing written to the log apart from start-up lines. | diff --git a/docs/user-guide/cli.md b/docs/user-guide/cli.md index 16270d3..ec65a0e 100644 --- a/docs/user-guide/cli.md +++ b/docs/user-guide/cli.md @@ -142,9 +142,11 @@ Docker. - **"Power off" inside Android turns the phone back on.** Use `verone stop`. - **No Google apps or Play Store.** Install apps from APK files. - **Android 14 and 12 only, x86-64 computers, Docker only.** -- **Android 12: "Restart" and "Power off" inside Android do nothing.** The phone keeps - running. Use `verone restart` or `verone stop`. On Android 12 `verone stop` takes about 20 seconds - and ends by forcing the phone off; your files were kept in tests. +- **Android 12 needs a helper to restart and power off.** Android 12 ignores "Restart" + and "Power off" chosen inside it. While an Android 12 phone exists, Verone runs a + small helper container, `verone-power-`, that carries the request out. It is + not a clean shutdown: files are saved to disk, then the phone ends at once, without + Android telling its apps first. `verone doctor` shows whether the helper runs. - **No sound has been verified.** scrcpy forwards audio on Android 11 and later, but it has not been tested with Verone. - **Phone data is not encrypted.** See [SECURITY.md](../../SECURITY.md).