Compare commits

..
Author SHA1 Message Date
atharvranjan 146d2dd467 Correct Win64 call-entry alignment wording
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:46:05 -06:00
atharvranjan a0d9b85dbf Run benchmark report tests in workspace CI and record migration review
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:42:19 -06:00
atharvranjan 5366b93986 Merge pull request #269 from MacosPorters/archive/pull/371/head
Validate DBT caches with executable generations and source revalidation
2026-11-24 22:31:00 -06:00
atharvranjan 50c392111d Merge pull request #266 from MacosPorters/archive/pull/352/head
bench: measure Metal startup in fresh processes and repeated runs (#178)
2026-11-24 22:26:04 -06:00
atharvranjan f43a07ce31 Synchronize cache generation fix with the integrated hosted C runtime
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:25:18 -06:00
atharvranjan 10fd1cd4be Merge pull request #265 from MacosPorters/archive/pull/346/head
metal: budgeted staged RGBA8 texture upload into Private storage (#144)
2026-11-24 22:24:24 -06:00
atharvranjan 95aa10c60f Merge pull request #278 from MacosPorters/archive/pull/394/head
Pack block-compressed texture mip chains by subresource
2026-11-24 22:24:17 -06:00
atharvranjan 873b4fd4a9 Integrate PR #266 and distinguish imported benchmark evidence
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:19:01 -06:00
atharvranjan d26af53cef Merge pull request #283 from MacosPorters/archive/pull/420/head
loader: add the Gate A2 hosted C program and its test (#419)
2026-11-24 22:15:23 -06:00
atharvranjan b6ebaaad5e Merge pull request #282 from MacosPorters/archive/pull/418/head
loader: add files for a hosted C program: fopen, fclose, fgets and perror (#402)
2026-11-24 22:11:50 -06:00
atharvranjan 44ac976291 Retain cache-hit assertions with generation-triggered source revalidation
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:10:24 -06:00
atharvranjan 0bd8e19aac Merge pull request #281 from MacosPorters/archive/pull/401/head
loader: add standard output and printf formatting for a hosted C program (#400)
2026-11-24 22:08:23 -06:00
atharvranjan e93509ef5b Merge pull request #280 from MacosPorters/archive/pull/399/head
loader: add exit, _exit and abort for a hosted C program (#395)
2026-11-24 22:04:34 -06:00
atharvranjan 8344e299c9 Merge pull request #277 from MacosPorters/archive/pull/393/head
loader: add program arguments for a hosted C program (#392)
2026-11-24 22:04:27 -06:00
atharvranjan 433dc43695 Merge pull request #273 from MacosPorters/archive/pull/385/head
loader: add nine C runtime startup services a hosted C program imports (#382)
2026-11-24 22:04:19 -06:00
atharvranjan a0f2d833aa Merge pull request #276 from MacosPorters/archive/pull/390/head
loader: add VirtualProtect, VirtualQuery and __C_specific_handler as stubs (#388)
2026-11-24 22:04:10 -06:00
atharvranjan 61afca42c9 Merge pull request #279 from MacosPorters/archive/pull/397/head
loader: run LOOP, LOOPE, LOOPNE and JRCXZ (#396)
2026-11-24 22:04:02 -06:00
atharvranjan be19e4e28f Merge pull request #275 from MacosPorters/archive/pull/389/head
loader: run LAHF and SAHF and report them in CPUID (#387)
2026-11-24 22:03:56 -06:00
atharvranjan 33ccf7fd55 Merge pull request #271 from MacosPorters/archive/pull/381/head
loader: add FNINIT and the x87 control, status and tag words (#378)
2026-11-24 22:03:49 -06:00
atharvranjan bb62353cfe Merge pull request #274 from MacosPorters/archive/pull/386/head
loader: raise #GP for instructions longer than 15 bytes (#384)
2026-11-24 22:03:42 -06:00
atharvranjan 1f2e7d3bb6 Merge pull request #272 from MacosPorters/archive/pull/383/head
bench: compare two dbt_bench JSON results (#114)
2026-11-24 22:03:34 -06:00
atharvranjan b5b646a58d Warm differential-test caches within the same guest address space
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:02:34 -06:00
atharvranjan 4314071ac7 Validate DBT cache identity with executable generations instead of byte scans
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:59:14 -06:00
atharvranjan 4e15e5f43b Synchronize PR #275 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:16 -06:00
atharvranjan cf4010ba94 Synchronize PR #271 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:14 -06:00
atharvranjan b9e6a9d365 Synchronize PR #274 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:12 -06:00
atharvranjan a1a1020ebd Synchronize PR #272 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:10 -06:00
atharvranjan e755ee94ed Merge pull request #264 from MacosPorters/archive/pull/340/head
benchmarks: measure gfx1030 metadata identification
2026-11-24 21:57:34 -06:00
atharvranjan e289318132 Merge pull request #267 from MacosPorters/archive/pull/359/head
loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
2026-11-24 21:49:39 -06:00
atharvranjan f685b54e32 Merge pull request #268 from MacosPorters/archive/pull/369/head
loader: add Win64 service ABI preservation tests (#201)
2026-11-24 21:48:28 -06:00
atharvranjan 0690a3ecb4 Merge pull request #284 from MacosPorters/archive/pull/422/head
loader: copy mid-size TLS templates into the zeroed block (#111)
2026-11-24 21:48:22 -06:00
atharvranjan 7286989296 Merge pull request #270 from MacosPorters/archive/pull/374/head
Fix ARM64 variable shift register encoding
2026-11-24 21:47:03 -06:00
Ranveer Soni 4cc703d566 Merge branch 'main' into fix/84-dbt-stale-code-cache 2026-11-25 07:02:16 +05:30
atharvranjan e856f080d1 dbt: retranslate cached blocks when guest code changes (#84)
Each cached block keeps the guest bytes it was translated from and is compared with the current executable bytes on every lookup.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 14:17:40 -06:00
Swastickc b09d96fd62 bench: measure Metal startup in fresh processes and repeated runs (#178)
Add `xenora-bench startup`. It checks one manifest fixture against the
independent reference, then times it phase by phase in two regimes: a
series of fresh child processes that each create the Metal device and
queue, translate and run the fixture once, and one process that
repeats the run. Phases are launch to main, device and queue,
translation, library, pipeline, submission, GPU and readback, reported
as median, p90, p99 and maximum, with raw fresh samples in launch
order.

Every sample must produce the expected output. A wrong output, a
failed or hung child (killed after 60 s) or a damaged sample line
stops the run before any result is written. Children inherit the
environment so the recorded MTL_* validation state applies to both
regimes.

Document the method and one recorded release run on an Apple M4 in
docs/testing/benchmarks.md, and add a changelog entry. Measurement
only.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-24 23:59:59 +05:30
13 changed files with 1108 additions and 28 deletions

No files matched your search

+11 -1
View File
@@ -33,6 +33,8 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version.
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
@@ -40,6 +42,14 @@ remains unsupported.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation.
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
submission, GPU, readback), with median, p90, p99 and maximum. Every sample must produce the fixture's
expected output, or the run stops without writing results. `docs/testing/benchmarks.md` records one
release run on an Apple M4: a fresh process took about 43 ms (median), 36 ms of it creating the Metal
device and queue, while repeated runs in one process needed about 0.2 ms of host submission. Measurement
only; nothing was optimized.
- Added an opt-in, budgeted staged upload for RGBA8 textures (#144). `MetalRgba8Texture::upload_staged` fills a
Private-storage texture through one reused Shared staging buffer that never exceeds a `StagingBudget`. It
copies whole-row bands with a blit encoder and reuses the buffer only after the previous command buffer has
@@ -59,7 +69,7 @@ remains unsupported.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify stack alignment before CALL and at callee entry (`RSP % 16 == 8`), accessibility of the caller-allocated 32-byte shadow space, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
+17 -2
View File
@@ -162,10 +162,21 @@ struct BatchResult {
pipelined: Stats,
}
mod startup;
mod startup_report;
fn main() -> Result<(), Box<dyn Error>> {
// Taken before anything else so a fresh startup child can report the time
// from its parent's spawn to `main`.
let entered = SystemTime::now();
let mut args = std::env::args().skip(1).peekable();
match args.peek().map(String::as_str) {
Some("startup") => return startup::run(args.skip(1)),
Some("startup-child") => return startup::child(entered, args.skip(1)),
_ => {}
}
let mut output = PathBuf::from("benchmarks/results");
let mut reps = DEFAULT_REPS;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--output" => {
@@ -179,7 +190,11 @@ fn main() -> Result<(), Box<dyn Error>> {
.map_err(|_| "--reps must be a positive integer")?;
}
"--help" | "-h" => {
println!("usage: xenora-bench [--output DIR] [--reps N]");
println!(
"usage: xenora-bench [--output DIR] [--reps N]\n \
xenora-bench startup [--fixture NAME] [--words N] [--processes N] \
[--reps N] [--output DIR]"
);
return Ok(());
}
other => return Err(format!("unknown argument {other}").into()),
+405
View File
@@ -0,0 +1,405 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Metal startup distributions: fresh processes versus repeated submissions (#178).
//!
//! `xenora-bench startup` checks one manifest fixture against the independent
//! reference, then measures it two ways:
//!
//! - **Fresh process.** It launches its own executable `--processes` times. Each
//! child creates the Metal device and queue, translates the fixture, runs it
//! once with `run_words_profiled`, checks the output and prints one sample line.
//! - **Repeated.** In this process it creates one device, then translates and runs
//! the same fixture `--reps` times. The first run is reported on its own.
//!
//! Every sample must produce the expected words. One wrong output, failed child or
//! unparsable sample line stops the run before anything is written. The
//! numbers describe this host only; two distributions do not explain each other.
use std::error::Error;
use std::fs;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, ENTRY_POINT, compile};
use crate::startup_report::Report;
use crate::{Fixture, Metadata, expand, parse_manifest, percentile, slug};
const DEFAULT_PROCESSES: usize = 30;
const DEFAULT_REPS: usize = 100;
/// A fresh process that has not exited by then is killed and fails the run.
const CHILD_TIMEOUT: Duration = Duration::from_secs(60);
/// Phases of one run, in seconds. `spawn_to_main` exists only for fresh processes.
pub(crate) const PHASES: [&str; 8] = [
"spawn_to_main",
"device",
"translate",
"library",
"pipeline",
"submit",
"gpu",
"readback",
];
/// One run's phase timings, indexed like [`PHASES`].
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub(crate) struct Sample(pub(crate) [f64; PHASES.len()]);
impl Sample {
fn line(&self) -> String {
let fields: Vec<String> = PHASES
.iter()
.zip(self.0)
.map(|(name, value)| format!("{name}={value:e}"))
.collect();
format!("startup-sample {}", fields.join(" "))
}
/// Parses exactly the line [`Sample::line`] prints: every phase once, in order.
pub(crate) fn parse(line: &str) -> Result<Self, String> {
let rest = line
.strip_prefix("startup-sample ")
.ok_or("missing startup-sample prefix")?;
let fields: Vec<&str> = rest.split(' ').collect();
if fields.len() != PHASES.len() {
return Err(format!(
"expected {} fields, got {}",
PHASES.len(),
fields.len()
));
}
let mut sample = Self::default();
for (i, (field, name)) in fields.iter().zip(PHASES).enumerate() {
let value = field
.strip_prefix(name)
.and_then(|v| v.strip_prefix('='))
.ok_or_else(|| format!("field {i} is not {name}=<seconds>"))?;
let value: f64 = value.parse().map_err(|_| format!("bad {name} value"))?;
if !value.is_finite() || value < 0.0 {
return Err(format!("{name} must be finite and non-negative"));
}
sample.0[i] = value;
}
Ok(sample)
}
}
/// Median, tail and extremes of one phase.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Summary {
pub(crate) n: usize,
pub(crate) min: f64,
pub(crate) median: f64,
pub(crate) p90: f64,
pub(crate) p99: f64,
pub(crate) max: f64,
}
pub(crate) fn summarize(values: &[f64]) -> Option<Summary> {
if values.is_empty() {
return None;
}
let mut sorted = values.to_vec();
sorted.sort_by(f64::total_cmp);
Some(Summary {
n: sorted.len(),
min: sorted[0],
median: percentile(&sorted, 0.5),
p90: percentile(&sorted, 0.9),
p99: percentile(&sorted, 0.99),
max: sorted[sorted.len() - 1],
})
}
struct Options {
fixture: Option<String>,
words: Option<usize>,
processes: usize,
reps: usize,
output: PathBuf,
}
fn count(value: Option<String>, flag: &str) -> Result<usize, String> {
let n: usize = value
.ok_or_else(|| format!("{flag} needs a count"))?
.parse()
.map_err(|_| format!("{flag} must be a positive integer"))?;
if n == 0 {
return Err(format!("{flag} must be at least 1"));
}
Ok(n)
}
fn parse_options(mut args: impl Iterator<Item = String>) -> Result<Options, String> {
let mut options = Options {
fixture: None,
words: None,
processes: DEFAULT_PROCESSES,
reps: DEFAULT_REPS,
output: PathBuf::from("artifacts/startup"),
};
while let Some(arg) = args.next() {
match arg.as_str() {
"--fixture" => options.fixture = Some(args.next().ok_or("--fixture needs a name")?),
"--words" => options.words = Some(count(args.next(), "--words")?),
"--processes" => options.processes = count(args.next(), "--processes")?,
"--reps" => options.reps = count(args.next(), "--reps")?,
"--output" => {
options.output = PathBuf::from(args.next().ok_or("--output needs a path")?);
}
other => return Err(format!("unknown startup argument {other}")),
}
}
Ok(options)
}
/// The fixture to time and its word count, after the reference agrees with it.
fn select(options: &Options) -> Result<(Fixture, usize), Box<dyn Error>> {
let fixtures = parse_manifest(&fs::read_to_string("benchmarks/manifest.toml")?)?;
let fixture = match &options.fixture {
Some(name) => fixtures.into_iter().find(|f| &f.name == name),
None => fixtures.into_iter().next(),
}
.ok_or("fixture not found in benchmarks/manifest.toml")?;
let code = fs::read(&fixture.path)?;
let reference = xenora_ref::execute(&code, &fixture.input).map_err(|e| e.to_string())?;
if reference != fixture.expected {
return Err("reference disagrees with hand-derived expected values".into());
}
let words = options
.words
.unwrap_or_else(|| *fixture.sizes.first().unwrap_or(&fixture.input.len()));
Ok((fixture, words))
}
/// Translates and runs the fixture once on `metal`, checking the output.
fn run_once(
metal: &NativeCompute,
fixture: &Fixture,
words: usize,
sample: &mut Sample,
) -> Result<(), Box<dyn Error>> {
let input = expand(&fixture.input, words);
let expected = expand(&fixture.expected, words);
let start = Instant::now();
let code = fs::read(&fixture.path)?;
let compiled = compile(Architecture::Gfx1030, &code).map_err(|e| e.to_string())?;
sample.0[2] = start.elapsed().as_secs_f64();
let profile = metal
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
.map_err(|e| e.to_string())?;
if profile.output != expected {
return Err(format!("{} output disagrees with known answers", fixture.name).into());
}
sample.0[3] = profile.library_seconds;
sample.0[4] = profile.pipeline_seconds;
sample.0[5] = profile.host_seconds - profile.library_seconds - profile.pipeline_seconds;
sample.0[6] = profile.gpu_seconds;
sample.0[7] = profile.readback_seconds;
Ok(())
}
fn unix_nanos(time: SystemTime) -> u128 {
time.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos())
}
/// Entry point of one fresh child process, called first thing in `main`.
///
/// `entered` is the wall-clock time at `main`; the parent passes the wall-clock
/// time just before it spawned this process.
pub(crate) fn child(
entered: SystemTime,
mut args: impl Iterator<Item = String>,
) -> Result<(), Box<dyn Error>> {
let spawned: u128 = args.next().ok_or("missing spawn time")?.parse()?;
let options = parse_options(args)?;
let (fixture, words) = select(&options)?;
let mut sample = Sample::default();
sample.0[0] = unix_nanos(entered).saturating_sub(spawned) as f64 / 1e9;
let start = Instant::now();
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
sample.0[1] = start.elapsed().as_secs_f64();
run_once(&metal, &fixture, words, &mut sample)?;
println!("{}", sample.line());
Ok(())
}
fn forwarded(fixture: &Fixture, words: usize) -> Vec<String> {
vec![
"--fixture".into(),
fixture.name.clone(),
"--words".into(),
words.to_string(),
]
}
/// Runs one fresh child and returns its spawn-to-exit wall time and stdout.
///
/// The child inherits this process's environment on purpose, so its `MTL_*`
/// validation settings are the ones the run's metadata records.
fn spawn_child(
exe: &std::path::Path,
fixture: &Fixture,
words: usize,
) -> Result<(f64, String), Box<dyn Error>> {
let started = Instant::now();
let spawned = unix_nanos(SystemTime::now());
let mut child = Command::new(exe)
.arg("startup-child")
.arg(spawned.to_string())
.args(forwarded(fixture, words))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
// Drain both pipes while waiting, so a child that writes more than a pipe
// buffer (validation logs, for example) cannot block and look like a hang.
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
std::thread::spawn(move || {
let mut text = String::new();
if let Some(mut pipe) = pipe {
let _ = pipe.read_to_string(&mut text);
}
text
})
};
let out = drain(child.stdout.take().map(|p| Box::new(p) as _));
let err = drain(child.stderr.take().map(|p| Box::new(p) as _));
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if started.elapsed() > CHILD_TIMEOUT {
child.kill()?;
child.wait()?;
return Err(format!("no exit within {} s", CHILD_TIMEOUT.as_secs()).into());
}
std::thread::sleep(Duration::from_millis(1));
};
let seconds = started.elapsed().as_secs_f64();
let stdout = out.join().map_err(|_| "stdout reader panicked")?;
let stderr = err.join().map_err(|_| "stderr reader panicked")?;
if !status.success() {
return Err(format!("{status}: {}", stderr.trim()).into());
}
Ok((seconds, stdout))
}
/// Runs both regimes and writes `startup.json` and `report.md`.
pub(crate) fn run(args: impl Iterator<Item = String>) -> Result<(), Box<dyn Error>> {
let options = parse_options(args)?;
let (fixture, words) = select(&options)?;
let exe = std::env::current_exe()?;
let mut fresh = Vec::with_capacity(options.processes);
let mut wall = Vec::with_capacity(options.processes);
for i in 0..options.processes {
let (seconds, stdout) = spawn_child(&exe, &fixture, words)
.map_err(|e| format!("fresh process {i} failed: {e}"))?;
wall.push(seconds);
let line = stdout
.lines()
.find(|l| l.starts_with("startup-sample "))
.ok_or_else(|| format!("fresh process {i} printed no sample"))?;
fresh.push(Sample::parse(line).map_err(|e| format!("fresh process {i}: {e}"))?);
}
let mut first = Sample::default();
let start = Instant::now();
let metal = NativeCompute::new().map_err(|e| e.to_string())?;
first.0[1] = start.elapsed().as_secs_f64();
run_once(&metal, &fixture, words, &mut first)?;
let mut repeated = Vec::with_capacity(options.reps);
for _ in 0..options.reps {
let mut sample = Sample::default();
run_once(&metal, &fixture, words, &mut sample)?;
repeated.push(sample);
}
let metadata = Metadata::collect(&metal.device_name(), options.reps);
let dir = options
.output
.join(slug(&metadata.device))
.join(&metadata.run_id);
fs::create_dir_all(&dir)?;
fs::write(dir.join("metadata.json"), metadata.to_json())?;
let report = Report {
fixture: &fixture.name,
words,
fresh: &fresh,
wall: &wall,
first: &first,
repeated: &repeated,
};
fs::write(dir.join("startup.json"), report.json())?;
let markdown = report.markdown(&metadata);
fs::write(dir.join("report.md"), &markdown)?;
println!("{markdown}");
println!("Startup results written to {}", dir.display());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sample_lines_round_trip() {
let sample = Sample([0.5, 1e-3, 2.5e-4, 0.0, 7.0, 1e-9, 3.25, 42.0]);
assert_eq!(Sample::parse(&sample.line()), Ok(sample));
}
#[test]
fn sample_lines_reject_damaged_input() {
let line = Sample([1.0; PHASES.len()]).line();
assert!(Sample::parse(&line.replacen("startup-sample", "sample", 1)).is_err());
assert!(Sample::parse(&line.replacen("device=", "devise=", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=-1e0", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=NaN", 1)).is_err());
assert!(Sample::parse(&line.replacen("gpu=1e0", "gpu=x", 1)).is_err());
assert!(Sample::parse(line.rsplit_once(' ').unwrap().0).is_err());
assert!(Sample::parse(&format!("{line} extra=1")).is_err());
// Phases out of order are refused even when every name is present.
let swapped = line
.replacen("device=", "TMP=", 1)
.replacen("translate=", "device=", 1)
.replacen("TMP=", "translate=", 1);
assert!(Sample::parse(&swapped).is_err());
}
#[test]
fn summary_uses_interpolated_percentiles() {
// 1..=100: position 0.9 * 99 = 89.1 lies between 90 and 91, and
// 0.99 * 99 = 98.01 between 99 and 100.
let values: Vec<f64> = (1..=100).rev().map(f64::from).collect();
let s = summarize(&values).unwrap();
assert_eq!((s.n, s.min, s.max), (100, 1.0, 100.0));
assert!((s.median - 50.5).abs() < 1e-9);
assert!((s.p90 - 90.1).abs() < 1e-9);
assert!((s.p99 - 99.01).abs() < 1e-9);
assert_eq!(summarize(&[]), None);
let one = summarize(&[3.0]).unwrap();
assert_eq!(
(one.median, one.p90, one.p99, one.max),
(3.0, 3.0, 3.0, 3.0)
);
}
#[test]
fn options_reject_bad_counts_and_flags() {
let parse = |args: &[&str]| parse_options(args.iter().map(|s| s.to_string()));
let defaults = parse(&[]).unwrap();
assert_eq!(
(defaults.processes, defaults.reps),
(DEFAULT_PROCESSES, DEFAULT_REPS)
);
let set = parse(&["--processes", "3", "--reps", "5", "--words", "64"]).unwrap();
assert_eq!((set.processes, set.reps, set.words), (3, 5, Some(64)));
assert!(parse(&["--processes", "0"]).is_err());
assert!(parse(&["--reps", "-1"]).is_err());
assert!(parse(&["--words"]).is_err());
assert!(parse(&["--fast"]).is_err());
}
}
+146
View File
@@ -0,0 +1,146 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! JSON and markdown output of `xenora-bench startup` (#178).
use std::fmt::Write as _;
use crate::startup::{PHASES, Sample, Summary, summarize};
use crate::{Metadata, json_str};
pub(crate) struct Report<'a> {
pub(crate) fixture: &'a str,
pub(crate) words: usize,
pub(crate) fresh: &'a [Sample],
pub(crate) wall: &'a [f64],
pub(crate) first: &'a Sample,
pub(crate) repeated: &'a [Sample],
}
fn column(samples: &[Sample], phase: usize) -> Vec<f64> {
samples.iter().map(|s| s.0[phase]).collect()
}
fn summary_json(summary: Option<Summary>) -> String {
summary.map_or_else(
|| "null".to_string(),
|s| {
format!(
"{{\"n\": {}, \"min\": {:e}, \"median\": {:e}, \"p90\": {:e}, \"p99\": {:e}, \"max\": {:e}}}",
s.n, s.min, s.median, s.p90, s.p99, s.max
)
},
)
}
impl Report<'_> {
pub(crate) fn json(&self) -> String {
let mut out = format!(
"{{\n \"fixture\": {},\n \"words\": {},\n \"process_wall\": {},\n",
json_str(self.fixture),
self.words,
summary_json(summarize(self.wall))
);
for (regime, samples) in [("fresh", self.fresh), ("repeated", self.repeated)] {
let _ = writeln!(out, " \"{regime}\": {{");
for (i, phase) in PHASES.iter().enumerate() {
let comma = if i + 1 < PHASES.len() { "," } else { "" };
let summary = if regime == "repeated" && i < 2 {
None
} else {
summarize(&column(samples, i))
};
let _ = writeln!(out, " \"{phase}\": {}{comma}", summary_json(summary));
}
out.push_str(" },\n");
}
let first: Vec<String> = PHASES
.iter()
.zip(self.first.0)
.skip(1)
.map(|(p, v)| format!("\"{p}\": {v:e}"))
.collect();
let _ = writeln!(out, " \"first_in_process\": {{{}}},", first.join(", "));
// Raw fresh-process samples in launch order, so a cold first process
// (for example an empty Metal shader cache) stays visible.
let rows: Vec<String> = self
.fresh
.iter()
.zip(self.wall)
.map(|(sample, wall)| {
let phases: Vec<String> = sample.0.iter().map(|v| format!("{v:e}")).collect();
format!("[{}, {wall:e}]", phases.join(", "))
})
.collect();
let _ = writeln!(
out,
" \"fresh_samples_columns\": [{}, \"process_wall\"],\n \"fresh_samples\": [\n {}\n ]\n}}",
PHASES
.iter()
.map(|p| json_str(p))
.collect::<Vec<_>>()
.join(", "),
rows.join(",\n ")
);
out
}
pub(crate) fn markdown(&self, metadata: &Metadata) -> String {
let ms = |v: f64| format!("{:.3}", v * 1e3);
let mut out = format!(
"# Metal startup: `{}`, {} words\n\nDevice {}, {} build, commit `{}`, API validation `{}`, shader validation `{}`, power `{}`, thermal `{}`.\n\nAll values in milliseconds. Fresh: {} processes. Repeated: {} runs after the first in one process. Every sample produced the expected output.\n\n| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n",
self.fixture,
self.words,
metadata.device,
metadata.profile,
metadata.commit,
metadata.api_validation,
metadata.shader_validation,
metadata.power,
metadata.thermal,
self.fresh.len(),
self.repeated.len(),
);
for (i, phase) in PHASES.iter().enumerate() {
let fresh = summarize(&column(self.fresh, i));
let repeated = (i >= 2)
.then(|| summarize(&column(self.repeated, i)))
.flatten();
let cells = |s: Option<Summary>| {
s.map_or_else(
|| "– | – | – | –".to_string(),
|s| {
format!(
"{} | {} | {} | {}",
ms(s.median),
ms(s.p90),
ms(s.p99),
ms(s.max)
)
},
)
};
let first = if i == 0 {
"–".to_string()
} else {
ms(self.first.0[i])
};
let _ = writeln!(
out,
"| `{phase}` | {} | {first} | {} |",
cells(fresh),
cells(repeated)
);
}
if let Some(s) = summarize(self.wall) {
let _ = writeln!(
out,
"| process wall (spawn to exit) | {} | {} | {} | {} | – | – | – | – | – |",
ms(s.median),
ms(s.p90),
ms(s.p99),
ms(s.max)
);
}
out
}
}
+4 -2
View File
@@ -14,8 +14,9 @@
//! refused, with exit status 1, unless both runs used the same host, workload,
//! build settings and sample counts.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
//! Report, comparison and percentile tests run in ordinary workspace tests
//! through `tests/dbt_benchmark_report.rs`. The benchmark target itself disables
//! Cargo's test harness. To run its tests directly, build with
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
//! and run the executable named by the benchmark's compiler-artifact message.
@@ -982,6 +983,7 @@ mod tests {
blocks_compiled: 626,
cache_hits: 0,
cache_misses: 626,
blocks_invalidated: 0,
native_bytes_emitted: 245_168,
dbt_dispatches: 626,
instructions_executed: 10_002,
+278 -17
View File
@@ -15,7 +15,7 @@ use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment, decode};
use crate::x86_exec;
use crate::x86_table::{FORMS, Op};
use std::collections::HashMap;
use std::{collections::HashMap, sync::Arc};
const MAX_BLOCK_INSTRUCTIONS: usize = 16;
@@ -29,6 +29,9 @@ pub struct DbtMetrics {
pub blocks_compiled: usize,
pub cache_hits: usize,
pub cache_misses: usize,
/// Cached blocks discarded because their guest bytes or executable mappings
/// changed. Each also counts as a cache miss.
pub blocks_invalidated: usize,
pub native_bytes_emitted: usize,
pub dbt_dispatches: usize,
pub instructions_executed: usize,
@@ -37,11 +40,42 @@ pub struct DbtMetrics {
pub service_calls: usize,
}
/// A translated block and its executable-memory generation.
///
/// Guest stores into executable memory (Intel SDM Vol. 3A 11.6), executable
/// mapping changes and another address space invalidate the retained token.
/// An unchanged token takes a constant-time check. After a generation or address
/// space change, bytes and execute permissions are revalidated once before an
/// identical translation may be reused in that generation.
/// Validation occurs at dispatch boundaries: a store into the currently running
/// block's later instructions still needs a separate dispatch-boundary design.
struct CachedBlock {
code: *const u8,
generation: Arc<()>,
start: u64,
source: Box<[u8]>,
}
impl CachedBlock {
fn is_current(&mut self, memory: &GuestMemory) -> bool {
if memory.code_is_current(&self.generation) {
return true;
}
if !self.source.iter().enumerate().all(|(offset, &byte)| {
matches!(memory.fetch_instruction_byte(self.start.wrapping_add(offset as u64)), Ok(current) if current == byte)
}) {
return false;
}
self.generation = memory.code_generation();
true
}
}
/// Dynamic Binary Translator and native execution runtime.
pub struct DbtEngine {
jit: JitMemory,
block_cache: HashMap<u64, *const u8>,
limited_block_cache: HashMap<(u64, usize), *const u8>,
block_cache: HashMap<u64, CachedBlock>,
limited_block_cache: HashMap<(u64, usize), CachedBlock>,
assembler: Arm64Assembler,
/// Decoded instructions that emitted helper calls point into.
decoded_blocks: Vec<Box<[Insn]>>,
@@ -245,26 +279,34 @@ impl DbtEngine {
block_limit: usize,
) -> Result<*const u8, ExitReason> {
if block_limit == MAX_BLOCK_INSTRUCTIONS {
if let Some(&fn_ptr) = self.block_cache.get(&rip) {
self.metrics.cache_hits += 1;
return Ok(fn_ptr);
if let Some(cached) = self.block_cache.get_mut(&rip) {
if cached.is_current(memory) {
self.metrics.cache_hits += 1;
return Ok(cached.code);
}
self.metrics.blocks_invalidated += 1;
}
self.metrics.cache_misses += 1;
let compiled_ptr = self.compile_block(rip, memory, block_limit)?;
self.block_cache.insert(rip, compiled_ptr);
return Ok(compiled_ptr);
let compiled = self.compile_block(rip, memory, block_limit)?;
let code = compiled.code;
self.block_cache.insert(rip, compiled);
return Ok(code);
}
// Keep budget-limited blocks separate so they cannot shorten a later run.
let key = (rip, block_limit);
if let Some(&fn_ptr) = self.limited_block_cache.get(&key) {
self.metrics.cache_hits += 1;
return Ok(fn_ptr);
if let Some(cached) = self.limited_block_cache.get_mut(&key) {
if cached.is_current(memory) {
self.metrics.cache_hits += 1;
return Ok(cached.code);
}
self.metrics.blocks_invalidated += 1;
}
self.metrics.cache_misses += 1;
let compiled_ptr = self.compile_block(rip, memory, block_limit)?;
self.limited_block_cache.insert(key, compiled_ptr);
Ok(compiled_ptr)
let compiled = self.compile_block(rip, memory, block_limit)?;
let code = compiled.code;
self.limited_block_cache.insert(key, compiled);
Ok(code)
}
fn compile_block(
@@ -272,7 +314,7 @@ impl DbtEngine {
start_rip: u64,
memory: &GuestMemory,
block_limit: usize,
) -> Result<*const u8, ExitReason> {
) -> Result<CachedBlock, ExitReason> {
// Decode the whole block first: lowering needs to know whether a later
// instruction observes the flags an earlier one produces.
let mut decoded = Vec::with_capacity(block_limit);
@@ -351,8 +393,17 @@ impl DbtEngine {
.map_err(|_| ExitReason::JitCacheExhausted)?;
self.metrics.blocks_compiled += 1;
self.metrics.native_bytes_emitted += asm.instructions().len() * 4;
let source = (0..rip.wrapping_sub(start_rip))
.map(|offset| memory.fetch_instruction_byte(start_rip.wrapping_add(offset)))
.collect::<Result<Box<[u8]>, _>>()
.map_err(ExitReason::MemoryFault)?;
self.decoded_blocks.push(insns);
Ok(emitted)
Ok(CachedBlock {
code: emitted,
generation: memory.code_generation(),
start: start_rip,
source,
})
}
}
@@ -1569,6 +1620,216 @@ mod tests {
)
}
/// `mov eax, imm32; hlt`, with the immediate at `ENTRY + 1`.
fn mov_eax(imm: u8) -> [u8; 6] {
[0xB8, imm, 0x00, 0x00, 0x00, 0xF4]
}
fn writable_fixture(code: &[u8]) -> (DbtEngine, GuestMemory) {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
ENTRY,
code.len(),
MemoryPermissions::READ_WRITE_EXECUTE,
code,
)
.unwrap();
(DbtEngine::new(64 * 1024).unwrap(), memory)
}
fn rax_after_run(engine: &mut DbtEngine, memory: &mut GuestMemory, limit: usize) -> u64 {
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, memory, limit);
assert_eq!(result.exit_reason, ExitReason::Halt);
cpu.get(Register::Rax)
}
#[test]
fn unchanged_code_stays_cached() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert_eq!(engine.metrics.blocks_compiled, 1);
assert_eq!(engine.metrics.cache_hits, 1);
assert_eq!(engine.metrics.blocks_invalidated, 0);
}
#[test]
fn data_writes_and_allocations_do_not_invalidate_executable_code() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
memory
.map_region(ENTRY + 0x1000, 8, MemoryPermissions::READ_WRITE)
.unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
for value in 0..64 {
memory.write_u64(ENTRY + 0x1000, value).unwrap();
let allocation = memory
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE)
.unwrap();
assert!(memory.release_virtual_allocation(allocation));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
}
assert_eq!(engine.metrics.blocks_compiled, 1);
assert_eq!(engine.metrics.cache_hits, 64);
assert_eq!(engine.metrics.blocks_invalidated, 0);
}
#[test]
fn cloned_address_spaces_diverge_when_executable_code_changes() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
let mut cloned = memory.clone();
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
memory.write_u8(ENTRY + 1, 7).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 7);
// A deep clone shares the proven identical executable snapshot. The
// write in the original space must still force retranslation there.
assert_eq!(engine.metrics.blocks_compiled, 2);
assert_eq!(engine.metrics.cache_hits, 2);
}
#[test]
fn executable_bypass_writes_invalidate_cached_translations() {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
ENTRY,
8,
MemoryPermissions::READ_EXECUTE,
&[0xB8, 1, 0, 0, 0, 0xF4, 0, 0],
)
.unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert!(memory.write_u32(ENTRY + 1, 9).is_err());
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert_eq!(engine.metrics.blocks_invalidated, 0);
memory
.write_u64_bypass(ENTRY, u64::from_le_bytes([0xB8, 2, 0, 0, 0, 0xF4, 0, 0]))
.unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
memory.write_u32_bypass(ENTRY + 1, 3).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 3);
assert_eq!(engine.metrics.blocks_invalidated, 2);
}
#[test]
fn executable_writes_crossing_regions_invalidate_cached_translations() {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, 2, MemoryPermissions::READ_WRITE_EXECUTE, &[0xB8, 1])
.unwrap();
memory
.map_region_with_data(
ENTRY + 2,
4,
MemoryPermissions::READ_WRITE_EXECUTE,
&[0, 0, 0, 0xF4],
)
.unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
memory.write_u32(ENTRY + 1, 9).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 9);
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn remapped_non_executable_memory_cannot_reuse_a_translation() {
let mut memory = GuestMemory::new();
let base = memory
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE_EXECUTE)
.unwrap();
memory.write_bytes(base, &mov_eax(1)).unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
let mut cpu = CpuState::new(base, 0);
assert_eq!(
engine.run(&mut cpu, &mut memory, 16).exit_reason,
ExitReason::Halt
);
assert!(memory.release_virtual_allocation(base));
assert_eq!(
memory.map_virtual_allocation(base, 4096, MemoryPermissions::READ_WRITE),
Ok(base)
);
memory.write_bytes(base, &mov_eax(1)).unwrap();
let mut cpu = CpuState::new(base, 0);
assert!(matches!(
engine.run(&mut cpu, &mut memory, 16).exit_reason,
ExitReason::MemoryFault(_)
));
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn repeated_code_rewrites_report_bounded_jit_cache_exhaustion() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
for value in 0..16_384u32 {
memory.write_u32(ENTRY + 1, value).unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut memory, 16);
if result.exit_reason == ExitReason::JitCacheExhausted {
return;
}
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(cpu.get(Register::Rax), u64::from(value));
}
panic!("rewritten blocks unexpectedly avoided the bounded JIT capacity");
}
#[test]
fn rewritten_code_is_translated_again() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
memory.write_bytes(ENTRY + 1, &[2]).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
assert_eq!(engine.metrics.blocks_compiled, 2);
assert_eq!(engine.metrics.blocks_invalidated, 1);
// The new translation is cached in turn.
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
assert_eq!(engine.metrics.blocks_compiled, 2);
}
#[test]
fn rewriting_the_last_byte_of_a_block_is_detected() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
// HLT becomes NOP, so the block now runs off the end of the mapping.
memory.write_bytes(ENTRY + 5, &[0x90]).unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut memory, 16);
assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_)));
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn budget_limited_block_is_checked_against_current_bytes() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
for expected in [1, 3] {
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut memory, 1);
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(cpu.get(Register::Rax), expected);
memory.write_bytes(ENTRY + 1, &[3]).unwrap();
}
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn another_address_space_does_not_reuse_a_block() {
let (mut engine, mut first) = writable_fixture(&mov_eax(1));
let (_, mut second) = writable_fixture(&mov_eax(7));
assert_eq!(rax_after_run(&mut engine, &mut first, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut second, 16), 7);
let mut unmapped = GuestMemory::new();
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut unmapped, 16);
assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_)));
}
#[test]
fn cached_block_obeys_remaining_budget() {
let code = [
+57 -3
View File
@@ -5,7 +5,7 @@
//! Provides isolated, page-aligned guest virtual memory with permission checking
//! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks.
use std::{fmt, ops::Range};
use std::{fmt, ops::Range, sync::Arc};
pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536;
@@ -119,8 +119,13 @@ impl MappedRegion {
}
/// Guest virtual memory address space.
#[derive(Default, Clone)]
#[derive(Default)]
pub struct GuestMemory {
// A retained token identifies a validated executable snapshot. Independent
// address spaces get distinct tokens. A deep clone may share its identical
// snapshot; an executable mutation detaches only the changed address space.
// Cached translations retain tokens, preventing allocator-address reuse.
executable_generation: Arc<()>,
regions: Vec<MappedRegion>,
private_heaps: std::collections::BTreeSet<u64>,
private_heap_serial: u64,
@@ -130,7 +135,32 @@ pub struct GuestMemory {
std::collections::BTreeMap<(u64, u64), crate::imports::CallbackFrame>,
}
impl Clone for GuestMemory {
fn clone(&self) -> Self {
Self {
executable_generation: Arc::clone(&self.executable_generation),
regions: self.regions.clone(),
private_heaps: self.private_heaps.clone(),
private_heap_serial: self.private_heap_serial,
crt_errno: self.crt_errno.clone(),
callback_frames: self.callback_frames.clone(),
}
}
}
impl GuestMemory {
pub(crate) fn code_generation(&self) -> Arc<()> {
Arc::clone(&self.executable_generation)
}
pub(crate) fn code_is_current(&self, generation: &Arc<()>) -> bool {
Arc::ptr_eq(&self.executable_generation, generation)
}
fn invalidate_executable_code(&mut self) {
self.executable_generation = Arc::new(());
}
/// Create a new empty guest address space.
pub fn new() -> Self {
Self::default()
@@ -197,6 +227,9 @@ impl GuestMemory {
allocation,
});
self.regions.sort_by_key(|r| r.base);
if permissions.execute && size != 0 {
self.invalidate_executable_code();
}
Ok(())
}
@@ -256,8 +289,14 @@ impl GuestMemory {
if !self.private_heaps.remove(&heap) {
return false;
}
let executable = self.regions.iter().any(|region| {
region.allocation == AllocationKind::Heap(heap) && region.permissions.execute
});
self.regions
.retain(|region| region.allocation != AllocationKind::Heap(heap));
if executable {
self.invalidate_executable_code();
}
true
}
@@ -377,10 +416,14 @@ impl GuestMemory {
if size < previous {
region.data.shrink_to_fit();
}
let executable = region.permissions.execute;
if destination != base {
region.base = destination;
self.regions.sort_by_key(|region| region.base);
}
if executable && (size != previous || destination != base) {
self.invalidate_executable_code();
}
Ok(destination)
}
@@ -420,7 +463,10 @@ impl GuestMemory {
else {
return false;
};
self.regions.remove(index);
let removed = self.regions.remove(index);
if removed.permissions.execute && !removed.data.is_empty() {
self.invalidate_executable_code();
}
true
}
@@ -510,11 +556,16 @@ impl GuestMemory {
required: Option<&'static str>,
) -> Result<(), MemoryError> {
let mut done = 0;
let mut executable = false;
for (index, offset, take) in self.resolve(address, src.len(), required)? {
executable |= take != 0 && self.regions[index].permissions.execute;
self.regions[index].data[offset..offset + take]
.copy_from_slice(&src[done..done + take]);
done += take;
}
if executable {
self.invalidate_executable_code();
}
Ok(())
}
@@ -524,6 +575,9 @@ impl GuestMemory {
&& self.regions[index].permissions.write
{
self.regions[index].data[range].copy_from_slice(src);
if !src.is_empty() && self.regions[index].permissions.execute {
self.invalidate_executable_code();
}
return Ok(());
}
self.write_checked(address, src, Some("write"))
+2 -3
View File
@@ -5723,10 +5723,9 @@ fn interpreter_executes_modified_code_after_a_jump() {
assert_eq!(self_modified_result(Engine::Interpreter), wanted);
}
/// Known defect: the DBT keeps running the block it translated before the store.
/// The DBT must not keep running the block it translated before the store (#84).
#[test]
#[ignore = "known defect (#155): the DBT keeps translated blocks after the guest rewrites their code"]
fn defect_dbt_executes_modified_code_after_a_jump() {
fn dbt_executes_modified_code_after_a_jump() {
for engine in [Engine::Dbt, Engine::DbtStepped] {
let wanted = (1, 2, ExitReason::Halt);
assert_eq!(self_modified_result(engine), wanted, "{engine:?}");
@@ -0,0 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Run the benchmark's report, comparison and percentile tests in normal CI.
//! Timing runs remain confined to the standalone benchmark entry point.
#[allow(dead_code)]
#[path = "../benches/dbt_bench.rs"]
mod benchmark;
+1
View File
@@ -45,6 +45,7 @@ Historical phase checkpoints retain their original evidence scope.
## Testing, validation, and benchmarks
- [Migrated pull-request integration review](testing/migration-pr-review.md) — Merge decisions, integration fixes, native verification and excluded concurrent work.
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
+1
View File
@@ -1,5 +1,6 @@
# Testing and acceptance
- [Migrated pull-request integration review](migration-pr-review.md) — Merge decisions, fixes, native verification and remaining scope limits.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](shader-form-acceptance.md) — Rule and evidence required to promote a form from local results to `fixture verified`.
- [Test inventory comparison](test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](x9-acceptance.md) — Native ARM64 results and unsupported cases.
+82
View File
@@ -76,6 +76,88 @@ cargo build --release -p xenora-benchmarks
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench --reps 7
```
## Startup distributions
`xenora-bench startup` measures what it costs to get one fixture result from
Metal, in two regimes:
- **Fresh process.** The harness launches its own executable `--processes`
times (default 30), one after another. Each child creates the Metal device and
queue, translates the fixture, runs it once and checks the output.
- **Repeated.** The harness process creates one device, runs the fixture once
(reported as *first in process*), then translates and runs it `--reps` more
times (default 100).
The fixture is the first one in `benchmarks/manifest.toml` unless `--fixture`
names another, at its smallest declared size unless `--words` sets one. The
independent reference must agree with the hand-derived expected values first,
and every sample in both regimes must produce the expected words. A wrong
output, a child that fails or does not exit within 60 seconds, or a damaged
sample line stops the run before anything is written.
| Phase | Source | Meaning |
| --- | --- | --- |
| `spawn_to_main` | wall clock, parent before spawn to child `main` | Process launch and Rust runtime start (fresh only) |
| `device` | host monotonic clock | `NativeCompute::new`: device and queue (fresh, and once in the repeated process) |
| `translate` | host monotonic clock | Read the fixture and run `xenora-shader::compile` |
| `library` | `RunProfile` | `newLibraryWithSource` |
| `pipeline` | `RunProfile` | Compute pipeline state creation |
| `submit` | `RunProfile` | `host` minus `library` and `pipeline`: buffers, encode, commit, wait |
| `gpu` | `GPUEndTime - GPUStartTime` | Command-buffer GPU execution |
| `readback` | `RunProfile` | Copy the output words back |
| process wall | host monotonic clock in the parent | Spawn to exit of one fresh child |
The report gives median, p90, p99 and maximum per phase. Percentiles
interpolate linearly, so with 30 processes p99 lies between the two largest
samples. `startup.json` also keeps every fresh sample in launch order.
Children inherit the parent's environment, so the `MTL_*` validation values in
`metadata.json` apply to both regimes. Results go to the ignored
`artifacts/startup/<hardware>/<run-id>/` unless `--output` says otherwise.
```sh
cargo build --release -p xenora-benchmarks
MTL_DEBUG_LAYER=0 MTL_SHADER_VALIDATION=0 ./target/release/xenora-bench startup
```
### Recorded run
This is the imported contributor's record for the named source revision.
The integration review does not reproduce or independently accept the full
measurement protocol below.
Run `1795544761`, Apple M4, release build of `0fdb995` plus this harness, API
and shader validation off, AC power, no thermal warnings, started right after
the release build. Fixture `add`, 4 words, 30 fresh processes, 100 repeated
runs. All values in milliseconds.
| Phase | Fresh median | Fresh p90 | Fresh p99 | Fresh max | First in process | Repeated median | Repeated p90 | Repeated p99 | Repeated max |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `spawn_to_main` | 2.746 | 3.133 | 5.325 | 6.198 | – | – | – | – | – |
| `device` | 35.762 | 38.770 | 41.060 | 41.864 | 32.802 | – | – | – | – |
| `translate` | 0.061 | 0.071 | 0.084 | 0.089 | 0.067 | 0.016 | 0.023 | 0.041 | 0.043 |
| `library` | 0.402 | 0.434 | 18.595 | 25.976 | 0.399 | 0.006 | 0.010 | 0.018 | 0.019 |
| `pipeline` | 0.363 | 0.401 | 0.623 | 0.708 | 0.342 | 0.013 | 0.021 | 0.031 | 0.043 |
| `submit` | 1.665 | 1.894 | 1.951 | 1.953 | 1.647 | 0.214 | 0.384 | 0.440 | 3.941 |
| `gpu` | 0.007 | 0.008 | 0.010 | 0.011 | 0.008 | 0.007 | 0.008 | 0.061 | 1.742 |
| `readback` | 0.001 | 0.001 | 0.002 | 0.002 | 0.001 | < 0.001 | < 0.001 | < 0.001 | < 0.001 |
| process wall (spawn to exit) | 43.225 | 46.770 | 68.236 | 75.958 | – | – | – | – | – |
Observations, without causal claims:
- Device and queue creation is the largest fresh-process phase, about 36 ms of a
43 ms median process. Within one process it is paid once.
- The `library` tail came from the first child launched after the build
(25.976 ms; the other 29 were 0.36–0.45 ms). A second run immediately after,
`1795544763`, had a fresh `library` maximum of 0.446 ms, with `device` median
36.414 ms and process-wall median 44.111 ms. This fits an on-disk Metal
compilation cache, but the run does not show that.
- After the first run in a process, `library` and `pipeline` fall to about
0.01 ms and `submit` to about 0.2 ms. The `gpu` time for this 4-word kernel is
at timer scale in both regimes.
Two runs on one host do not describe other Apple GPU generations, sustained
load, other fixtures or larger word counts.
## Limitations
The corpus currently covers three synthetic gfx1030 compute fixtures under the
+96
View File
@@ -0,0 +1,96 @@
# Migrated pull-request integration review
Reviewed on November 24, 2026 (America/Chicago). The initial inventory contained
23 open pull requests under `Arths17`, including the development-plan PR.
Twenty-two were merged after their updated heads passed the applicable GitHub
checks. Imported records retain their original author attribution and commits.
The maintainer authorized per-merge admin overrides for the review restriction.
The ARM64 build/test requirement, one-approval rule, code-owner review requirement
and enforcement for admins remain configured. Failed or pending checks were
resolved before merging. The conditional `verify` comment job is normally skipped;
that skip is not independent semantic verification.
## Results
All links below refer to the BetterXen repository.
| PR | Result | Integration work |
| --- | --- | --- |
| [#263](https://github.com/MacosPorters/betterxen/pull/263) | Pending | Pending: overlaps the contributor's live PR #290, excluded by the maintainer. |
| [#264](https://github.com/MacosPorters/betterxen/pull/264) | Merged; checks passed | Identification fixture runs in ordinary tests; benchmark-harness lint fixed. |
| [#265](https://github.com/MacosPorters/betterxen/pull/265) | Merged; checks passed | Bounded native texture staging; planner and Metal readback tests. |
| [#266](https://github.com/MacosPorters/betterxen/pull/266) | Merged; checks passed | Startup measurement harness; unit tests and correctness smoke run. |
| [#267](https://github.com/MacosPorters/betterxen/pull/267) | Merged; checks passed | Bounded flat draws and repeated-frame regressions. |
| [#268](https://github.com/MacosPorters/betterxen/pull/268) | Merged; checks passed | Windows x64 calling conventions; writable-home-slot regression and nonvolatile vector-register negative controls. |
| [#269](https://github.com/MacosPorters/betterxen/pull/269) | Merged; checks passed | Executable generations with source revalidation; original cache assertions preserved. |
| [#270](https://github.com/MacosPorters/betterxen/pull/270) | Merged; checks passed | ARM64 shift encoding and operand checks; draft marked ready. |
| [#271](https://github.com/MacosPorters/betterxen/pull/271) | Merged; checks passed | Floating-point unit initialization, combined decoder generation and preserved tests. |
| [#272](https://github.com/MacosPorters/betterxen/pull/272) | Merged; checks passed | Dynamic binary translation (DBT) report comparison and input validation. |
| [#273](https://github.com/MacosPorters/betterxen/pull/273) | Merged; checks passed | C startup service integration and registry regeneration. |
| [#274](https://github.com/MacosPorters/betterxen/pull/274) | Merged; checks passed | Instruction-length faults and precise retirement. |
| [#275](https://github.com/MacosPorters/betterxen/pull/275) | Merged; checks passed | Flag-transfer instructions; combined fixtures and supported-case expectations retained. |
| [#276](https://github.com/MacosPorters/betterxen/pull/276) | Merged; checks passed | Explicitly unsupported service stubs and combined registry. |
| [#277](https://github.com/MacosPorters/betterxen/pull/277) | Merged; checks passed | Guest arguments and environment with combined services. |
| [#278](https://github.com/MacosPorters/betterxen/pull/278) | Merged; checks passed | Packed texture footprints; CPU and native GPU checks. |
| [#279](https://github.com/MacosPorters/betterxen/pull/279) | Merged; checks passed | Loop instructions; regenerated tables and corrected description to 3,600 comparisons. |
| [#280](https://github.com/MacosPorters/betterxen/pull/280) | Merged; checks passed | Process termination and exit callbacks. |
| [#281](https://github.com/MacosPorters/betterxen/pull/281) | Merged; checks passed | Formatted output integrated with startup and arguments. |
| [#282](https://github.com/MacosPorters/betterxen/pull/282) | Merged; checks passed | File streams; combined registry and dependency readiness. |
| [#283](https://github.com/MacosPorters/betterxen/pull/283) | Merged; checks passed | Hosted C fixture; driver architecture checked before execution. |
| [#284](https://github.com/MacosPorters/betterxen/pull/284) | Merged; checks passed | Thread-local storage (TLS) template-copy integration and preserved changelog entries. |
| [#288](https://github.com/MacosPorters/betterxen/pull/288) | Merged; checks passed | Development phases, README and migration-check record. |
PR #263 remains open to avoid competing with the contributor's live PR #290.
PR #290 was excluded from branch edits, reviews and merge operations as requested.
Its filesystem security and integration acceptance are left to that workstream.
## Verification and evidence scope
The integrated runtime candidate was
`5366b9398668128fdbb0b0879840dfa072bfa352`. Its GitHub native Rust workflow passed,
including workspace formatting, strict Clippy, tests and the hosted C fixture.
Local native results below concern the reported Apple M4 host running macOS 27.0
(class A host observations); they establish no Xbox-hardware or commercial-game
execution result.
| Check | Observed result |
| --- | --- |
| `scripts/test-gpu.sh` | 124 passed, 0 failed; 2 manual timing tests ignored. Metal API and GPU validation enabled. |
| Packed block-compressed texture GPU target | 1 passed, 0 failed, 0 ignored, with both validation layers enabled. |
| `scripts/demo.sh` | All three original fixtures matched Metal, reference and known-answer outputs. |
| `scripts/audit/native.sh` | 110 executables/loadable dependencies checked with `file`, `lipo` and `otool`; ARM64 architecture and permitted linkage checks passed. |
| Status, claims and dependency audits | Passed. |
The cache fix also passed an isolated local workspace run at `44ac976`: 917
passed, 0 failed, 35 ignored, plus strict Clippy. Its three alternating CPU
benchmark pairs used native release executables and identical original inputs:
per-run warm medians were 87.334–88.333 microseconds with per-byte validation and
15.625–18.791 microseconds with generation validation. Machine idleness was not
controlled. These measurements do not close the formal performance gate; their
candidate scope and cold results are recorded in PR #269.
A supplemental benchmark test-harness command exposed a missing initialization
for the newly added cache-invalidation counter. The follow-up initializes that
fixture and runs the existing report, JSON, comparison and percentile tests via
an ordinary integration-test target, preserving their assertions. This lets
workspace CI detect future benchmark-test compilation failures. All 14 existing
tests passed through both the ordinary integration target and the documented
manual harness command; strict workspace Clippy passed as well.
Raw final native logs, cache benchmark JSON and the PR-state inventory are kept
under ignored `artifacts/pr-integration/` in the lead checkout. PR checks and merge
records remain linked from each GitHub record.
## Remaining acceptance
This is an integration and execution record. Independent semantic and security
acceptance remains separate from implementer-run checks and administrative merge
permission. No release gates were redefined or releases created. Commercial Xbox
game execution remains unsupported.
Active-block self-modifying code is tracked separately in
[issue #291](https://github.com/MacosPorters/betterxen/issues/291); native-code cache
reclamation remains [issue #95](https://github.com/MacosPorters/betterxen/issues/95).
The source fixture programs, desktop instruction evidence and native Mac results
retain their existing boundaries.