Skip to content

A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.

Rust

Add a verified Android scan worker benchmark (#77)

Vishnu Srivatsavaa72373f0acaf
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index abb3b64..8102d15 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -76,9 +76,9 @@ jobs:
- name: Lint frontend and fixtures
run: npm run lint
- - name: Test transfer benchmark offline on Windows
+ - name: Test benchmark tools offline on Windows
if: runner.os == 'Windows'
- run: python -m unittest discover -s tests -p test_transfer_benchmark.py -v
+ run: python -m unittest discover -s tests -p 'test_*benchmark.py' -v
- name: Test daemon protocol on host
if: runner.os != 'Windows'
diff --git a/README.md b/README.md
index 1817212..14d9bce 100644
--- a/README.md
+++ b/README.md
@@ -257,6 +257,10 @@ and does not keep directory descriptors open. Root and `--read-only` scans
remain serial, retaining their exclusions and scan-wide inode deduplication.
The authenticated protocol and deletion checks apply to every worker setting.
+For a controlled phone experiment across 1, 2, 4 and 8 workers, see
+[the verified scan benchmark](docs/scan-benchmark.md). It checks matching trees
+and reports scan/stream medians without changing the app's default.
+
The app uses scan stream v1 (advertised alongside protocol v3): bounded JSON
frames arrive during traversal, with partial counts/recent entries and a cancel
button. Successful results require verified totals, a terminal completion frame
diff --git a/docs/scan-benchmark.md b/docs/scan-benchmark.md
new file mode 100644
index 0000000..143ccaf
--- /dev/null
+++ b/docs/scan-benchmark.md
@@ -0,0 +1,98 @@
+# Android scan worker benchmark
+
+Ordinary scans already use four C++ workers. Compare worker counts on the same
+phone before changing that default or replacing traversal. This developer tool
+does not change the app's behavior and makes no speedup claim.
+
+## Run manually
+
+Use the development prerequisites in the README, including a current ARM64
+Android daemon at `src-tauri/bin/daemon` and the bundled host ADB. Stop any active
+app scan, connect and authorize the phone, and run from the repository root:
+
+```sh
+python3 tests/benchmark_device_scan.py --serial YOUR_DEVICE_SERIAL
+```
+
+On Windows, use `python`. An explicit serial is mandatory; another device is
+never selected as a fallback. The default root is `/sdcard`. To use a quieter
+existing directory, append `--root /sdcard/Download`. `--adb` and `--daemon`
+accept explicit executable/artifact paths. `--output` selects a new directory
+whose parent must exist; existing directories are refused.
+
+Keep the phone awake, temperature and power conditions stable, and storage
+unchanged. Pause downloads, camera use and other writers. The experiment takes
+several minutes for a large tree. Its first run also compiles an optimized Rust
+test executable; it does not open the app. Root/read-only sessions are refused
+because that traversal is serial. The tool does not root/unroot the phone,
+restart ADB, drop caches or modify scanned files.
+
+## What the experiment verifies
+
+The wrapper snapshots the local daemon and records its SHA-256. Four independent
+owned sessions use those same bytes, one each for 1, 2, 4 and 8 workers. They scan
+sequentially; the other daemons are idle. One warm-up per mode precedes five
+measured rounds with mixed order:
+
+```text
+1 4 2 8
+8 2 4 1
+2 1 8 4
+4 8 1 2
+1 8 2 4
+```
+
+All 24 scans pass through the application's authenticated stream decoder,
+including completion totals, byte counts and terminal EOF checks. Each scan
+must report the requested worker count. Exact paths, entry types, sizes,
+counted flags, totals, errors and skipped counts must match the first warm-up.
+Arrival order and internal node IDs may differ. A changed tree invalidates the
+experiment; choose a quiet folder and retry. Matching nonzero errors/skipped
+counts describe matching partial coverage, not complete access to the device.
+This is metadata equality, not a file-content hash comparison.
+
+The report contains individual runs and medians of the five measured runs:
+
+- `scan_ms`: daemon-reported scan time, including its existing streaming timing
+ semantics. Serialize/send phases overlap traversal and must not be added.
+- `stream_wall_ms`: host time from TCP connection through authenticated command,
+ strict decoding and terminal EOF. It excludes daemon/session startup, the GUI,
+ and the app's catalog/index construction.
+- `snapshot_ms`: host metadata canonicalization after the timed stream. This
+ comparison work does not count toward `stream_wall_ms`.
+
+This is a warmed, current-binary scaling experiment. It cannot establish cold
+cache performance, explain old versus new build regressions, or reproduce the
+full GUI scan duration. Compare both scan and stream medians, review variation
+across individual runs, and repeat before making a worker-default change.
+
+## Results and cleanup
+
+The tool prints its result directory and a median table. Share `result.json`
+after reviewing it. It includes the selected root, device model, Android SDK,
+host OS/architecture, ADB version and daemon hash. It excludes the device serial,
+authentication tokens and enumerated filenames. Exact trees exist only in host
+memory during comparison. `trials.jsonl` is an incremental journal;
+`measurements.json` is an intermediate report. Neither substitutes for the final
+verified `result.json`, which is created only after successful cleanup.
+
+Press Ctrl+C once to cancel and wait for cleanup. The wrapper closes a private
+pipe; Rust interrupts its active scan socket and uses normal owned-session
+cleanup. Failure also attempts cleanup for every started session. No process
+name kill, shared-path deletion or foreign-forward removal is used. If the
+phone disconnects, ADB fails or the cleanup deadline expires, private session
+resources may remain and the tool reports failure. A forced second interruption
+can also prevent cleanup. Do not interpret partial output as a valid comparison.
+
+## Offline validation
+
+```sh
+python3 -m unittest discover -s tests -p 'test_*benchmark.py' -v
+cargo test --locked --manifest-path src-tauri/Cargo.toml --lib
+```
+
+Normal tests and CI never contact a phone. Python tests mock Cargo. Rust tests
+exercise comparison/cancellation and, on non-root Unix hosts, fake ADB with a
+real host-built daemon, checking successful and failed experiment cleanup.
+The live experiment is an ignored Rust test requiring explicit environment
+opt-in; invoke it through the wrapper, not by running all ignored tests.
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index af05bbc..9ab2d7c 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -17,6 +17,8 @@ use std::io::{Read, Write};
use std::net::{Shutdown, TcpStream};
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
use tauri::ipc::Channel;
+#[cfg(test)]
+mod scan_benchmark;
mod scan_stream;
mod scan_store;
mod session;
diff --git a/src-tauri/src/scan_benchmark.rs b/src-tauri/src/scan_benchmark.rs
new file mode 100644
index 0000000..9c0bb24
--- /dev/null
+++ b/src-tauri/src/scan_benchmark.rs
@@ -0,0 +1,447 @@
+//! Opt-in device experiment. Uses the real session/decoder, never the GUI.
+use crate::{scan_stream, session, TCP_CONNECT_TIMEOUT, TCP_READ_TIMEOUT};
+use serde_json::{json, Value};
+use std::collections::BTreeMap;
+use std::io::{Read, Write};
+use std::net::{Shutdown, TcpStream};
+use std::path::PathBuf;
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc, Mutex,
+};
+use std::time::Instant;
+
+const MODES: [u8; 4] = [1, 2, 4, 8];
+const ORDER: [[u8; 4]; 5] = [
+ [1, 4, 2, 8],
+ [8, 2, 4, 1],
+ [2, 1, 8, 4],
+ [4, 8, 1, 2],
+ [1, 8, 2, 4],
+];
+type Snapshot = BTreeMap<String, (u8, u64, bool)>;
+
+#[derive(Default)]
+pub(super) struct Cancellation {
+ cancelled: AtomicBool,
+ socket: Mutex<Option<TcpStream>>,
+}
+impl Cancellation {
+ fn check(&self) -> Result<(), String> {
+ if self.cancelled.load(Ordering::SeqCst) {
+ Err("Benchmark cancelled".into())
+ } else {
+ Ok(())
+ }
+ }
+ fn cancel(&self) {
+ self.cancelled.store(true, Ordering::SeqCst);
+ if let Ok(socket) = self.socket.lock() {
+ if let Some(socket) = socket.as_ref() {
+ let _ = socket.shutdown(Shutdown::Both);
+ }
+ }
+ }
+}
+
+fn snapshot(response: &scan_stream::Response) -> Snapshot {
+ let mut directories = BTreeMap::<u32, String>::new();
+ let mut entries = BTreeMap::new();
+ for (id, node) in response.nodes.iter().enumerate() {
+ let path = if node.parent == scan_stream::NONE {
+ response.root.clone()
+ } else {
+ let parent = &directories[&node.parent];
+ format!("{}/{}", parent.trim_end_matches('/'), node.name)
+ };
+ let kind = match node.kind {
+ scan_stream::Kind::Directory => 0,
+ scan_stream::Kind::File => 1,
+ scan_stream::Kind::Other => 2,
+ };
+ if kind == 0 {
+ directories.insert(id as u32, path.clone());
+ }
+ entries.insert(path, (kind, node.size, node.counted));
+ }
+ entries
+}
+
+fn measure(
+ connection: &session::Connection,
+ root: &str,
+ workers: u8,
+ cancel: &Cancellation,
+) -> Result<(Value, Snapshot), String> {
+ cancel.check()?;
+ if connection.read_only {
+ return Err("Benchmark requires a non-root ADB shell: root/read-only scans are serial. No automatic unroot is attempted.".into());
+ }
+ let started = Instant::now();
+ let mut socket = TcpStream::connect_timeout(&connection.address, TCP_CONNECT_TIMEOUT)
+ .map_err(|e| e.to_string())?;
+ socket
+ .set_read_timeout(Some(TCP_READ_TIMEOUT))
+ .map_err(|e| e.to_string())?;
+ socket
+ .set_write_timeout(Some(TCP_CONNECT_TIMEOUT))
+ .map_err(|e| e.to_string())?;
+ *cancel
+ .socket
+ .lock()
+ .map_err(|_| "Benchmark cancellation unavailable")? =
+ Some(socket.try_clone().map_err(|e| e.to_string())?);
+ let result = (|| {
+ cancel.check()?;
+ let payload = crate::command_payload(&format!("SCAN_STREAM {root}"), &connection.token)?;
+ socket
+ .write_all(payload.as_bytes())
+ .map_err(|e| e.to_string())?;
+ let response = scan_stream::read(
+ &mut scan_stream::SocketReader::new(&mut socket),
+ false,
+ |_| cancel.check(),
+ )?;
+ let stream_wall_ms = started.elapsed().as_secs_f64() * 1000.0;
+ cancel.check()?;
+ if response.root() != root {
+ return Err("Daemon scanned an unexpected root".into());
+ }
+ let validation = Instant::now();
+ let mut metadata = serde_json::to_value(&response).map_err(|e| e.to_string())?;
+ metadata["root"] = json!(response.root());
+ if metadata["scan_threads"].as_u64() != Some(workers as u64) {
+ return Err(
+ "Daemon did not run the requested worker count; no comparison recorded".into(),
+ );
+ }
+ let tree = snapshot(&response);
+ metadata["stream_wall_ms"] = json!(stream_wall_ms);
+ metadata["snapshot_ms"] = json!(validation.elapsed().as_secs_f64() * 1000.0);
+ Ok((metadata, tree))
+ })();
+ *cancel
+ .socket
+ .lock()
+ .map_err(|_| "Benchmark cancellation unavailable")? = None;
+ result
+}
+
+fn same_scan(
+ reference: &Value,
+ expected: &Snapshot,
+ metadata: &Value,
+ actual: &Snapshot,
+) -> Result<(), String> {
+ for field in [
+ "root",
+ "total_files",
+ "total_dirs",
+ "total_size",
+ "errors",
+ "skipped",
+ "read_only",
+ ] {
+ if reference[field] != metadata[field] {
+ return Err(format!("Scan {field} changed; results are not comparable. Choose a quiet folder and retry."));
+ }
+ }
+ if expected != actual {
+ return Err("Scanned paths, types, sizes or counted flags changed; results are not comparable. Choose a quiet folder and retry.".into());
+ }
+ Ok(())
+}
+
+fn median(values: &mut [f64]) -> f64 {
+ values.sort_by(f64::total_cmp);
+ let middle = values.len() / 2;
+ if values.len() % 2 == 0 {
+ (values[middle - 1] + values[middle]) / 2.0
+ } else {
+ values[middle]
+ }
+}
+
+pub(super) fn run(
+ adb: PathBuf,
+ daemon: PathBuf,
+ serial: String,
+ root: &str,
+ output: &std::path::Path,
+ cancel: &Cancellation,
+) -> Result<Value, String> {
+ if root.is_empty()
+ || !root.starts_with('/')
+ || root.contains(['\n', '\r', '\0'])
+ || root.len() + "SCAN_STREAM ".len() > crate::MAX_COMMAND_BYTES
+ {
+ return Err(
+ "Use an absolute scan path without line breaks, within the command limit".into(),
+ );
+ }
+ cancel.check()?;
+ crate::devices::require_selected(&adb, &serial)?;
+ let targeted = |args: &[&str]| {
+ let mut selected = vec!["-s", &serial];
+ selected.extend_from_slice(args);
+ crate::adb(&adb, &selected)
+ };
+ let model = targeted(&["shell", "getprop ro.product.model"])?;
+ let android_sdk = targeted(&["shell", "getprop ro.build.version.sdk"])?;
+ let version = crate::adb(&adb, &["version"])?;
+ let mut sessions = BTreeMap::new();
+ let outcome = (|| {
+ for workers in MODES {
+ cancel.check()?;
+ eprintln!("Preparing {workers}-worker session...");
+ let (session, _) =
+ session::Session::start_benchmark(adb.clone(), &daemon, serial.clone(), workers)?;
+ if session.connection().read_only {
+ return Err("Benchmark requires a non-root ADB shell; root scans cannot compare parallel workers".into());
+ }
+ sessions.insert(workers, session);
+ }
+ let mut journal = std::fs::OpenOptions::new()
+ .create_new(true)
+ .write(true)
+ .open(output.join("trials.jsonl"))
+ .map_err(|e| e.to_string())?;
+ let mut reference = None;
+ let mut rows = Vec::new();
+ for (warmup, order) in
+ std::iter::once((true, MODES)).chain(ORDER.into_iter().map(|order| (false, order)))
+ {
+ for workers in order {
+ cancel.check()?;
+ eprintln!(
+ "{}: {workers} workers",
+ if warmup { "Warm-up" } else { "Measured scan" }
+ );
+ let (mut metadata, tree) =
+ measure(&sessions[&workers].connection(), root, workers, cancel)?;
+ if let Some((stats, snapshot)) = &reference {
+ same_scan(stats, snapshot, &metadata, &tree)?;
+ } else {
+ reference = Some((metadata.clone(), tree));
+ }
+ metadata["warmup"] = json!(warmup);
+ metadata["order"] = json!(rows.len() + 1);
+ serde_json::to_writer(&mut journal, &metadata).map_err(|e| e.to_string())?;
+ writeln!(journal).map_err(|e| e.to_string())?;
+ journal.flush().map_err(|e| e.to_string())?;
+ eprintln!(
+ " scan {} ms; stream round-trip {:.1} ms",
+ metadata["scan_time_ms"],
+ metadata["stream_wall_ms"].as_f64().unwrap()
+ );
+ rows.push(metadata);
+ }
+ }
+ let mut medians = Vec::new();
+ for workers in MODES {
+ let samples: Vec<_> = rows
+ .iter()
+ .filter(|row| row["warmup"] == false && row["scan_threads"] == workers)
+ .collect();
+ let mut daemon: Vec<_> = samples
+ .iter()
+ .map(|row| row["scan_time_ms"].as_f64().unwrap())
+ .collect();
+ let mut wall: Vec<_> = samples
+ .iter()
+ .map(|row| row["stream_wall_ms"].as_f64().unwrap())
+ .collect();
+ medians.push(json!({"workers":workers,"samples":samples.len(),"scan_ms":median(&mut daemon),"stream_wall_ms":median(&mut wall)}));
+ }
+ Ok(
+ json!({"verified":true,"root":root,"device_model":model.trim(),"android_sdk":android_sdk.trim(),
+ "adb_version":version.lines().take(2).collect::<Vec<_>>(),"host_os":std::env::consts::OS,"host_arch":std::env::consts::ARCH,
+ "warmups_per_mode":1,"measured_runs_per_mode":5,"medians":medians,"runs":rows}),
+ )
+ })();
+ let mut cleanup = Vec::new();
+ for session in sessions.values_mut() {
+ cleanup.extend(session.cleanup());
+ }
+ if !cleanup.is_empty() {
+ return Err(format!(
+ "Session cleanup incomplete: {}. Benchmark result: {}",
+ cleanup.join("; "),
+ if outcome.is_ok() {
+ "measurements completed"
+ } else {
+ "failed"
+ }
+ ));
+ }
+ outcome
+}
+
+#[test]
+#[ignore = "Live Android experiment: invoke through tests/benchmark_device_scan.py only"]
+fn connected_device() {
+ assert_eq!(
+ std::env::var("SOCKETSWEEP_DEVICE_BENCH").as_deref(),
+ Ok("1"),
+ "Use tests/benchmark_device_scan.py; this test contacts a real device"
+ );
+ let env = |name| std::env::var(name).unwrap_or_else(|_| panic!("Missing {name}"));
+ let cancel = Arc::new(Cancellation::default());
+ let watcher = cancel.clone();
+ std::thread::spawn(move || {
+ let mut byte = [0];
+ while matches!(std::io::stdin().read(&mut byte), Ok(n) if n > 0) {}
+ watcher.cancel();
+ });
+ let output = PathBuf::from(env("SOCKETSWEEP_BENCH_OUTPUT"));
+ let result = run(
+ PathBuf::from(env("SOCKETSWEEP_BENCH_ADB")),
+ PathBuf::from(env("SOCKETSWEEP_BENCH_DAEMON")),
+ env("SOCKETSWEEP_BENCH_SERIAL"),
+ &env("SOCKETSWEEP_BENCH_ROOT"),
+ &output,
+ &cancel,
+ )
+ .unwrap_or_else(|e| panic!("Benchmark failed: {e}"));
+ let mut file = std::fs::OpenOptions::new()
+ .create_new(true)
+ .write(true)
+ .open(output.join("measurements.json"))
+ .unwrap();
+ serde_json::to_writer_pretty(&mut file, &result).unwrap();
+ writeln!(file).unwrap();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Cursor;
+ use std::net::TcpListener;
+ use std::time::Duration;
+
+ fn frame(value: Value) -> Vec<u8> {
+ let bytes = serde_json::to_vec(&value).unwrap();
+ let mut result = (bytes.len() as u32).to_be_bytes().to_vec();
+ result.extend(bytes);
+ result
+ }
+
+ fn fixture(reversed: bool) -> Vec<u8> {
+ let mut entries = vec![
+ json!({"id":0,"parent":null,"name":"fixture","kind":"directory","size":0,"counted":true}),
+ ];
+ let dir =
+ json!({"id":1,"parent":0,"name":"nested","kind":"directory","size":0,"counted":true});
+ let a =
+ json!({"id":2,"parent":1,"name":"exact ü name","kind":"file","size":7,"counted":true});
+ let b = json!({"id":3,"parent":0,"name":"other","kind":"file","size":5,"counted":true});
+ if reversed {
+ let (mut dir, mut a, mut b) = (dir, a, b);
+ b["id"] = json!(1);
+ dir["id"] = json!(2);
+ a["id"] = json!(3);
+ a["parent"] = json!(2);
+ entries.extend([b, dir, a]);
+ } else {
+ entries.extend([dir, a, b]);
+ }
+ let mut bytes = frame(
+ json!({"type":"started","data":{"stream_version":1,"root":"/fixture","read_only":false}}),
+ );
+ bytes.extend(frame(json!({"type":"entries","data":{"entries":entries}})));
+ bytes.extend(frame(json!({"type":"done","data":{"total_files":2,"total_dirs":2,"total_size":12,
+ "errors":0,"skipped":0,"scan_time_ms":1,"scan_threads":4,"serialize_ms":0,"send_ms":0,"bytes_sent":bytes.len()}})));
+ bytes
+ }
+
+ #[test]
+ fn comparison_preserves_exact_tree_independent_of_parallel_arrival_order() {
+ let parse =
+ |order| scan_stream::read(&mut Cursor::new(fixture(order)), false, |_| Ok(())).unwrap();
+ let expected = snapshot(&parse(false));
+ let actual = snapshot(&parse(true));
+ assert_eq!(expected, actual);
+ assert!(actual.contains_key("/fixture/nested/exact ü name"));
+ let metadata = serde_json::to_value(parse(false)).unwrap();
+ same_scan(&metadata, &expected, &metadata, &actual).unwrap();
+ for field in [
+ "root",
+ "total_files",
+ "total_dirs",
+ "total_size",
+ "errors",
+ "skipped",
+ "read_only",
+ ] {
+ let mut changed = metadata.clone();
+ changed[field] = json!("changed");
+ assert!(
+ same_scan(&metadata, &expected, &changed, &actual).is_err(),
+ "{field}"
+ );
+ }
+ for replacement in [(1, 6, true), (2, 5, true), (1, 5, false)] {
+ let mut changed = actual.clone();
+ changed.insert("/fixture/other".into(), replacement);
+ assert!(same_scan(&metadata, &expected, &metadata, &changed).is_err());
+ }
+ let mut renamed = actual;
+ renamed.remove("/fixture/other");
+ renamed.insert("/fixture/renamed".into(), (1, 5, true));
+ assert!(same_scan(&metadata, &expected, &metadata, &renamed).is_err());
+ }
+
+ #[test]
+ fn measurement_rejects_wrong_root_and_worker_count() {
+ for (root, workers, expected) in [
+ ("/wrong", 4, "unexpected root"),
+ ("/fixture", 2, "requested worker count"),
+ ] {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let connection = session::Connection {
+ address: listener.local_addr().unwrap(),
+ token: "0".repeat(64),
+ read_only: false,
+ };
+ let server = std::thread::spawn(move || {
+ let (mut socket, _) = listener.accept().unwrap();
+ socket
+ .set_read_timeout(Some(Duration::from_secs(5)))
+ .unwrap();
+ let mut input = std::io::BufReader::new(socket.try_clone().unwrap());
+ let mut command = String::new();
+ for _ in 0..2 {
+ std::io::BufRead::read_line(&mut input, &mut command).unwrap();
+ }
+ socket.write_all(&fixture(false)).unwrap();
+ });
+ let cancel = Cancellation::default();
+ assert!(measure(&connection, root, workers, &cancel)
+ .unwrap_err()
+ .contains(expected));
+ assert!(cancel.socket.lock().unwrap().is_none());
+ server.join().unwrap();
+ }
+ }
+
+ #[test]
+ fn cancellation_closes_active_socket_and_prevents_further_work() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
+ let (_peer, _) = listener.accept().unwrap();
+ client
+ .set_read_timeout(Some(Duration::from_secs(1)))
+ .unwrap();
+ let cancel = Cancellation::default();
+ *cancel.socket.lock().unwrap() = Some(client.try_clone().unwrap());
+ cancel.cancel();
+ assert!(cancel.check().is_err());
+ match client.read(&mut [0]) {
+ Ok(size) => assert_eq!(size, 0),
+ Err(error) => assert!(!matches!(
+ error.kind(),
+ std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock
+ )),
+ }
+ }
+}
diff --git a/src-tauri/src/session.rs b/src-tauri/src/session.rs
index deb1a8c..8e959fc 100644
--- a/src-tauri/src/session.rs
+++ b/src-tauri/src/session.rs
@@ -134,9 +134,32 @@ impl Session {
daemon: &Path,
serial: String,
root_mode: bool,
+ ) -> Result<(Self, String), String> {
+ Self::start_configured(adb, daemon, serial, root_mode, None)
+ }
+
+ #[cfg(test)]
+ pub fn start_benchmark(
+ adb: PathBuf,
+ daemon: &Path,
+ serial: String,
+ workers: u8,
+ ) -> Result<(Self, String), String> {
+ if !(1..=8).contains(&workers) {
+ return Err("Benchmark workers must be between 1 and 8".into());
+ }
+ Self::start_configured(adb, daemon, serial, false, Some(workers))
+ }
+
+ fn start_configured(
+ adb: PathBuf,
+ daemon: &Path,
+ serial: String,
+ root_mode: bool,
+ workers: Option<u8>,
) -> Result<(Self, String), String> {
let mut session = Self::new(adb, serial)?;
- let result = session.start_inner(daemon, root_mode);
+ let result = session.start_inner(daemon, root_mode, workers);
match result {
Ok(response) => Ok((session, response)),
Err(error) => {
@@ -153,7 +176,12 @@ impl Session {
}
}
- fn start_inner(&mut self, daemon: &Path, root_mode: bool) -> Result<String, String> {
+ fn start_inner(
+ &mut self,
+ daemon: &Path,
+ root_mode: bool,
+ workers: Option<u8>,
+ ) -> Result<String, String> {
let deadline = Instant::now() + START_TIMEOUT;
if !supports_shell_v2(&self.adb(&["features"], None, deadline)?) {
return Err("The connected device must support ADB shell v2 for owned sessions".into());
@@ -194,9 +222,12 @@ impl Session {
)?;
let ready_path = format!("{}/ready", self.directory);
let mode = if root_mode { " --read-only" } else { "" };
+ let worker_args = workers
+ .map(|count| format!(" --threads {count}"))
+ .unwrap_or_default();
let launch = device_shell_command(
self.privilege,
- &format!("exec '{executable}' 0 '{token_path}' --session-ready '{ready_path}'{mode}"),
+ &format!("exec '{executable}' 0 '{token_path}' --session-ready '{ready_path}'{mode}{worker_args}"),
);
// Raw shell protocol forwards stdin EOF. No nohup, PTY, token argv,
// inherited terminal input, or unbounded captured daemon diagnostics.
@@ -352,6 +383,16 @@ fn owned_forwards(list: &str, serial: &str, local: u16, remote: u16) -> Vec<Stri
mod tests {
use super::*;
+ #[test]
+ fn benchmark_rejects_invalid_worker_counts_before_launch() {
+ for workers in [0, 9, u8::MAX] {
+ let error = Session::start_benchmark(
+ PathBuf::from("missing-adb"), Path::new("missing-daemon"), "fixture".into(), workers,
+ ).err().unwrap();
+ assert!(error.contains("between 1 and 8"), "{error}");
+ }
+ }
+
#[test]
fn shell_v2_requires_an_exact_feature_line() {
for output in [
@@ -533,6 +574,49 @@ mod tests {
assert!(calls.contains("[\"devices\", \"-l\"]"));
}
+ #[test]
+ fn benchmark_uses_real_streams_requested_workers_and_owned_cleanup() {
+ // A UID-0 host deliberately forces the daemon into serial mode.
+ if Command::new("id").arg("-u").output().unwrap().stdout == b"0\n" {
+ return;
+ }
+ let device = Device::new();
+ let adb = device.client("benchmark", "benchmark-device");
+ let storage = device.root.join("storage");
+ fs::create_dir(&storage).unwrap();
+ fs::write(storage.join("exact ü name"), b"fixture").unwrap();
+ let output = device.root.join("results");
+ fs::create_dir(&output).unwrap();
+ let result = crate::scan_benchmark::run(
+ adb.clone(), daemon().into(), "benchmark-device".into(), storage.to_str().unwrap(),
+ &output, &crate::scan_benchmark::Cancellation::default(),
+ ).unwrap();
+ assert_eq!(result["verified"], true);
+ assert_eq!(result["runs"].as_array().unwrap().len(), 24);
+ for (index, workers) in [1, 2, 4, 8].into_iter().enumerate() {
+ assert_eq!(result["medians"][index]["workers"], workers);
+ assert_eq!(result["medians"][index]["samples"], 5);
+ }
+ let encoded = serde_json::to_string(&result).unwrap();
+ assert!(!encoded.contains("benchmark-device"));
+ assert!(!encoded.contains("exact ü name"));
+ assert_eq!(device.directories(), 0);
+ assert_eq!(device.rows().len(), 1); // only the unrelated mapping
+ assert_eq!(
+ fs::read_to_string(output.join("trials.jsonl")).unwrap().lines().count(), 24,
+ );
+ let failure_output = device.root.join("failed-results");
+ fs::create_dir(&failure_output).unwrap();
+ let missing = storage.join("missing");
+ assert!(crate::scan_benchmark::run(
+ adb, daemon().into(), "benchmark-device".into(), missing.to_str().unwrap(),
+ &failure_output, &crate::scan_benchmark::Cancellation::default(),
+ ).is_err());
+ assert_eq!(device.directories(), 0);
+ assert_eq!(device.rows().len(), 1);
+ assert!(!failure_output.join("measurements.json").exists());
+ }
+
#[test]
fn two_sessions_on_same_or_different_devices_remain_independent() {
for serials in [("same", "same"), ("first", "second")] {
diff --git a/tests/benchmark_device_scan.py b/tests/benchmark_device_scan.py
new file mode 100644
index 0000000..cedc644
--- /dev/null
+++ b/tests/benchmark_device_scan.py
@@ -0,0 +1,114 @@
+#!/usr/bin/env python3
+"""Opt-in Android worker benchmark using the application's Rust session/decoder.
+
+Nothing contacts ADB on import or --help. This script runs the ignored live
+experiment only after explicit serial selection. Offline tests mock Cargo.
+"""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+import tempfile
+
+REPO = Path(__file__).resolve().parents[1]
+TEST = "scan_benchmark::connected_device"
+
+
+def digest(path):
+ result = hashlib.sha256()
+ with path.open("rb") as stream:
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
+ result.update(block)
+ return result.hexdigest()
+
+
+def benchmark(serial, root="/sdcard", output=None, adb=None, daemon=None):
+ if not serial or any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in serial):
+ raise ValueError("Choose an explicit device serial without whitespace/control characters")
+ if not root.startswith("/") or any(c in root for c in "\r\n\0") or len(root.encode()) + len("SCAN_STREAM ") > 16 * 1024:
+ raise ValueError("Choose an absolute scan path without line breaks, within 16 KiB")
+ adb = Path(adb or REPO / "src-tauri/bin" / ("adb.exe" if os.name == "nt" else "adb")).resolve(strict=True)
+ daemon = Path(daemon or REPO / "src-tauri/bin/daemon").resolve(strict=True)
+ if not adb.is_file() or not daemon.is_file():
+ raise ValueError("ADB and daemon must be files")
+ if output is None:
+ output = Path(tempfile.mkdtemp(prefix="socketsweep-scan-benchmark-"))
+ else:
+ output = Path(output).resolve()
+ output.mkdir(mode=0o700) # Never overwrite another experiment.
+ print(f"Results directory: {output}", flush=True)
+ print("Four warm-ups, then five mixed-order scans per worker count. Keep storage unchanged.", flush=True)
+ with tempfile.TemporaryDirectory(prefix="socketsweep-scan-artifact-") as directory:
+ # All four sessions receive the exact same immutable local snapshot,
+ # even if the original build output is replaced during the experiment.
+ snapshot = Path(directory) / "daemon"
+ shutil.copyfile(daemon, snapshot)
+ fingerprint = digest(snapshot)
+ env = os.environ.copy()
+ env.update(SOCKETSWEEP_DEVICE_BENCH="1", SOCKETSWEEP_BENCH_SERIAL=serial,
+ SOCKETSWEEP_BENCH_ROOT=root.rstrip("/") or "/", SOCKETSWEEP_BENCH_ADB=str(adb),
+ SOCKETSWEEP_BENCH_DAEMON=str(snapshot), SOCKETSWEEP_BENCH_OUTPUT=str(output))
+ command = ["cargo", "test", "--release", "--locked", "--manifest-path", str(REPO / "src-tauri/Cargo.toml"),
+ "--lib", TEST, "--", "--ignored", "--exact", "--nocapture"]
+ group = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {"start_new_session": True}
+ process = subprocess.Popen(command, cwd=REPO, env=env, stdin=subprocess.PIPE, **group)
+ try:
+ status = process.wait()
+ except KeyboardInterrupt:
+ # Rust watches this pipe and interrupts its active scan socket.
+ # Shielding Cargo from terminal SIGINT allows owned-session cleanup.
+ process.stdin.close()
+ print("Cancelling; waiting for bounded session cleanup...", file=sys.stderr, flush=True)
+ try:
+ process.wait(timeout=90)
+ except subprocess.TimeoutExpired:
+ process.terminate() # only this wrapper's owned Cargo child
+ try:
+ process.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait()
+ print("Cleanup timed out; private session files/forwards may remain.", file=sys.stderr)
+ raise
+ finally:
+ if not process.stdin.closed:
+ process.stdin.close()
+ if status:
+ raise RuntimeError(f"Experiment failed (Cargo exit {status}). Inspect {output}; no verified result.json was created.")
+ with (output / "measurements.json").open(encoding="utf-8") as stream:
+ report = json.load(stream)
+ if report.get("verified") is not True:
+ raise ValueError("Experiment did not produce verified measurements")
+ report["daemon_sha256"] = fingerprint
+ with (output / "result.json").open("x", encoding="utf-8") as stream:
+ json.dump(report, stream, indent=2, allow_nan=False)
+ stream.write("\n")
+ print("\nWorkers | median scan ms | median stream round-trip ms", flush=True)
+ for row in report["medians"]:
+ print(f"{row['workers']:7} | {row['scan_ms']:14.1f} | {row['stream_wall_ms']:27.1f}", flush=True)
+ print(f"\nShare this file after reviewing it: {output / 'result.json'}", flush=True)
+ return output
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--serial", required=True)
+ parser.add_argument("--root", default="/sdcard", help="Existing directory to scan; keep its contents unchanged")
+ parser.add_argument("--output", type=Path, help="New result directory; parent must exist")
+ parser.add_argument("--adb", type=Path, help="Host ADB executable; defaults to bundled resource")
+ parser.add_argument("--daemon", type=Path, help="Android daemon; defaults to bundled resource")
+ args = parser.parse_args()
+ try:
+ benchmark(args.serial, args.root, args.output, args.adb, args.daemon)
+ except KeyboardInterrupt:
+ parser.exit(130, "Benchmark cancelled; no verified result.json was created.\n")
+ except (OSError, ValueError, RuntimeError) as error:
+ parser.exit(1, f"Benchmark failed: {error}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/fake_session_adb.py b/tests/fake_session_adb.py
index 0eda2b6..4092c24 100644
--- a/tests/fake_session_adb.py
+++ b/tests/fake_session_adb.py
@@ -16,7 +16,7 @@ import time
config = json.loads(Path(sys.argv[1]).read_text())
args = sys.argv[2:]
-if args != ["devices", "-l"]:
+if args not in (["devices", "-l"], ["version"]):
assert args[:2] == ["-s", config["serial"]], args
args = args[2:]
base = Path(config["base"])
@@ -35,7 +35,9 @@ def mapped(command):
return command.replace("/data/local/tmp/", str(Path(config["phone"])) + "/")
-if args == ["devices", "-l"]:
+if args == ["version"]:
+ print("Android Debug Bridge version 1.0.41\nVersion host-fixture")
+elif args == ["devices", "-l"]:
discovery = base / "devices.txt"
print(discovery.read_text() if discovery.exists() else
f'List of devices attached\n{config["serial"]}\tdevice model:Fixture\n')
@@ -50,7 +52,11 @@ elif args[0] == "shell":
elevated = command.startswith("su -c ")
if elevated:
command = shlex.split(command)[2]
- if command == "id -u":
+ if command == "getprop ro.product.model":
+ print("Host fixture")
+ elif command == "getprop ro.build.version.sdk":
+ print("fixture")
+ elif command == "id -u":
print("0" if elevated and failure != "root" else "2000")
elif args[1] == "-T":
fail("launch")
diff --git a/tests/test_device_scan_benchmark.py b/tests/test_device_scan_benchmark.py
new file mode 100644
index 0000000..c0ca833
--- /dev/null
+++ b/tests/test_device_scan_benchmark.py
@@ -0,0 +1,106 @@
+"""Offline wrapper tests: Cargo and ADB are never executed."""
+import hashlib
+import io
+import json
+from pathlib import Path
+import tempfile
+import unittest
+from unittest.mock import patch
+
+import benchmark_device_scan as benchmark
+
+
+class DeviceScanBenchmarkTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.adb = self.root / "fake-adb"
+ self.adb.touch()
+ self.daemon = self.root / "fake-daemon"
+ self.daemon.write_bytes(b"immutable fixture")
+ self.output = self.root / "results"
+
+ def run_benchmark(self, **kwargs):
+ return benchmark.benchmark("explicit-device", output=self.output,
+ adb=self.adb, daemon=self.daemon, **kwargs)
+
+ def test_invalid_inputs_and_existing_output_never_launch(self):
+ with patch.object(benchmark.subprocess, "Popen") as launch:
+ for serial in ("", "with space", "x\n", "x\0"):
+ with self.assertRaises(ValueError):
+ benchmark.benchmark(serial)
+ for root in ("relative", "/x\n", "/x\0", "/" + "ü" * 8192):
+ with self.assertRaises(ValueError):
+ self.run_benchmark(root=root)
+ self.assertFalse(self.output.exists())
+ self.output.mkdir()
+ sentinel = self.output / "keep"
+ sentinel.write_bytes(b"unchanged")
+ with self.assertRaises(FileExistsError):
+ self.run_benchmark()
+ self.assertEqual(sentinel.read_bytes(), b"unchanged")
+ launch.assert_not_called()
+
+ def test_success_uses_release_exact_opt_in_and_immutable_artifact(self):
+ child = None
+
+ def launch(command, **kwargs):
+ nonlocal child
+ self.assertIn("--release", command)
+ self.assertEqual(command[-5:], [benchmark.TEST, "--", "--ignored", "--exact", "--nocapture"])
+ env = kwargs["env"]
+ self.assertEqual(env["SOCKETSWEEP_DEVICE_BENCH"], "1")
+ self.assertEqual(env["SOCKETSWEEP_BENCH_SERIAL"], "explicit-device")
+ self.assertEqual(env["SOCKETSWEEP_BENCH_ROOT"], "/sdcard")
+ artifact = Path(env["SOCKETSWEEP_BENCH_DAEMON"])
+ self.assertNotEqual(artifact, self.daemon)
+ self.assertEqual(artifact.read_bytes(), b"immutable fixture")
+ self.daemon.write_bytes(b"new build")
+ report = {"verified": True, "medians": [{"workers": 1, "scan_ms": 1, "stream_wall_ms": 2}]}
+ (self.output / "measurements.json").write_text(json.dumps(report), encoding="utf-8")
+ from unittest.mock import Mock
+ child = Mock(stdin=io.BytesIO())
+ child.wait.return_value = 0
+ return child
+
+ with patch.object(benchmark.subprocess, "Popen", side_effect=launch):
+ self.run_benchmark(root="/sdcard///")
+ self.assertTrue(child.stdin.closed)
+ result = json.loads((self.output / "result.json").read_text())
+ self.assertEqual(result["daemon_sha256"], hashlib.sha256(b"immutable fixture").hexdigest())
+
+ def test_failed_or_unverified_run_has_no_result(self):
+ from unittest.mock import Mock
+ for status in (1, 0):
+ with self.subTest(status=status):
+ self.output = self.root / f"results-{status}"
+
+ def launch(*args, **kwargs):
+ (self.output / "measurements.json").write_text('{"verified":false}')
+ child = Mock(stdin=io.BytesIO())
+ child.wait.return_value = status
+ return child
+
+ with patch.object(benchmark.subprocess, "Popen", side_effect=launch):
+ with self.assertRaises((ValueError, RuntimeError)):
+ self.run_benchmark()
+ self.assertFalse((self.output / "result.json").exists())
+
+ def test_interrupt_closes_cancellation_pipe_and_waits_for_cleanup(self):
+ from unittest.mock import Mock
+ child = Mock(stdin=io.BytesIO())
+
+ def wait(**kwargs):
+ if not kwargs:
+ raise KeyboardInterrupt
+ self.assertTrue(child.stdin.closed)
+ self.assertEqual(kwargs, {"timeout": 90})
+ return 0
+
+ child.wait.side_effect = wait
+ with patch.object(benchmark.subprocess, "Popen", return_value=child):
+ with self.assertRaises(KeyboardInterrupt):
+ self.run_benchmark()
+ child.terminate.assert_not_called()
+ self.assertFalse((self.output / "result.json").exists())