Detect stalled runs, wait for memory to settle after a stop, and stop bottles through WINEPREFIX (#385)

This commit is contained in:
atharvranjan committed 2026-11-25 15:08:42 -06:00
1 parent 566272082a
commit 8e5856bbcf
6 files changed
+244 -12

No files matched your search

+1
View File
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- Added `--stall-timeout` and a memory-settle wait to `betterxen-hybrid run`/`bench` (#385): a run that prints nothing for the given time is stopped and classified `stalled`, and after any stop the supervisor waits (up to `--settle-bound`, default 60 s) until free memory is back above the start threshold and records whether it recovered. Based on supervision lessons from skakwy's victory-mac (reimplemented, not copied). Also fixes a defect found by the first real stall run: stopping a bottle used `CX_BOTTLE`, which does not select the bottle, so a stopped Windows process kept running; it now sets `WINEPREFIX`. Verified with 4 new unit tests (stub launcher) and a real CrossOver 26.3 run on the M4: a silent workload was stopped as `stalled` after 4.7 s of a 120 s timeout, nothing was left running, and the next run passed. The low-memory recovery path is only tested with an injected memory reader. Not independently reviewed.
- Added `betterxen-hybrid run` and `bench`: launch a Windows program through an installed CrossOver (`bin/wine --bottle`, an interface CodeWeavers does not document for macOS), with timeout, the memory guard, failure classification (passed, failed exit, timed out, stopped on low memory, cannot execute, no graphics device), sampled CrossOver process memory and CPU, thermal notes, recognised host-noise diagnostics and frame statistics, and write a JSON record; `bench` repeats a workload across graphics backends. Locally verified with 24 unit tests (stub launcher) and with real runs on CrossOver 26.3 on the Apple M4.
- Executed the original Windows workloads under CrossOver 26.3 for the first time (`docs/research/crossover-baseline-2026-11-25.md`). x86-64 C, Rust, Direct3D 11 clear and triangle/frame-loop programs passed; all four ARM64 builds were rejected by CrossOver (`cannot execute`). Five-repeat, 2000-frame comparison of default, D3DMetal, DXMT, DXVK and wined3d on a trivial offscreen workload: D3DMetal's median submit-and-wait was about 1.8 times the others; this is not rendering performance. Observed on one machine, not independently reproduced, using an undocumented backend variable.
- Added `workloads/d3d11-frameloop` (indexed triangle, shaders, event-query frame loop) and negative controls for both Direct3D programs; made workload builds byte-reproducible on one machine with `--no-insert-timestamp`.
+1 -1
View File
@@ -16,4 +16,4 @@ Cargo resolves the Rust packages from crates.io at the source checksums in [Carg
The [isolated fuzz workspace](fuzz/Cargo.lock) resolves developer-only dependencies, including [libfuzzer-sys](https://github.com/rust-fuzz/libfuzzer/tree/719e4efb9b8857ebaa782ae59376c8cbb78fed0f). See the [fuzz dependency inventory](docs/licenses.md#fuzz-development-dependencies) for locked revisions and selected licenses.
llvm-mingw release 20261117 is used as an external build tool for original Windows test programs under Apache-2.0 with LLVM exceptions plus its component licences; nothing from it is shipped or copied (see [hybrid-toolchain](docs/research/hybrid-toolchain.md)). `crates/hybrid/src/memory.rs` is a Rust reimplementation of the memory-guard logic in skakwy's [victory-mac](https://github.com/skakwy/victory-mac) `mac/run-victory.sh` (commit 22b3f8e45a59, GPL-3.0), used with the author's permission.
llvm-mingw release 20261117 is used as an external build tool for original Windows test programs under Apache-2.0 with LLVM exceptions plus its component licences; nothing from it is shipped or copied (see [hybrid-toolchain](docs/research/hybrid-toolchain.md)). `crates/hybrid/src/memory.rs` is a Rust reimplementation of the memory-guard logic in skakwy's [victory-mac](https://github.com/skakwy/victory-mac) `mac/run-victory.sh` (commit 22b3f8e45a59, GPL-3.0), used with the author's permission. The stall detection and memory-settle logic in `crates/hybrid/src/run.rs` follows supervision lessons from the same repository (`mac/PROGRESS.md`, `crates/victory-core/src/notes.rs`) and is reimplemented, not copied.
+8 -1
View File
@@ -9,7 +9,7 @@ const USAGE: &str = "usage: betterxen-hybrid <command>
frames <file> frame-time statistics; file has one interval in ms per line (JSON)
guard [--min-start-free N] [--min-free N] -- CMD ARGS...
run CMD; refuse to start / stop it when free memory is low
run --bottle B [--backend X] [--timeout S] [--expect TEXT] [--out DIR]
run --bottle B [--backend X] [--timeout S] [--stall-timeout S] [--settle-bound S] [--expect TEXT] [--out DIR]
[--min-start-free N] [--min-free N] -- EXE [ARGS...]
run a Windows program through CrossOver; write a JSON record
bench --bottle B --backends a,b,c [--repeat N] [same options] -- EXE [ARGS...]
@@ -112,6 +112,8 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
let mut backends = Vec::new();
let mut repeat = 1u32;
let mut timeout = 300u64;
let mut stall = None;
let mut settle = 60u64;
let mut expect = None;
let mut out = None;
let (mut min_start, mut min_free) = (50u8, 15u8);
@@ -127,6 +129,8 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
"--backends" => backends = v.split(',').map(String::from).collect(),
"--repeat" => repeat = v.parse().map_err(|_| "bad --repeat")?,
"--timeout" => timeout = v.parse().map_err(|_| "bad --timeout")?,
"--stall-timeout" => stall = Some(v.parse().map_err(|_| "bad --stall-timeout")?),
"--settle-bound" => settle = v.parse().map_err(|_| "bad --settle-bound")?,
"--expect" => expect = Some(v),
"--out" => out = Some(PathBuf::from(v)),
"--min-start-free" => min_start = v.parse().map_err(|_| "bad --min-start-free")?,
@@ -165,6 +169,9 @@ fn parse_run_args(args: &[String]) -> Result<RunArgs, String> {
},
expect,
work_dir: work,
stall_timeout: stall.map(std::time::Duration::from_secs),
settle_bound: std::time::Duration::from_secs(settle),
read_free: memory::free_percentage,
},
backends,
repeat,
+212 -9
View File
@@ -8,7 +8,15 @@
//! launcher interface is vendor-help-only. The graphics backend is selected through the
//! `CX_GRAPHICS_BACKEND` environment variable, which appears in third-party launch scripts and
//! is likewise undocumented; an unrecognised value was observed to be ignored silently, so a
//! record names the backend *requested* and relies on the workload's own diagnostics
//!
//! Stall detection and the wait for memory to settle after a stop follow the supervision
//! lessons in skakwy's <https://github.com/skakwy/victory-mac> (`mac/PROGRESS.md`,
//! `mac/run-victory.sh`, `crates/victory-core/src/notes.rs` at commit 22b3f8e45a59; his own
//! work, GPL-3.0, used with his permission): detect a hung run by absence of progress, stop a
//! bottle with `wineserver -k` and its prefix, and do not start the next run until memory has
//! been returned. Reimplemented here; none of his code is copied.
//!
//! A record names the backend *requested* and relies on the workload's own diagnostics
//! (adapter name, backend log lines) to show what actually ran.
use crate::frames;
@@ -30,6 +38,12 @@ pub struct RunConfig {
/// Text that must appear in stdout for a zero exit to count as a pass.
pub expect: Option<String>,
pub work_dir: PathBuf,
/// Stop the run when neither stdout nor stderr has grown for this long.
pub stall_timeout: Option<Duration>,
/// After a stop, wait at most this long for free memory to return to `min_start_free`.
pub settle_bound: Duration,
/// Free-memory reader; `memory::free_percentage` outside tests.
pub read_free: fn() -> Option<u8>,
}
#[derive(Debug, Clone, PartialEq)]
@@ -38,6 +52,8 @@ pub enum Class {
FailedExit(i32),
MissingExpectedMarker,
TimedOut,
/// No output on stdout or stderr for the stall timeout.
Stalled,
StoppedLowMemory,
RefusedToStart,
/// The Windows loader did not accept the file (for example an ARM64 PE this build cannot run).
@@ -55,6 +71,7 @@ impl Class {
Class::FailedExit(c) => format!("failed_exit_{c}"),
Class::MissingExpectedMarker => "missing_expected_marker".into(),
Class::TimedOut => "timed_out".into(),
Class::Stalled => "stalled".into(),
Class::StoppedLowMemory => "stopped_low_memory".into(),
Class::RefusedToStart => "refused_to_start_low_memory".into(),
Class::CannotExecute => "cannot_execute".into(),
@@ -171,8 +188,9 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
let err_path = cfg
.work_dir
.join(format!("stderr-{t_wall}-{}.txt", std::process::id()));
let mut settle: Option<(Duration, bool)> = None;
let thermal_before = thermal();
let free_start = memory::free_percentage();
let free_start = (cfg.read_free)();
let mut result = RunRecord {
class: Class::LaunchFailed,
@@ -212,6 +230,8 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
let needles = vec![bundle, format!("Bottles/{}", cfg.bottle)];
let (mut cpu_sum, mut n) = (0f64, 0u32);
let mut stop: Option<Class> = None;
let mut last_len = 0u64;
let mut last_growth = Instant::now();
loop {
match child.try_wait() {
Ok(Some(st)) => {
@@ -225,7 +245,7 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
result.samples.peak_rss_kb = result.samples.peak_rss_kb.max(rss);
cpu_sum += cpu;
n += 1;
match memory::free_percentage() {
match (cfg.read_free)() {
Some(f) => {
let m = result.samples.min_free_percent.map_or(f, |x| x.min(f));
result.samples.min_free_percent = Some(m);
@@ -235,22 +255,46 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
}
None => stop = Some(Class::MemoryUnreadable),
}
let len = [&out_path, &err_path]
.iter()
.map(|p| std::fs::metadata(p).map_or(0, |m| m.len()))
.sum::<u64>();
if len != last_len {
last_len = len;
last_growth = Instant::now();
}
if stop.is_none() && started.elapsed() > cfg.timeout {
stop = Some(Class::TimedOut);
}
if stop.is_none()
&& cfg.stall_timeout.is_some_and(|d| last_growth.elapsed() > d)
{
stop = Some(Class::Stalled);
}
if stop.is_some() {
memory::terminate(&mut child, cfg.limits.grace);
if let Some(dir) = cfg.wine.parent() {
let _ = Command::new(dir.join("wineserver"))
.arg("-k")
.env("CX_BOTTLE", &cfg.bottle)
.status();
}
stop_bottle(&cfg.wine, &cfg.bottle);
break;
}
std::thread::sleep(cfg.limits.poll);
}
result.duration = started.elapsed();
if stop.is_some() {
let t = Instant::now();
let need = cfg.limits.min_start_free;
let mut recovered = false;
loop {
if (cfg.read_free)().is_some_and(|f| f >= need) {
recovered = true;
break;
}
if t.elapsed() >= cfg.settle_bound {
break;
}
std::thread::sleep(cfg.limits.poll);
}
settle = Some((t.elapsed(), recovered));
}
result.samples.samples = n;
result.samples.mean_cpu_percent_of_core =
if n > 0 { cpu_sum / n as f64 } else { 0.0 };
@@ -319,6 +363,21 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
Json::Num(result.duration.as_secs_f64() * 1000.0),
),
("timeout_s", Json::Num(cfg.timeout.as_secs_f64())),
(
"stall_timeout_s",
cfg.stall_timeout
.map_or(Json::Null, |d| Json::Num(d.as_secs_f64())),
),
(
"memory_settle_after_stop",
settle.map_or(Json::Null, |(d, ok)| {
Json::obj(vec![
("waited_ms", Json::Num(d.as_secs_f64() * 1000.0)),
("recovered_to_start_threshold", Json::Bool(ok)),
("bound_s", Json::Num(cfg.settle_bound.as_secs_f64())),
])
}),
),
(
"free_memory_percent_at_start",
free_start.map_or(Json::Null, |f| Json::Num(f as f64)),
@@ -355,6 +414,30 @@ pub fn execute(cfg: &RunConfig, crossover_build: Option<String>) -> RunRecord {
result
}
/// Prefix directory of a bottle. CrossOver documents `BottleDir` in its preferences; otherwise
/// the default location under Application Support is used.
pub fn bottle_prefix(bottle: &str) -> PathBuf {
let base = crate::crossover::preference("BottleDir")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(std::env::var("HOME").unwrap_or_default())
.join("Library/Application Support/CrossOver/Bottles")
});
base.join(bottle)
}
/// Stop every process of one bottle with `wineserver -k`, selecting the bottle through
/// `WINEPREFIX`. Setting `CX_BOTTLE` instead was tried first and observed NOT to select the
/// bottle: the Windows process kept running after the supervisor reported it stopped.
pub fn stop_bottle(wine: &Path, bottle: &str) {
if let Some(dir) = wine.parent() {
let _ = Command::new(dir.join("wineserver"))
.arg("-k")
.env("WINEPREFIX", bottle_prefix(bottle))
.status();
}
}
pub fn wine_path(app: &Path) -> PathBuf {
app.join("Contents/SharedSupport/CrossOver/bin/wine")
}
@@ -425,6 +508,9 @@ mod tests {
},
expect: Some("PASS".into()),
work_dir: std::env::temp_dir().join(format!("bxrun-{tag}-{}", std::process::id())),
stall_timeout: None,
settle_bound: Duration::from_millis(200),
read_free: memory::free_percentage,
}
}
@@ -479,4 +565,121 @@ mod tests {
Class::FailedExit(3)
);
}
#[test]
fn silent_workload_is_stopped_as_stalled_before_the_timeout() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stall1-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let mut c = cfg(w, 20_000, "d");
c.stall_timeout = Some(Duration::from_millis(300));
let t0 = Instant::now();
let r = execute(&c, None);
assert_eq!(r.class, Class::Stalled);
assert!(
t0.elapsed() < Duration::from_secs(5),
"stall must fire long before the 20 s timeout"
);
assert!(r.json.render().contains("\"classification\": \"stalled\""));
}
#[test]
fn workload_that_keeps_printing_is_not_stalled() {
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stall2-{}", std::process::id()));
// Prints every 0.1 s for about 1.2 s: longer than the 0.5 s stall timeout in total.
let w = stub(
&dir,
"i=0; while [ $i -lt 12 ]; do echo tick; i=$((i+1)); sleep 0.1; done; echo PASS",
);
let mut c = cfg(w, 20_000, "e");
c.stall_timeout = Some(Duration::from_millis(500));
assert_eq!(execute(&c, None).class, Class::Passed);
}
static FREE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(90);
fn fake_free() -> Option<u8> {
Some(FREE.load(std::sync::atomic::Ordering::SeqCst))
}
// One test owns the shared `FREE` value, so it does not race with the others.
#[test]
fn after_a_stop_the_run_waits_for_memory_to_return() {
use std::sync::atomic::Ordering::SeqCst;
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-settle-{}", std::process::id()));
let w = stub(&dir, "exec /bin/sleep 30");
let mut c = cfg(w, 300, "f");
c.read_free = fake_free;
c.limits.min_start_free = 50;
c.limits.min_free = 0; // only the timeout stops the run
c.settle_bound = Duration::from_secs(5);
// Memory drops 100 ms in and returns 900 ms in; the timeout stop happens at about 300 ms.
FREE.store(90, SeqCst);
let h = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(100));
FREE.store(10, SeqCst);
std::thread::sleep(Duration::from_millis(800));
FREE.store(90, SeqCst);
});
let r = execute(&c, None);
h.join().unwrap();
assert_eq!(r.class, Class::TimedOut);
let j = r.json.render();
assert!(j.contains("\"recovered_to_start_threshold\": true"), "{j}");
assert!(r.duration >= Duration::from_millis(300));
// Memory never returns: the wait gives up at the bound and says so.
FREE.store(90, SeqCst);
let h = std::thread::spawn(|| {
std::thread::sleep(Duration::from_millis(100));
FREE.store(10, SeqCst);
});
c.settle_bound = Duration::from_millis(400);
let t0 = Instant::now();
let r = execute(&c, None);
h.join().unwrap();
assert!(t0.elapsed() < Duration::from_secs(5));
assert!(
r.json
.render()
.contains("\"recovered_to_start_threshold\": false")
);
FREE.store(90, SeqCst);
}
#[test]
fn stopping_a_bottle_selects_it_through_wineprefix() {
use std::os::unix::fs::PermissionsExt;
if !cfg!(target_os = "macos") {
return;
}
let dir = std::env::temp_dir().join(format!("bxrun-stop-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let log = dir.join("wineserver.log");
let ws = dir.join("wineserver");
std::fs::write(
&ws,
format!(
"#!/bin/sh\necho \"args=$* WINEPREFIX=$WINEPREFIX\" > '{}'\n",
log.display()
),
)
.unwrap();
std::fs::set_permissions(&ws, std::fs::Permissions::from_mode(0o755)).unwrap();
stop_bottle(&dir.join("wine"), "my-bottle");
let got = std::fs::read_to_string(&log).unwrap();
assert!(got.contains("args=-k"), "{got}");
assert!(
got.contains("Bottles/my-bottle") || got.contains("/my-bottle"),
"{got}"
);
}
}
@@ -96,3 +96,19 @@ Counts for this pass: 11 component groups reviewed; 1 integrated (adapted); 0 in
- **PortWatch VI** (portwatch-vi.xyz): its own description says "leaked Xbox Series build of GTA VI". Reference for discovery only, unchanged.
- **MacBox, ScarlettMac:** see above; unchanged.
- **ossover CI** (`.github/workflows/ci.yml`): a macOS arm64 runner running `bash -n` over shell scripts, a standard-library Python manifest check with `python3 -I`, and `swift build`/`test`. The two cheap ideas (shell syntax check, isolated-interpreter script) match what `docs_hygiene.py` already does; a `bash -n` step for `scripts/hybrid/*.sh` is a candidate follow-up, not added.
### Per-file authorship of victory-mac (measured with `git blame` at `22b3f8e45a59`)
"Owned" means every line is attributed to skakwy. His permission covers these; it cannot cover lines written by others, and some owned files still carry other restrictions.
| File (lines, all his) | What it is | Decision |
| --- | --- | --- |
| `crates/victory-shader/src/emit/f64.rs` (409) | fp64 by 64-bit integer operations, with tests against the CPU's `f64` | General-purpose. Candidate for the native shader compiler; native work is paused, so it waits for a maintainer decision (#387) |
| `mac/run-victory.sh` (139), `crates/victory-core/src/notes.rs` (135) | Run script with memory guard; stall bookkeeping | Memory guard adapted (`guard`); stall detection and settle adapted in #385; the rest is game-specific launch configuration |
| `mac/unixlib/*`, `crates/victory-gpu/src/alias.rs` (369), `zerocopy.rs` (365), `crates/victory-hle/src/modules/vmem.rs` (208) | Alias mappings and a Metal swizzle over game memory | Not integrated: they act on D3DMetal internals and game memory (Apple's licence section 2D forbids reverse engineering; his notes give D3DMetal struct offsets) |
| `crates/victory-loader/src/maskmov.rs` (830), `masked_stores.rs` (243) | Rewrites masked AVX stores in a console title's image for Rosetta | Not integrated: the header says it follows XCL's `maskmov.rs`, which is GPL-2.0-only (incompatible with GPL-3.0-or-later), and it patches a title image |
| `crates/victory-gpu/src/ambient.rs` (193), `mac/scan/*` | Replaces one game's lighting output; scans its shader pack | Not integrated: game-specific |
| `crates/victory-gpu/src/dxc.rs` (110) | Loads Microsoft's `dxcompiler.dll` to compile HLSL under Wine | General-purpose. Not needed yet: D3D12 minimal tests can use SM 5.1 through `d3dcompiler_47`. Revisit when a workload needs SM 6 |
| `tools/macos/gnullvm-cc.sh`, `mac/build.sh` | Windows cross-link wrapper, build wrapper | Evaluated; failed with Homebrew `llvm@17`; superseded by llvm-mingw |
Everything else in the repository is mostly or entirely other authors' work (for example `victory-gpu/src/host.rs` is 8 % his, `victory-shader/src/emit/lower.rs` 1 %).
+6 -1
View File
@@ -5,6 +5,8 @@
// check passed; non-zero names the failing check. It touches no game data and no graphics.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
static uint32_t crc32(const unsigned char *p, size_t n) {
@@ -23,7 +25,10 @@ static DWORD WINAPI bump(LPVOID arg) {
return 0;
}
int main(void) {
// `--sleep-silent <seconds>` sleeps before printing anything, to exercise stall detection in
// the supervisor; the checks still run afterwards.
int main(int argc, char **argv) {
if (argc > 2 && !strcmp(argv[1], "--sleep-silent")) Sleep((DWORD)atoi(argv[2]) * 1000u);
#if defined(__x86_64__)
const char *arch = "x86_64";
#elif defined(__aarch64__)