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 bounded parallel storage traversal with anchored directory reads (#28)
Vishnu Srivatsavaff8b78947e90
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex aa8ddd8..1422d3c 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -92,7 +92,7 @@ jobs:echo "Compiler: $CC""$CC" \- -std=c++17 -O2 -Wall -Wextra -Wpedantic \+ -std=c++17 -O2 -pthread -Wall -Wextra -Wpedantic \-fno-exceptions -fno-rtti -DNDEBUG \-static-libstdc++ \-s \@@ -113,7 +113,7 @@ jobs:Write-Host "Compiler: $CC"& $CC `- -std=c++17 -O2 -Wall -Wextra -Wpedantic `+ -std=c++17 -O2 -pthread -Wall -Wextra -Wpedantic `-fno-exceptions -fno-rtti -DNDEBUG `-static-libstdc++ `-s `diff --git a/README.md b/README.mdindex 55b0fda..c4cdc41 100644--- a/README.md+++ b/README.md@@ -236,6 +236,13 @@ bash ./build.shcopies it into `src-tauri/bin/daemon`, which Tauri bundles. Rebuild after changingthe daemon so local development uses the current protocol (v3).*+Ordinary storage scans use a bounded pool of four workers. For daemon-level+comparisons, append `--threads N` (1–8) after `PORT TOKEN_FILE`; one worker+provides a serial reference. The pending directory queue holds at most 64 jobs+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.+### 2. Install Frontend Dependencies```bashcd ..diff --git a/engine/build.sh b/engine/build.shindex 1a80797..b86d71a 100644--- a/engine/build.sh+++ b/engine/build.sh@@ -43,7 +43,7 @@ OUT="$SCRIPT_DIR/daemon"echo "[build] Compiling daemon.cpp → daemon (aarch64-linux-android) ...""$CC" \- -std=c++17 -O2 -Wall -Wextra -Wpedantic \+ -std=c++17 -O2 -pthread -Wall -Wextra -Wpedantic \-fno-exceptions -fno-rtti -DNDEBUG \-static-libstdc++ \-s \diff --git a/engine/daemon.cpp b/engine/daemon.cppindex 888c287..fb3be04 100644--- a/engine/daemon.cpp+++ b/engine/daemon.cpp@@ -39,6 +39,7 @@ namespace cfg {constexpr int MAX_DEPTH = 64;constexpr int RECV_TIMEOUT_SEC = 30;constexpr size_t MAX_COMMAND_BYTES = 16 * 1024;+ constexpr int DEFAULT_SCAN_THREADS = 4;}// ── Globals ─────────────────────────────────────────────────────────────────@@ -47,6 +48,7 @@ static void on_signal(int) { g_running = 0; }static safe_delete::Root g_scan_root; // pins the successful scan root for deletionstatic std::string g_session_token;static bool g_read_only = false;+static int g_scan_threads = cfg::DEFAULT_SCAN_THREADS;// Per-phase scan timing (see SCAN in handle_client). Counters reset per scan.static int64_t g_sort_ns = 0; // cumulative time sorting directory children@@ -141,6 +143,10 @@ struct FileNode {bool is_dir = false;int64_t size = 0;std::vector<FileNode> children;+ // Only directory entries use these identities. Parallel jobs validate an+ // opened directory before reading it; neither field is sent to the host.+ dev_t device = 0;+ ino_t inode = 0;};struct ScanStats {@@ -303,6 +309,8 @@ static FileNode scan(const std::string& path, const std::string& name,return node;}+#include "parallel_scan.h"+// ── Command dispatch ────────────────────────────────────────────────────────static void handle_client(int fd) {struct timeval tv { cfg::RECV_TIMEOUT_SEC, 0 };@@ -398,7 +406,22 @@ static void handle_client(int fd) {auto t0 = std::chrono::steady_clock::now();ScanStats stats{};- FileNode tree = scan(root, root_name, stats, 0);+ FileNode tree;+ int scan_threads = 1;+ if (g_read_only) {+ // Preserve serial, scan-wide inode deduplication and exclusions.+ tree = scan(root, root_name, stats, 0);+ } else {+ tree.name = root_name;+ tree.path = root;+ tree.is_dir = true;+ tree.device = g_scan_root.identity.st_dev;+ tree.inode = g_scan_root.identity.st_ino;+ const auto result = parallel_scan::run(g_scan_root, tree, stats,+ g_scan_threads, cfg::MAX_DEPTH);+ scan_threads = result.workers;+ g_sort_ns = result.sort_ns;+ }if (!g_scan_root.unchanged()) {g_scan_root.clear();out.write("{\"status\":\"error\",\"message\":\"Scan root changed during scan; scan again\"}\n");@@ -419,6 +442,8 @@ static void handle_client(int fd) {out.write("{\"status\":\"ok\",\"scan_time_ms\":");out.write(std::to_string(ms));+ out.write(",\"scan_threads\":");+ out.write(std::to_string(scan_threads));out.write(",\"total_files\":");out.write(std::to_string(stats.files));out.write(",\"total_dirs\":");@@ -471,12 +496,28 @@ int main(int argc, char* argv[]) {// A shell-owned 0600 file supplies the secret, keeping it out of process// arguments. Consume and unlink it before accepting any connections.- if (argc != 3 && !(argc == 4 && std::strcmp(argv[3], "--read-only") == 0)) {- std::fprintf(stderr, "[engine] Usage: daemon PORT TOKEN_FILE [--read-only]\n");+ bool read_only_requested = false;+ bool threads_requested = false;+ bool valid_args = argc >= 3;+ for (int i = 3; valid_args && i < argc; ++i) {+ if (std::strcmp(argv[i], "--read-only") == 0 && !read_only_requested) {+ read_only_requested = true;+ } else if (std::strcmp(argv[i], "--threads") == 0 && !threads_requested && i + 1 < argc) {+ threads_requested = true;+ const std::string value = argv[++i];+ valid_args = value.size() == 1 && value[0] >= '1' &&+ value[0] <= '0' + parallel_scan::MAX_WORKERS;+ if (valid_args) g_scan_threads = value[0] - '0';+ } else {+ valid_args = false;+ }+ }+ if (!valid_args) {+ std::fprintf(stderr, "[engine] Usage: daemon PORT TOKEN_FILE [--read-only] [--threads 1..8]\n");return 1;}// Even an already-root ADB shell using the default launch cannot delete.- g_read_only = argc == 4 || ::geteuid() == 0;+ g_read_only = read_only_requested || ::geteuid() == 0;{std::ifstream token_file(argv[2]);std::getline(token_file, g_session_token);diff --git a/engine/parallel_scan.h b/engine/parallel_scan.hnew file mode 100644index 0000000..5ec9b78--- /dev/null+++ b/engine/parallel_scan.h@@ -0,0 +1,219 @@+#pragma once++#include <array>+#include <condition_variable>+#include <deque>+#include <mutex>+#include <pthread.h>++// This hook is compiled out of production builds. Tests replace entries at+// deterministic points rather than relying on timing to exercise races.+#ifndef SOCKETSWEEP_SCAN_CHECKPOINT+#define SOCKETSWEEP_SCAN_CHECKPOINT(event, parent, name) ((void)0)+#endif+#ifndef SOCKETSWEEP_SCAN_CREATE_THREAD+#define SOCKETSWEEP_SCAN_CREATE_THREAD pthread_create+#endif++namespace parallel_scan {++constexpr int MAX_WORKERS = 8;+constexpr size_t MAX_PENDING = 64;++struct Result {+ int workers = 1;+ size_t queue_peak = 0;+ int64_t sort_ns = 0;+};++struct Task {+ FileNode* node;+ int depth;+};++// Only directory jobs enter the queue. Its entries own no descriptors. A+// worker owns its subtree's child vector until enumeration is finished, then+// publishes pointers into that stable vector. Aggregation and sorting happen+// after every worker has joined, so ancestors are never updated concurrently.+class Pool {+ struct Worker {+ Pool* pool = nullptr;+ ScanStats stats;+ };+ const safe_delete::Root& root_;+ int max_depth_;+ std::mutex mutex_;+ std::condition_variable ready_;+ std::deque<Task> queue_;+ size_t outstanding_ = 1; // queued + active jobs, including the root+ size_t queue_peak_ = 1;+ std::array<Worker, MAX_WORKERS> workers_;++ safe_delete::Fd open_directory(const FileNode& node) const {+ // Reopen from the pinned root one component at a time. In particular,+ // opening a queued path must not follow a replaced parent symlink.+ safe_delete::Fd current(::openat(root_.fd.get(), ".",+ O_RDONLY | O_DIRECTORY | O_CLOEXEC));+ if (current.get() < 0) return current;+ const size_t prefix = root_.path.size() + (root_.path == "/" ? 0 : 1);+ size_t start = prefix;+ while (start < node.path.size()) {+ size_t end = node.path.find('/', start);+ if (end == std::string::npos) end = node.path.size();+ const std::string name = node.path.substr(start, end - start);+ SOCKETSWEEP_SCAN_CHECKPOINT("before_open", current.get(), name.c_str());+ current.reset(::openat(current.get(), name.c_str(),+ O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));+ if (current.get() < 0) return current;+ start = end + 1;+ }+ struct stat actual{};+ if (::fstat(current.get(), &actual) != 0 ||+ actual.st_dev != node.device || actual.st_ino != node.inode) {+ current.reset();+ }+ return current;+ }++ bool enqueue(Task task) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (queue_.size() >= MAX_PENDING) return false;+ queue_.push_back(task);+ ++outstanding_;+ queue_peak_ = std::max(queue_peak_, queue_.size());+ ready_.notify_one();+ return true;+ }++ void process(Task task, ScanStats& stats) {+ FileNode& node = *task.node;+ ++stats.dirs;+ if (task.depth >= max_depth_) { ++stats.errors; return; }+ safe_delete::Fd opened = open_directory(node);+ if (opened.get() < 0) { ++stats.errors; return; }+ SOCKETSWEEP_SCAN_CHECKPOINT("opened", opened.get(), node.path.c_str());+ DIR* listing = ::fdopendir(opened.get());+ if (!listing) { ++stats.errors; return; }+ opened.release(); // fdopendir now owns it+ const int parent = ::dirfd(listing);+ while (true) {+ errno = 0;+ struct dirent* entry = ::readdir(listing);+ if (!entry) {+ if (errno != 0) ++stats.errors;+ break;+ }+ const std::string name = entry->d_name;+ if (name == "." || name == "..") continue;+ #ifdef DT_LNK+ if (entry->d_type == DT_LNK) continue;+ #endif+ FileNode child;+ child.name = name;+ child.path = (node.path == "/" ? node.path : node.path + '/') + name;+ struct stat info{};+ if (::fstatat(parent, name.c_str(), &info, AT_SYMLINK_NOFOLLOW) != 0) {+ ++stats.errors;+ } else if (S_ISLNK(info.st_mode)) {+ continue;+ } else if (S_ISDIR(info.st_mode)) {+ child.is_dir = true;+ child.device = info.st_dev;+ child.inode = info.st_ino;+ } else if (S_ISREG(info.st_mode)) {+ child.size = info.st_size;+ ++stats.files;+ stats.total_size += info.st_size;+ }+ node.children.push_back(std::move(child));+ }+ ::closedir(listing);+ // Release the listing before any recursive fallback. Even at the queue+ // limit, descriptors stay bounded by the worker count rather than the+ // width or depth of the tree. Do not wait for queue space: all workers+ // could otherwise block while no worker remains to consume jobs.+ for (auto& child : node.children) {+ if (child.is_dir) {+ Task next{&child, task.depth + 1};+ if (!enqueue(next)) process(next, stats);+ }+ }+ }++ void work(ScanStats& stats) {+ while (true) {+ Task task{};+ {+ std::unique_lock<std::mutex> lock(mutex_);+ ready_.wait(lock, [&] { return !queue_.empty() || outstanding_ == 0; });+ if (outstanding_ == 0) return;+ task = queue_.front();+ queue_.pop_front();+ }+ process(task, stats);+ {+ std::lock_guard<std::mutex> lock(mutex_);+ if (--outstanding_ == 0) ready_.notify_all();+ }+ }+ }++ static void* entry(void* context) {+ auto& worker = *static_cast<Worker*>(context);+ worker.pool->work(worker.stats);+ return nullptr;+ }++ static void aggregate(FileNode& node, int64_t& sort_ns) {+ if (!node.is_dir) return;+ node.size = 0;+ for (auto& child : node.children) {+ aggregate(child, sort_ns);+ node.size += child.size;+ }+ const auto start = std::chrono::steady_clock::now();+ std::sort(node.children.begin(), node.children.end(),+ [](const FileNode& a, const FileNode& b) { return a.size > b.size; });+ sort_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(+ std::chrono::steady_clock::now() - start).count();+ }++public:+ Pool(const safe_delete::Root& root, FileNode& tree, int max_depth)+ : root_(root), max_depth_(max_depth) {+ queue_.push_back({&tree, 0});+ for (auto& worker : workers_) worker.pool = this;+ }++ Result run(FileNode& tree, ScanStats& stats, int requested_workers) {+ Result result;+ std::array<pthread_t, MAX_WORKERS - 1> threads{};+ const int count = std::max(1, std::min(requested_workers, MAX_WORKERS));+ for (int i = 1; i < count; ++i) {+ // pthread_create reports failure without throwing: the daemon is+ // built with -fno-exceptions. Fewer workers still finish all jobs.+ if (SOCKETSWEEP_SCAN_CREATE_THREAD(&threads[i - 1], nullptr, entry,+ &workers_[i]) != 0) break;+ ++result.workers;+ }+ work(workers_[0].stats); // the calling thread participates+ for (int i = 1; i < result.workers; ++i) ::pthread_join(threads[i - 1], nullptr);+ for (int i = 0; i < result.workers; ++i) {+ stats.files += workers_[i].stats.files;+ stats.dirs += workers_[i].stats.dirs;+ stats.total_size += workers_[i].stats.total_size;+ stats.errors += workers_[i].stats.errors;+ }+ result.queue_peak = queue_peak_;+ aggregate(tree, result.sort_ns);+ return result;+ }+};++inline Result run(const safe_delete::Root& root, FileNode& tree, ScanStats& stats,+ int workers, int max_depth) {+ Pool pool(root, tree, max_depth);+ return pool.run(tree, stats, workers);+}++} // namespace parallel_scandiff --git a/tests/benchmark_scan.py b/tests/benchmark_scan.pynew file mode 100644index 0000000..6191db6--- /dev/null+++ b/tests/benchmark_scan.py@@ -0,0 +1,142 @@+"""Compare authenticated daemon scans on a disposable host fixture.++Example: python3 tests/benchmark_scan.py /tmp/new-daemon --baseline /tmp/old-daemon+Run as an ordinary user: UID 0 deliberately forces the daemon's serial root mode.+This measures warm-cache host traversal/JSON transfer, not Android performance.+"""++import argparse+import hashlib+import json+import os+from pathlib import Path+import random+import secrets+import socket+import statistics+import subprocess+import tempfile+import time+++def fingerprint(result):+ """Compare paths/types/sizes and all counters, independently of child order."""+ entries = []+ pending = [result["tree"]]+ while pending:+ node = pending.pop()+ entries.append((node["path"], node["type"], node["size"]))+ pending.extend(node.get("children", []))+ counters = {key: result[key] for key in+ ["total_files", "total_dirs", "total_size", "errors", "skipped", "read_only"]}+ return hashlib.sha256(json.dumps([counters, sorted(entries)], ensure_ascii=True).encode()).hexdigest()+++class Daemon:+ def __init__(self, binary, work, threads):+ self.token = secrets.token_hex(32)+ token_file = work / ("token-" + self.token[:8])+ token_file.write_text(self.token + "\n")+ token_file.chmod(0o600)+ with socket.socket() as reservation:+ reservation.bind(("127.0.0.1", 0))+ self.port = reservation.getsockname()[1]+ args = [str(binary), str(self.port), str(token_file)]+ if threads is not None:+ args.extend(["--threads", str(threads)])+ self.process = subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ try:+ for attempt in range(100):+ try:+ self.command("PING")+ return+ except OSError:+ if self.process.poll() is not None:+ raise RuntimeError("Daemon exited during startup")+ time.sleep(0.01)+ raise RuntimeError("Daemon startup timed out")+ except BaseException:+ self.close()+ raise++ def command(self, command):+ with socket.create_connection(("127.0.0.1", self.port), timeout=120) as client:+ client.sendall(f"AUTH {self.token}\n{command}\n".encode())+ data = bytearray()+ while chunk := client.recv(256 * 1024):+ data.extend(chunk)+ result = json.loads(data)+ if result["status"] != "ok":+ raise RuntimeError(result)+ return result, len(data)++ def close(self):+ if self.process.poll() is None:+ try:+ self.command("SHUTDOWN")+ self.process.wait(timeout=5)+ except (OSError, RuntimeError, subprocess.TimeoutExpired):+ self.process.kill()+ self.process.wait()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("binary", type=Path)+ parser.add_argument("--baseline", type=Path)+ parser.add_argument("--output", type=Path)+ parser.add_argument("--repeats", type=int, default=5)+ args = parser.parse_args()+ if os.geteuid() == 0 or args.repeats < 1:+ parser.error("Use an ordinary user and at least one repeat")+ with tempfile.TemporaryDirectory(prefix="socketsweep-benchmark-") as directory:+ work = Path(directory)+ root = work / "storage"+ root.mkdir()+ for album in range(200):+ child = root / f"album_{album:03}"+ child.mkdir()+ for index in range(200):+ with (child / f"file_{index:03}").open("wb") as file:+ file.truncate(1024 + index)+ daemons = {}+ results = []+ try:+ if args.baseline:+ daemons["baseline"] = Daemon(args.baseline.resolve(), work, None)+ for workers in [1, 2, 4, 8]:+ daemons[str(workers)] = Daemon(args.binary.resolve(), work, workers)+ reference = None+ for daemon in daemons.values():+ result, _ = daemon.command(f"SCAN {root}")+ assert result["total_files"] == 40000 and result["total_dirs"] == 201+ assert result["total_size"] == 44940000 and result["errors"] == 0+ digest = fingerprint(result)+ reference = reference or digest+ assert digest == reference, "Warm-up tree differs"+ trials = list(daemons) * args.repeats+ random.Random(27).shuffle(trials)+ for mode in trials:+ start = time.perf_counter()+ result, wire_bytes = daemons[mode].command(f"SCAN {root}")+ wall_ms = (time.perf_counter() - start) * 1000+ assert fingerprint(result) == reference, "Measured scan differs"+ row = {key: result[key] for key in ["scan_time_ms", "traverse_ms", "sort_ms",+ "serialize_ms", "send_ms", "total_files",+ "total_dirs", "total_size", "errors"]}+ row.update(mode=mode, wall_ms=wall_ms, wire_bytes=wire_bytes)+ results.append(row)+ for mode in daemons:+ samples = [row for row in results if row["mode"] == mode]+ summary = {key: round(statistics.median(row[key] for row in samples), 3)+ for key in samples[0] if key != "mode"}+ print(mode, json.dumps(summary), flush=True)+ if args.output:+ args.output.write_text(json.dumps(results, indent=2) + "\n")+ finally:+ for daemon in daemons.values():+ daemon.close()+++if __name__ == "__main__":+ main()diff --git a/tests/parallel_scan_test.cpp b/tests/parallel_scan_test.cppnew file mode 100644index 0000000..48e4d01--- /dev/null+++ b/tests/parallel_scan_test.cpp@@ -0,0 +1,208 @@+#include <cerrno>+#include <cstdio>+#include <filesystem>+#include <functional>+#include <map>+#include <pthread.h>+#include <sys/resource.h>++static std::function<void(const char*, int, const char*)> checkpoint;+static void scan_checkpoint(const char* event, int parent, const char* name) {+ if (checkpoint) checkpoint(event, parent, name);+}+static int create_calls = 0;+static int fail_after = -1;+static int create_thread(pthread_t* thread, const pthread_attr_t* attr,+ void* (*entry)(void*), void* context) {+ if (fail_after >= 0 && create_calls++ >= fail_after) return EAGAIN;+ return pthread_create(thread, attr, entry, context);+}+#define SOCKETSWEEP_SCAN_CHECKPOINT scan_checkpoint+#define SOCKETSWEEP_SCAN_CREATE_THREAD create_thread+#define main daemon_main+#include "../engine/daemon.cpp"+#undef main++static void require(bool ok, const char* message) {+ if (!ok) { std::fprintf(stderr, "%s\n", message); std::exit(1); }+}+struct Fixture {+ std::string path;+ Fixture() {+ char pattern[] = "/tmp/socketsweep-parallel-XXXXXX";+ char* created = ::mkdtemp(pattern);+ require(created != nullptr, "mkdtemp failed");+ path = created;+ }+ ~Fixture() { std::error_code error; std::filesystem::remove_all(path, error); }+ std::string dir(const std::string& name) {+ const auto value = path + '/' + name;+ require(::mkdir(value.c_str(), 0700) == 0, "mkdir failed");+ return value;+ }+ void file(const std::string& name, size_t size) {+ const auto value = path + '/' + name;+ safe_delete::Fd fd(::open(value.c_str(), O_CREAT | O_WRONLY | O_EXCL | O_CLOEXEC, 0600));+ require(fd.get() >= 0 && ::ftruncate(fd.get(), static_cast<off_t>(size)) == 0,+ "file creation failed");+ }+};+struct Snapshot {+ FileNode tree;+ ScanStats stats;+ parallel_scan::Result result;+};+static Snapshot run(const std::string& path, int workers) {+ safe_delete::Root root;+ require(root.open(path), "root open failed");+ Snapshot snapshot;+ snapshot.tree.name = path.substr(path.rfind('/') + 1);+ snapshot.tree.path = path;+ snapshot.tree.is_dir = true;+ snapshot.tree.device = root.identity.st_dev;+ snapshot.tree.inode = root.identity.st_ino;+ snapshot.result = parallel_scan::run(root, snapshot.tree, snapshot.stats, workers, cfg::MAX_DEPTH);+ require(snapshot.result.workers >= 1 && snapshot.result.workers <= workers,+ "worker count out of bounds");+ require(snapshot.result.queue_peak <= parallel_scan::MAX_PENDING, "queue exceeded bound");+ return snapshot;+}+using Entries = std::map<std::string, std::pair<bool, int64_t>>;+static void flatten(const FileNode& node, Entries& entries) {+ require(entries.emplace(node.path, std::make_pair(node.is_dir, node.size)).second,+ "duplicate output path");+ for (const auto& child : node.children) flatten(child, entries);+ for (size_t i = 1; i < node.children.size(); ++i) {+ require(node.children[i-1].size >= node.children[i].size, "children are not size-sorted");+ }+}+static void same(const Snapshot& actual, const FileNode& expected, const ScanStats& stats) {+ Entries a, b;+ flatten(actual.tree, a);+ flatten(expected, b);+ require(a == b, "parallel tree differs from serial reference");+ require(actual.stats.files == stats.files && actual.stats.dirs == stats.dirs &&+ actual.stats.total_size == stats.total_size && actual.stats.errors == stats.errors &&+ actual.stats.skipped == stats.skipped, "parallel statistics differ from serial reference");+}+static void equivalence() {+ Fixture fixture;+ for (int d = 0; d < 180; ++d) {+ const std::string dir = "album " + std::to_string(d);+ fixture.dir(dir);+ fixture.dir(dir + "/empty");+ for (int i = 0; i < 12; ++i) fixture.file(dir + "/file " + std::to_string(i), d + i);+ }+ fixture.file(".hidden", 17);+ fixture.file(" leading and trailing ", 29);+ fixture.file("quote\"line\n", 31);+ require(::link((fixture.path + "/.hidden").c_str(), (fixture.path + "/hard-link").c_str()) == 0,+ "hard link creation failed");+ require(::symlink("album 0", (fixture.path + "/dir-link").c_str()) == 0, "symlink failed");+ require(::symlink(".hidden", (fixture.path + "/file-link").c_str()) == 0, "symlink failed");+ require(::mkfifo((fixture.path + "/fifo").c_str(), 0600) == 0, "fifo failed");+#if defined(__linux__)+ fixture.file(std::string("nonutf-") + '\xff', 41);+#endif+ ScanStats stats;+ g_read_only = false;+ FileNode expected = scan(fixture.path, fixture.path.substr(fixture.path.rfind('/') + 1), stats, 0);+ for (int workers : {1, 2, 4, 8}) {+ for (int repeat = 0; repeat < 3; ++repeat) same(run(fixture.path, workers), expected, stats);+ }+}+static void depth() {+ Fixture fixture;+ std::string path;+ for (int level = 0; level < 67; ++level) {+ fixture.file(path + (path.empty() ? "" : "/") + "file", level);+ path += (path.empty() ? "" : "/") + std::string("next");+ fixture.dir(path);+ }+ ScanStats stats;+ const auto name = fixture.path.substr(fixture.path.rfind('/') + 1);+ FileNode expected = scan(fixture.path, name, stats, 0);+ require(stats.errors == 1 && stats.dirs == 65 && stats.files == 64, "bad depth fixture");+ for (int workers : {1, 4, 8}) same(run(fixture.path, workers), expected, stats);+}+static void replacement(const std::string& kind) {+ Fixture fixture;+ fixture.dir("root");+ fixture.dir("root/selected");+ fixture.file("root/selected/original", 3);+ fixture.dir("outside");+ fixture.file("outside/secret", 1000000);+ bool fired = false;+ std::mutex barrier;+ checkpoint = [&](const char* event, int, const char* name) {+ std::lock_guard<std::mutex> lock(barrier);+ const bool match = kind == "opened" ?+ std::string(event) == "opened" && std::string(name) == fixture.path + "/root/selected" :+ std::string(event) == "before_open" && std::string(name) == "selected";+ if (fired || !match) return;+ fired = true;+ require(::rename((fixture.path + "/root/selected").c_str(), (fixture.path + "/moved").c_str()) == 0,+ "race rename failed");+ if (kind == "inode") {+ fixture.dir("root/selected");+ fixture.file("root/selected/replacement", 1000000);+ } else {+ require(::symlink((fixture.path + "/outside").c_str(),+ (fixture.path + "/root/selected").c_str()) == 0, "race symlink failed");+ }+ };+ const auto snapshot = run(fixture.path + "/root", 4);+ checkpoint = {};+ require(fired, "race checkpoint not reached");+ require(snapshot.stats.total_size == (kind == "opened" ? 3 : 0), "replacement data scanned");+ require(snapshot.stats.errors == (kind == "opened" ? 0 : 1), "replacement error not reported");+}+static size_t descriptors() {+ DIR* dir = ::opendir("/dev/fd");+ require(dir != nullptr, "descriptor listing failed");+ size_t count = 0;+ while (auto* entry = ::readdir(dir)) if (entry->d_name[0] != '.') ++count;+ ::closedir(dir);+ return count;+}+static void resources() {+ Fixture fixture;+ for (int i = 0; i < 800; ++i) {+ const auto dir = std::to_string(i);+ fixture.dir(dir);+ fixture.file(dir + "/file", 7);+ }+ struct rlimit saved{};+ require(::getrlimit(RLIMIT_NOFILE, &saved) == 0, "getrlimit failed");+ struct rlimit limited = saved;+ limited.rlim_cur = std::min<rlim_t>(saved.rlim_cur, 32);+ require(::setrlimit(RLIMIT_NOFILE, &limited) == 0, "setrlimit failed");+ const size_t before = descriptors();+ const auto serial = run(fixture.path, 1);+ require(serial.result.queue_peak == parallel_scan::MAX_PENDING && serial.stats.files == 800,+ "queue saturation fallback lost work");+ for (int i = 0; i < 8; ++i) {+ const auto snapshot = run(fixture.path, 8);+ require(snapshot.stats.files == 800 && snapshot.stats.total_size == 5600 &&+ snapshot.stats.errors == 0, "low-descriptor scan failed");+ }+ require(descriptors() == before, "scan leaked descriptors");+ require(::setrlimit(RLIMIT_NOFILE, &saved) == 0, "restore rlimit failed");+ for (int failure : {0, 2}) {+ fail_after = failure;+ create_calls = 0;+ const auto snapshot = run(fixture.path, 8);+ require(snapshot.result.workers == failure + 1, "worker creation fallback failed");+ require(snapshot.stats.files == 800 && snapshot.stats.errors == 0, "worker fallback lost files");+ }+ fail_after = -1;+}+int main(int argc, char** argv) {+ require(argc == 2, "test case required");+ const std::string test = argv[1];+ if (test == "equivalence") equivalence();+ else if (test == "depth") depth();+ else if (test == "symlink" || test == "inode" || test == "opened") replacement(test);+ else if (test == "resources") resources();+ else require(false, "unknown test case");+}diff --git a/tests/test_daemon.py b/tests/test_daemon.pyindex 279842c..258280d 100644--- a/tests/test_daemon.py+++ b/tests/test_daemon.py@@ -18,13 +18,14 @@ import unittestclass DaemonHarness(unittest.TestCase):read_only = False+ scan_threads = None@classmethoddef setUpClass(cls):cls.build_dir = tempfile.TemporaryDirectory(prefix="socketsweep-test-build-")cls.binary = str(Path(cls.build_dir.name) / "daemon")compiler = os.environ.get("CXX") or shutil.which("clang++") or "c++"source = Path(__file__).resolve().parents[1] / "engine" / "daemon.cpp"- subprocess.run([compiler, "-std=c++17", "-O2", "-Wall", "-Wextra",+ subprocess.run([compiler, "-std=c++17", "-O2", "-pthread", "-Wall", "-Wextra","-Wpedantic", "-fno-exceptions", "-fno-rtti",str(source), "-o", cls.binary], check=True)@@ -47,6 +48,8 @@ class DaemonHarness(unittest.TestCase):args = [self.binary, str(self.port), str(token_file)]if self.read_only:args.append("--read-only")+ if self.scan_threads is not None:+ args.extend(["--threads", str(self.scan_threads)])self.process = subprocess.Popen(args,stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)self.addCleanup(self.stop)@@ -202,6 +205,7 @@ class DaemonTests(DaemonHarness):class ReadOnlyDaemonTests(DaemonHarness):read_only = True+ scan_threads = 8def test_read_only_handshake_and_delete_block_before_and_after_scan(self):status = self.request("PING")@@ -212,7 +216,9 @@ class ReadOnlyDaemonTests(DaemonHarness):target.write_text("private app data")for scanned in [False, True]:if scanned:- self.assertTrue(self.scan()["read_only"])+ result = self.scan()+ self.assertTrue(result["read_only"])+ self.assertEqual(result["scan_threads"], 1)result = self.request(f"DELETE {target}")self.assertEqual(result["status"], "error")self.assertIn("read-only", result["message"])@@ -256,7 +262,7 @@ class DeletionRaceTests(unittest.TestCase):cls.binary = str(Path(cls.build_dir.name) / "race-tests")compiler = os.environ.get("CXX") or shutil.which("clang++") or "c++"source = Path(__file__).resolve().parent / "safe_delete_test.cpp"- subprocess.run([compiler, "-std=c++17", "-O2", "-Wall", "-Wextra",+ subprocess.run([compiler, "-std=c++17", "-O2", "-pthread", "-Wall", "-Wextra","-Wpedantic", "-fno-exceptions", "-fno-rtti",str(source), "-o", cls.binary], check=True)diff --git a/tests/test_parallel_scan.py b/tests/test_parallel_scan.pynew file mode 100644index 0000000..6a9a472--- /dev/null+++ b/tests/test_parallel_scan.py@@ -0,0 +1,62 @@+"""Scanner equivalence, scheduler resource bounds, and deterministic races."""++import os+from pathlib import Path+import shutil+import subprocess+import tempfile+import unittest++from test_daemon import DaemonHarness+++class ParallelScanTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.build = tempfile.TemporaryDirectory(prefix="socketsweep-parallel-build-")+ cls.binary = str(Path(cls.build.name) / "scanner-tests")+ compiler = os.environ.get("CXX") or shutil.which("clang++") or "c++"+ source = Path(__file__).with_name("parallel_scan_test.cpp")+ subprocess.run([compiler, "-std=c++17", "-O2", "-pthread", "-Wall", "-Wextra",+ "-Wpedantic", "-fno-exceptions", "-fno-rtti", str(source),+ "-o", cls.binary], check=True)++ @classmethod+ def tearDownClass(cls):+ cls.build.cleanup()++ def run_case(self, case):+ result = subprocess.run([self.binary, case], capture_output=True, text=True, timeout=30)+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)++ def test_all_worker_counts_match_serial_tree_and_totals(self): self.run_case("equivalence")+ def test_depth_limit_is_preserved(self): self.run_case("depth")+ def test_queued_directory_symlink_replacement_is_not_followed(self): self.run_case("symlink")+ def test_queued_directory_inode_replacement_is_reported(self): self.run_case("inode")+ def test_opened_directory_cannot_redirect_to_symlink_target(self): self.run_case("opened")+ def test_low_descriptor_limit_cleanup_and_worker_creation_failure(self): self.run_case("resources")+++class ParallelProtocolTests(DaemonHarness):+ def test_worker_argument_validation(self):+ for flags in [["--threads"], ["--threads", "0"], ["--threads", "9"],+ ["--threads", "4junk"], ["--threads", "-1"], ["--threads", "2", "--threads", "3"],+ ["--read-only", "--read-only"], ["--unknown"]]:+ result = subprocess.run([self.binary, "5050", "unused-token", *flags],+ capture_output=True, text=True, timeout=3)+ self.assertNotEqual(result.returncode, 0)+ self.assertIn("Usage:", result.stderr)++ def test_parallel_scan_keeps_protocol_and_directory_totals(self):+ for i in range(80):+ directory = self.root / str(i)+ directory.mkdir()+ (directory / "file").write_bytes(b"1234567")+ result = self.scan()+ self.assertEqual(result["scan_threads"], 1 if os.geteuid() == 0 else 4)+ self.assertEqual(result["total_files"], 80)+ self.assertEqual(result["total_dirs"], 81)+ self.assertEqual(result["total_size"], 560)+ self.assertEqual(result["errors"], 0)+ self.assertEqual(result["tree"]["size"], 560)+ self.assertTrue(all(child["size"] == 7 for child in result["tree"]["children"]))diff --git a/tests/test_root_scan.py b/tests/test_root_scan.pyindex 6e88848..b24330d 100644--- a/tests/test_root_scan.py+++ b/tests/test_root_scan.py@@ -26,7 +26,7 @@ class RootScanSandboxTests(unittest.TestCase):cls.build = tempfile.TemporaryDirectory(prefix="socketsweep-root-build-")cls.binary = Path(cls.build.name) / "daemon"source = Path(__file__).resolve().parents[1] / "engine" / "daemon.cpp"- subprocess.run([os.environ.get("CXX", "g++"), "-std=c++17", "-O2", "-static",+ subprocess.run([os.environ.get("CXX", "g++"), "-std=c++17", "-O2", "-pthread", "-static","-Wall", "-Wextra", "-Wpedantic", "-fno-exceptions","-fno-rtti", str(source), "-o", str(cls.binary)], check=True)