Files
metal2vulkan/crates/metal2vulkan-validation/tests/integration/compile_worker.rs
T
Anees Iqbal ae78d6c14f Validation: the worker watchdog charges compressed and swapped memory, not resident memory alone
The worker memory watchdog summed each process-group member's resident size: VmRSS on Linux,
proc_pid_rusage's ri_resident_size on macOS. Under memory pressure the system takes a worker's
pages out of its resident set (macOS's compressor; Linux's swap, to a disk or to compressed RAM
such as zram), so a group holding more than the 500-MiB ceiling could pass it unseen. On CI's
macOS job at 9e7034c214, worker_memory_watchdog_enforces_aggregate_limit ran into its 20-s
deadline: its two 256-MiB children (one written byte a page, nearly all zero) never summed to the
limit. That is the product ceiling going soft under pressure, not only a test problem.

What a member is charged (process_charged_bytes) is now:
- macOS: the larger of ri_resident_size and ri_phys_footprint, from the same proc_pid_rusage call.
  The SDK's sys/resource.h declares both in rusage_info_v2 with no comment; footprint(1) defines
  the ledger: "phys_footprint - the current value of the kernel ledger tracking the amount of
  dirty memory owned by a process", Dirty "includes "(Swapped)" memory, ... and memory written to
  implicitly, such as zero-filled", and (Swapped) is "A subset of Dirty memory that has been
  compressed or swapped to storage by the kernel". The footprint leaves out clean file-backed
  pages the resident size counts, so the larger of the two never trips later than before.
- Linux: VmRSS + VmSwap from the same /proc/<pid>/status read (status_charged_bytes). The member
  rules of process/linux.rs are unchanged: a member before its exec that shares its parent's
  memory is charged nothing, a copy-on-write one is counted (an overcount, never an undercount),
  and every other member is charged its own VmRSS and VmSwap, read after its flags.

Names that would lie are renamed: worker_resident_bytes -> worker_charged_bytes,
member_resident_bytes -> member_charged_bytes (both platforms). process_resident_bytes keeps
the resident size alone for own_resident_bytes, whose figure (corpus-triage's parent_rss_bytes,
the supervisor-heap test) stays resident memory; its doc no longer says it is read as workers'
are. The stop's message says "process-group memory budget". Docs that called the sampled figure
RSS (worker.rs, compile.rs, alloc.rs, audit.rs, budgets.rs, translation_audit.rs,
authored_compile.rs, corpus-pipeline.rs, corpus-triage's usage, docs/HOWTO.md's recipe) now say
memory; report keys (peak_*_rss_bytes, peak_resident_bytes) keep their names.

A stop at the ceiling is a recorded `failed oom` row of the engine census and of the
specialization lane's attempts, and its detail is the stop's message, so the measure can change
a recorded row: ENGINE_CENSUS_VERSION 8 -> 9 and SPECIALIZATION_AUDIT_VERSION 6 -> 7, as both
were bumped when the member charging last changed (engine 5, specialization 2). The authored
compile census records no worker stop (failures are never cached), so its version stays.

The fixture is unchanged: it now trips on its zero-filled pages wherever the system compresses or
swaps them.

Verified: a_members_swapped_memory_is_charged failed at the parent commit (lavapipe-free CPU
job m3-max-87876: left 307200000, right 563200000; 19 other worker::process tests passed). The
macOS arm is unchecked before the push (no Mac job); it stands on libc 0.2.189 and 0.2.191's
rusage_info_v2 (pub ri_phys_footprint: u64, beside the ri_resident_size this code already read)
and on CI's macOS job.
2026-12-04 21:24:00 -08:00

236 lines
8.8 KiB
Rust

