Compare commits

..
Author SHA1 Message Date
atharvranjan 8df13ae976 ci: retrigger 2026-11-24 14:02:59 -06:00
atharvranjan 00eb6971e9 Preserve UTF-8 native inspection output
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 13:45:16 -06:00
atharvranjan 281d92bfb5 Read native audit JSON as UTF-8
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 13:28:35 -06:00
5 changed files with 132 additions and 83 deletions

No files matched your search

+2
View File
@@ -52,6 +52,8 @@ jobs:
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test pull request template check
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
- name: Test native audit JSON decoding
run: python3 -m unittest discover -s tests/audit
- name: Test semantic registry generator and coverage report
run: |
python3 -m unittest discover -s tests/semantics_generator
+1
View File
@@ -189,6 +189,7 @@ remains unsupported.
native DBT.
### Fixed
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
+11 -80
View File
@@ -1,12 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Synthetic interpreter and DBT timings.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, 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.
use std::hint::black_box;
use std::time::{Duration, Instant};
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
@@ -95,25 +88,14 @@ fn check(result: ExecutionResult) {
assert_eq!(result.final_state.get(Register::Rax), ADDS as u64);
}
fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
// Interpolate between adjacent values at rank (n - 1) * fraction.
let rank = (sorted.len() - 1) as f64 * fraction;
let lower = sorted[rank.floor() as usize];
let upper = sorted[rank.ceil() as usize];
lower + (upper - lower).mul_f64(rank.fract())
}
fn report(label: &str, samples: &mut [Duration]) {
samples.sort_unstable();
let median = percentile(samples, 0.50);
let p95 = percentile(samples, 0.95);
let p99 = percentile(samples, 0.99);
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
let median = samples[samples.len() / 2];
let min = samples[0];
let max = samples[samples.len() - 1];
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
println!(
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, median {mips:.2} MIPS",
samples.len()
);
}
@@ -122,8 +104,6 @@ fn main() {
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
assert!(sample_count > 0);
let warmup_count = std::env::var("XENORA_DBT_BENCH_WARMUP")
.map_or(10, |value| value.parse::<usize>().expect("warmup count"));
let mut code = vec![0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]; // mov rax, 0
for _ in 0..ADDS {
@@ -144,52 +124,38 @@ fn main() {
let mut warm = Vec::with_capacity(sample_count);
let mut cold_metrics = None;
for record in
std::iter::repeat_n(false, warmup_count).chain(std::iter::repeat_n(true, sample_count))
{
for _ in 0..sample_count {
let mut interp = Interpreter::new(initial_cpu.clone(), &mut loaded.memory, BUDGET);
let start = Instant::now();
let result = black_box(interp.run());
let interpreter_time = start.elapsed();
interpreter.push(start.elapsed());
check(result);
let mut dbt = DbtEngine::new(4 * 1024 * 1024).unwrap();
let mut cpu = initial_cpu.clone();
let start = Instant::now();
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
let cold_time = start.elapsed();
cold.push(start.elapsed());
check(result);
assert!(dbt.metrics.blocks_compiled > 0);
assert_eq!(dbt.metrics.cache_hits, 0);
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
let metrics = dbt.metrics;
cold_metrics = Some(dbt.metrics);
let mut cpu = initial_cpu.clone();
let start = Instant::now();
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
let warm_time = start.elapsed();
warm.push(start.elapsed());
check(result);
assert_eq!(dbt.metrics.blocks_compiled, metrics.blocks_compiled);
assert_eq!(
Some(dbt.metrics.blocks_compiled),
cold_metrics.map(|m| m.blocks_compiled)
);
assert_eq!(dbt.metrics.cache_hits, dbt.metrics.blocks_compiled);
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
if record {
interpreter.push(interpreter_time);
cold.push(cold_time);
warm.push(warm_time);
cold_metrics = Some(metrics);
}
}
println!("{INSTRUCTIONS} guest instructions per sample, final RAX={ADDS}");
println!("{warmup_count} warmup rounds excluded (XENORA_DBT_BENCH_WARMUP, default 10)");
println!(
"Cold DBT includes translation with a fresh engine; warm DBT reuses that engine's cache."
);
println!(
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
);
println!("Even sample counts use the midpoint of the two middle values for the median.");
report("Interpreter", &mut interpreter);
report("Cold DBT", &mut cold);
report("Warm DBT", &mut warm);
@@ -199,38 +165,3 @@ fn main() {
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
);
}
#[cfg(test)]
mod tests {
#[test]
fn single_sample_has_no_spread() {
use super::{Duration, percentile};
let samples = [Duration::from_micros(50)];
for fraction in [0.25, 0.50, 0.75, 0.95, 0.99] {
assert_eq!(percentile(&samples, fraction), samples[0]);
}
}
#[test]
fn percentiles_interpolate_across_even_samples() {
use super::{Duration, percentile};
let samples = [10, 20, 30, 100].map(Duration::from_micros);
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(25));
assert_eq!(percentile(&samples, 0.95), Duration::from_nanos(89_500));
assert_eq!(percentile(&samples, 0.99), Duration::from_nanos(97_900));
assert_eq!(
percentile(&samples, 0.75) - percentile(&samples, 0.25),
Duration::from_nanos(30_000)
);
}
#[test]
fn median_uses_the_middle_of_odd_samples() {
use super::{Duration, percentile};
let samples = [10, 20, 100].map(Duration::from_micros);
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
}
}
+6 -3
View File
@@ -17,10 +17,13 @@ python3 - <<'PY'
import json
from pathlib import Path
import subprocess
import sys
sys.stdout.reconfigure(encoding="utf-8")
executables = set()
for filename in ("native-build.jsonl", "native-tests.jsonl"):
for line in (Path("artifacts") / filename).read_text().splitlines():
for line in (Path("artifacts") / filename).read_text(encoding="utf-8").splitlines():
entry = json.loads(line)
if entry.get("executable"):
executables.add(entry["executable"])
@@ -32,11 +35,11 @@ if not executables:
raise SystemExit("No Cargo executable or loadable dependency artifacts found.")
for path in sorted(executables):
subprocess.run(["file", path], check=True)
archs = subprocess.check_output(["lipo", "-archs", path], text=True).strip()
archs = subprocess.check_output(["lipo", "-archs", path], encoding="utf-8").strip()
print(archs, flush=True)
if archs != "arm64":
raise SystemExit(f"Non-ARM64 build artifact: {path}")
linkage = subprocess.check_output(["otool", "-L", path], text=True)
linkage = subprocess.check_output(["otool", "-L", path], encoding="utf-8")
print(linkage, end="", flush=True)
if any(name in linkage.casefold() for name in ("vulkan", "moltenvk")):
raise SystemExit(f"Unexpected graphics linkage: {path}")
+112
View File
@@ -0,0 +1,112 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Exercise native audit JSON decoding and inspection under an ASCII locale."""
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = (ROOT / "scripts/audit/native.sh").read_text(encoding="utf-8")
AUDIT = SCRIPT.split("python3 - <<'PY'\n", 1)[1].rsplit("\nPY", 1)[0]
# Reader-only cases stop before the native executable inspection.
READER = AUDIT.split("\nif not executables:", 1)[0]
class NativeJsonTests(unittest.TestCase):
def run_audit(self, streams, code=READER):
with tempfile.TemporaryDirectory() as directory:
artifacts = Path(directory) / "artifacts"
artifacts.mkdir()
for name, payload in zip(
("native-build.jsonl", "native-tests.jsonl"), streams, strict=True
):
(artifacts / name).write_bytes(payload)
return subprocess.run(
[
sys.executable,
"-c",
"import locale\n"
"assert locale.getencoding().lower() in ('ascii', 'us-ascii')\n"
+ code
+ "\nprint(json.dumps(sorted(executables)))\n",
],
cwd=directory,
env={
**os.environ,
"LC_ALL": "C",
"PYTHONCOERCECLOCALE": "0",
"PYTHONUTF8": "0",
},
capture_output=True,
encoding="utf-8",
check=False,
)
def test_utf8_in_each_cargo_stream(self):
for stream in (0, 1):
with self.subTest(stream=stream):
entry = {
"executable": "/synthetic/caf\u00e9/bin",
"filenames": ["/synthetic/caf\u00e9/lib.dylib"],
"message": {"rendered": "synthetic diagnostic: \u03bb"},
}
streams = [b'{}\n', b'{}\n']
streams[stream] = (json.dumps(entry, ensure_ascii=False) + "\n").encode(
"utf-8"
)
result = self.run_audit(streams)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout),
["/synthetic/caf\u00e9/bin", "/synthetic/caf\u00e9/lib.dylib"],
)
def test_ascii_streams_keep_deduplicated_artifacts(self):
entry = b'{"executable":"/synthetic/bin","filenames":["/synthetic/lib.so","/synthetic/lib.rlib"]}\n'
result = self.run_audit([entry, entry])
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout), ["/synthetic/bin", "/synthetic/lib.so"]
)
def test_invalid_utf8_is_rejected(self):
result = self.run_audit([b'{"executable":"\xff"}\n', b'{}\n'])
self.assertNotEqual(result.returncode, 0)
self.assertIn("UnicodeDecodeError", result.stderr)
@unittest.skipUnless(
sys.platform == "darwin" and platform.machine() == "arm64",
"requires native ARM64 macOS inspection tools",
)
def test_native_inspection_of_unicode_path_under_ascii_locale(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / "fixture.c"
source.write_text("int main(void) { return 0; }\n", encoding="utf-8")
binary = root / "caf\u00e9"
subprocess.run(
["/usr/bin/clang", "-arch", "arm64", str(source), "-o", str(binary)],
check=True,
capture_output=True,
)
entry = (
json.dumps({"executable": str(binary)}, ensure_ascii=False) + "\n"
).encode("utf-8")
for stream in (0, 1):
with self.subTest(stream=stream):
streams = [b'{}\n', b'{}\n']
streams[stream] = entry
result = self.run_audit(streams, code=AUDIT)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn(str(binary), result.stdout)
self.assertIn("Checked 1 native executables", result.stdout)
if __name__ == "__main__":
unittest.main()