//! The engine compile worker across a real process boundary: every validation binary that
//! compiles engine pipelines for a device serves the worker, and what comes back through the
//! pipeline's cache artifact bytes is the pipeline the public API compiles in process. A pipeline
//! holding a constant blob crosses it without the worker copying the blob.
use metal2vulkan::library::FunctionConstantValues;
use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError};
use metal2vulkan_validation::acceptance::{
compile_draw_in_worker, compile_pipeline, compile_row_in_worker, retained, row,
AcceptancePipeline, PipelineRequest, RequestFunction, RowCompile, RowPipeline, RowStage,
};
use metal2vulkan_validation::engine::load_description;
use metal2vulkan_validation::worker::compile::{
compile_compute, CompileWorker, NotCompiled, WorkerDevice,
};
use metal2vulkan_validation::worker::{WorkerFailure, DEADLINE};
use std::path::{Path, PathBuf};
fn fixture(name: &str) -> Option<Vec<u8>> {
match llvm_assemble(&engine_dir().join(name)) {
Ok(bytes) => Some(bytes),
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}"),
}
}
/// `program`, executed once before any compile: the OS may scan a freshly linked binary on its
/// first exec (seconds on macOS), which the 20-s worker deadline would count. A tool's worker is
/// the tool's own executable, which has run by the time it spawns one.
fn worker(program: &Path) -> CompileWorker {
let _ = std::process::Command::new(program)
.arg("--help")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status();
CompileWorker::program(program)
}
fn device(stem: &str) -> WorkerDevice {
WorkerDevice::new(load_description(stem).unwrap()).unwrap()
}
/// Every binary that compiles through the worker serves it (and installs the allocator it
/// refuses to serve without).
fn serving() -> [PathBuf; 2] {
[bin_exe!("corpus-pipeline"), bin_exe!("corpus-vulkan")]
}
#[test]
fn every_device_tool_serves_the_compile_worker_with_the_public_apis_pipeline() {
let Some(bitcode) = fixture("store_const.ll") else {
return;
};
let device = device("moltenvk-m3");
let request = PipelineRequest::Compute {
entry: "store_const".into(),
constants: FunctionConstantValues::defaults(),
};
let AcceptancePipeline::Compute(expected) =
compile_pipeline(&[&bitcode], &request, device.device(), None).unwrap()
else {
panic!("a kernel compiles to a compute pipeline");
};
for path in serving() {
let program = path.display();
let worker = worker(&path);
let compiled = compile_compute(
&worker,
&device,
&retained(&bitcode),
"store_const",
&FunctionConstantValues::defaults(),
)
.unwrap_or_else(|failure| panic!("{program}: {}", failure.message()));
let compiled_pipeline = compiled.result.unwrap();
assert_eq!(compiled_pipeline, *expected, "{program}");
assert!(
compiled.allocator_peak.is_some_and(|peak| peak > 0),
"{program}"
);
assert!(compiled.measured.elapsed < DEADLINE, "{program}");
if cfg!(any(target_os = "macos", target_os = "linux")) {
assert!(compiled.measured.peak_resident_bytes.is_some(), "{program}");
}
// The worker's report carries its counting allocator's process peak beside the sampled
// memory: at least the compile's own peak, which it contains.
let process_peak = compiled.measured.allocator_peak_bytes;
assert!(
process_peak.is_some_and(|peak| peak >= compiled.allocator_peak.unwrap()),
"{program}: {process_peak:?}"
);
assert!(compiled.measured.peak_bytes() >= process_peak, "{program}");
}
}
/// A logged draw (`corpus-pipeline --draws`) crosses the worker boundary: the vertex and
/// fragment functions of two sources, drawn together under the logged template, come back as the
/// render pipeline the in-process compile builds, a fragment row's.
#[test]
fn a_logged_draw_compiles_in_the_worker_as_in_process() {
let Some(bitcode) = fixture("stage_io.ll") else {
return;
};
let worker = worker(&bin_exe!("corpus-pipeline"));
let device = device("moltenvk-m3");
let undefined = FunctionConstantValues::defaults();
let mut template = row::fragment_row(&bitcode, "stage_io_fragment", &undefined)
.unwrap()
.template;
template.vertex_descriptor = row::vertex_row(&bitcode, "stage_io_vertex", &undefined)
.unwrap()
.template
.vertex_descriptor;
assert!(template.vertex_descriptor.is_some());
let request = PipelineRequest::Draw {
vertex: RequestFunction::new("stage_io_vertex", undefined.clone()),
fragment: RequestFunction::new("stage_io_fragment", undefined),
template: template.clone(),
};
let AcceptancePipeline::Render(expected) =
compile_pipeline(&[&bitcode, &bitcode], &request, device.device(), None).unwrap()
else {
panic!("a draw compiles to a render pipeline");
};
let (compiled, measured) = compile_draw_in_worker(
&worker,
&device,
&[retained(&bitcode), retained(&bitcode)],
"stage_io_vertex",
"stage_io_fragment",
&template,
);
let RowCompile::Compiled(pipeline) = compiled else {
panic!("{compiled:?}");
};
let RowPipeline::Render {
pipeline,
row: RowStage::Fragment,
} = *pipeline
else {
panic!("a draw came back as another kind");
};
assert_eq!(pipeline.stages.len(), 2);
assert_eq!(*pipeline, *expected);
assert!(measured.is_some());
}
#[test]
fn a_vertex_function_and_a_refusal_cross_the_worker_boundary() {
let Some(bitcode) = fixture("stage_io.ll") else {
return;
};
let worker = worker(&bin_exe!("corpus-pipeline"));
let device = device("moltenvk-m3");
// A vertex function that reads attributes and a fragment function, as L4 rows: the
// descriptor and the companion are derived (and the companion assembled) in the worker, and
// the render pipeline itself (not a refusal) crosses the boundary.
for (entry, stage, stages) in [
("stage_io_vertex", RowStage::Vertex, 1),
("stage_io_fragment", RowStage::Fragment, 2),
] {
let request = PipelineRequest::Row {
entry: entry.into(),
stage,
constants: FunctionConstantValues::defaults(),
};
let AcceptancePipeline::Render(expected) =
compile_pipeline(&[&bitcode], &request, device.device(), None).unwrap()
else {
panic!("{entry} compiles to a render pipeline");
};
let (compiled, measured) = compile_row_in_worker(
&worker,
&device,
&retained(&bitcode),
entry,
stage,
&FunctionConstantValues::defaults(),
);
let RowCompile::Compiled(pipeline) = compiled else {
panic!("{entry}: {compiled:?}");
};
let RowPipeline::Render { pipeline, .. } = *pipeline else {
panic!("{entry} came back as another kind");
};
assert_eq!(*pipeline, *expected);
assert_eq!(pipeline.stages.len(), stages);
assert!(measured.unwrap().elapsed < DEADLINE);
}
// The product's typed refusal comes back as its outcome, not as a worker failure.
let refused = compile_compute(
&worker,
&device,
&retained(&bitcode),
"no_such_entry",
&Default::default(),
)
.unwrap();
let Err(NotCompiled::Product(outcome, detail)) = refused.result else {
panic!("no_such_entry compiled");
};
assert_eq!(outcome.label(), "invalid_descriptor", "{detail}");
}
#[test]
fn a_program_that_does_not_serve_the_worker_is_a_worker_failure() {
let device = device("runtime-floor");
// `true` exits successfully without a result: the result cannot be read.
match compile_compute(
&CompileWorker::program("true"),
&device,
&retained(b"bitcode"),
"main",
&Default::default(),
) {
Err(failure @ WorkerFailure::Output(..)) => {
assert_eq!(failure.outcome().key(), "worker_exit")
}
other => panic!("{other:?}"),
}
// A program that cannot start is a setup failure (transient tooling).
match compile_compute(
&CompileWorker::program("/nonexistent/compile-worker"),
&device,
&retained(b"bitcode"),
"main",
&Default::default(),
) {
Err(failure @ WorkerFailure::Setup(_)) => assert!(failure.outcome().is_transient()),
other => panic!("{other:?}"),
}
}