Author SHA1 Message Date
Pavlo Ratushnyi 303fd4cf46 feat(cuda-driver): add fixed ordered f32 matvec primitive
Linux / keyless-cuda-gate (pull_request) Skipped
Linux / verify (pull_request) Successful in 3m45s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 1m39s
Linux / linux-static-cli (pull_request) Successful in 5m47s
Linux / release-cli (pull_request) Skipped
2026-10-08 09:51:12 +02:00
Pavlo Ratushnyi b9519f967a Harden config parity input file handling 2026-10-08 01:26:32 +02:00
Pavlo Ratushnyi 4aeec3c541 Add offline PLE config parity preflight 2026-10-08 01:19:30 +02:00
Pavlo Ratushnyi bbc8018e8b Bound runtime image probe waits and cleanup
Linux / keyless-cuda-gate (pull_request) Skipped
Desktop foundation / core (ubuntu-latest) (pull_request) Successful in 2m50s
Linux / verify (pull_request) Successful in 6m33s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 1m34s
Linux / linux-static-cli (pull_request) Successful in 6m26s
Linux / release-cli (pull_request) Skipped
2026-10-08 00:53:28 +02:00
19 changed files with 3767 additions and 1735 deletions
-66
View File
@@ -9,72 +9,6 @@ Store future benchmark definitions and sanitized fixtures in Git; place generate
`fixtures/chat/paired-smoke.json` contains public synthetic arithmetic, retrieval, and function-call prompts. Run `scripts/bench-chat-paired.py` from the repository root. It sends one untimed warmup per case and endpoint, then alternates baseline/candidate order over repeated, sequential requests with the same model, prompt, greedy sampling settings, and token cap. It checks each response's terminal `finish_reason` and case-specific text or tool arguments. The report includes per-case pass counts, raw response timings, and paired wall-time ratios. The full response report is written only to a new private path outside Git with mode 0600; API keys are read from private server config files and omitted from the report.
For the current upstream server, pass its full bound URL as `--baseline-url`, its `/health` URL as `--baseline-ready-url`, the configured model name as `--model`, and its private JSON config as `--baseline-auth-config`. The readiness poll waits for a nonzero `max_context` because upstream can report `loaded: true` during loading. Once a compressed inference endpoint exists, pass its URL as `--candidate-url` and optionally `--candidate-ready-url`. A baseline-only run is a functional check and cannot establish a speedup. Even a paired run of this small synthetic suite is only a smoke test: the charter's long-context, real-agent, cache-state, and model-quality gates still require separate runs. Record engine/config digests, GPU, driver, CUDA, power settings, and artifact digests in a private `--metadata` JSON for any reported performance result. Never commit the report or private config.
## Offline comparison of sequential Chat reports
When two model arms cannot fit together, compare two **single-arm** schema-1
reports from the same suite/model/configuration. A standalone harness run may
label its rows `baseline` in both files; the filenames select the comparison
arms. Each file must contain one arm, exactly one warmup per case and the full
declared repeat range. Missing or duplicate pairs, category drift, malformed
rows, nonfinite numbers and inconsistent successful HTTP/terminal/quality
claims fail before any comparison is published. Genuine observed quality or
HTTP failures remain explicit data, with failed categories reported separately.
```sh
python3 -B scripts/compare-chat-reports.py \
/private/evaluation/baseline.json /private/evaluation/candidate.json \
--output /private/evaluation/comparison.json
python3 -B scripts/render-paired-report.py /private/evaluation/comparison.json \
--output /private/evaluation/comparison.md
```
JSON and Markdown outputs must be new files outside Git and use mode 0600;
neither overwrites an existing file. The comparator prints fixed aggregate
counts only, without case labels, response text, tool arguments or metadata.
Markdown omits raw responses, tool arguments and metadata values. Private
metadata remains in the private JSON for reproducibility.
Existing schema-1 median fields remain available. Overall, category and case
groups additionally contain mean, median, linearly interpolated p10/p90 and
sample counts for both arms' wall times and positive paired prefill/decode
rates. Ratios are calculated **within each pair**, then summarized; they are
not ratios of arm medians. Zero token rates (for example fully cached prefill)
and missing timings never become divisions by zero: `timing_coverage` and
`unavailable_pairs` disclose their exclusion, while a wholly unavailable
throughput summary stays `null`. Counts must be nonnegative integers; timing
values must be finite/nonnegative and measured wall times strictly positive.
Ratio uncertainty uses a deterministic distribution-free, two-sided 95%
confidence interval for the population **median paired ratio**, selected from
order statistics with exact binomial coverage. This bounds work without a
bootstrap dependency or random seed. Fewer than six pairs cannot yield a finite
95% interval and receive `null` bounds; fewer than 30 pairs receive an explicit
small-sample flag. The interval assumes independent pairs sharing a population
median; sequential cache/load drift and correlated repeats can invalidate that
assumption. Category/overall mixtures also depend on case composition. The
interval does not measure those systematic errors or uncertainty in the mean.
The report names missing charter provenance fields without echoing their
values: `engine_commit`, `control_plane_commit`, `model_sha256`, `quantization`,
`gpu`, `driver`, `cuda_toolkit`, `power_limit_watts`, `context_tokens`,
`kv_configuration`, `slots`, `batch_size`, `speculation`, `cache_state`,
`workload_sha256`, `quality_gate_result`, `draft_acceptance_rate`,
`expert_cache_hit_rate`, `kv_streaming_hit_rate`; measured TTFT and prompt/output
token-count coverage are checked separately. Unavailable/not-applicable metrics
should be explained in private provenance; a declaration is not a measurement.
Conflicting declared hardware, model source, context/KV/slot/batch/speculation,
cache or workload identity refuses pairing. Engine/control-plane/codec version
changes can be the intended comparison, but must be recorded for each arm.
Inputs are bounded to 32 MiB each, 64 cases, 4,096 measured pairs, 100 repeats
per case, JSON depth 32 and one million JSON nodes. Timing/count magnitudes are
bounded to 10^12. Split larger suites deliberately instead of silently dropping
rows. JSON statistics and the Markdown rendering remain **descriptive**:
sequential runs, synthetic CPU fixtures, complete metadata or passing smoke
checks never automatically qualify GPU inference, model quality or an
end-to-end agent performance improvement. Those charter gates remain separate.
# Live Responses episode replay
`scripts/replay-live-responses.py` is an offline evaluator for an **explicitly
+212 -57
View File
@@ -7,13 +7,27 @@
//! verification evidence only and is not a production dependency. Do not infer
//! a fixed export ABI from the newer alias.
use crate::{Error, Result};
use crate::{Error, FixedOperation, Result};
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct ContextHandle(usize);
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct BufferHandle(u64);
impl BufferHandle {
pub(crate) fn validate_extent(self, bytes: usize) -> Result<()> {
let bytes = u64::try_from(bytes).map_err(|_| Error::InvalidMatvecShape)?;
if self.0 == 0 || bytes == 0 || self.0.checked_add(bytes).is_none() {
return Err(Error::InvalidMatvecShape);
}
Ok(())
}
#[cfg(test)]
pub(crate) fn synthetic(address: u64) -> Self {
Self(address)
}
}
#[derive(Clone, Copy)]
pub(crate) struct ModuleHandle(usize);
#[derive(Clone, Copy)]
@@ -64,6 +78,55 @@ impl Drop for LaunchArguments {
}
}
struct MatvecStorage {
addresses: [u64; 3],
rows: u32,
columns: u32,
parameters: [*mut std::ffi::c_void; 5],
}
// Only this NonNull owner moves. No reference/Box is recreated while the
// self-referential field pointers may be read by the native launch.
pub(crate) struct MatvecArguments {
storage: std::ptr::NonNull<MatvecStorage>,
}
impl MatvecArguments {
pub(crate) fn new(
matrix: BufferHandle,
vector: BufferHandle,
output: BufferHandle,
rows: u32,
columns: u32,
) -> Self {
let storage = Box::into_raw(Box::new(MatvecStorage {
addresses: [matrix.0, vector.0, output.0],
rows,
columns,
parameters: [std::ptr::null_mut(); 5],
}));
// SAFETY: stable uniquely raw-owned allocation; raw projections avoid
// retagging the storage through a new Box or whole-allocation borrow.
unsafe {
for i in 0..3 {
(*storage).parameters[i] = (&raw mut (*storage).addresses[i]).cast();
}
(*storage).parameters[3] = (&raw mut (*storage).rows).cast();
(*storage).parameters[4] = (&raw mut (*storage).columns).cast();
}
Self {
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
}
}
}
impl Drop for MatvecArguments {
fn drop(&mut self) {
// SAFETY: reconstructed exactly once before launch or after successful
// completion. The caller permanently forgets this owner on sync fault.
unsafe {
drop(Box::from_raw(self.storage.as_ptr()));
}
}
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
@@ -106,6 +169,7 @@ mod enabled {
*mut *mut c_void,
) -> CuResult;
static FIXED_PTX: &[u8] = concat!(include_str!("vector_add.ptx"), "\0").as_bytes();
static MATVEC_PTX: &[u8] = concat!(include_str!("matvec.ptx"), "\0").as_bytes();
type MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult;
struct Library(*mut c_void);
@@ -146,81 +210,82 @@ mod enabled {
Err(Error::Driver { operation, code })
}
}
// Fixed names/signatures remain explicitly paired. This macro is not a
// caller-selected resolver; a missing symbol exits before initialization.
macro_rules! symbol {
($library:ident, $name:literal, $ty:ty) => {{
// SAFETY: valid owned library handle and static C name.
let address = unsafe { libc::dlsym($library.0, $name.as_ptr()) };
if address.is_null() {
return Err(Error::MissingSymbol(
$name.to_str().expect("static ASCII symbol"),
));
}
// SAFETY: the fixed ABI name is paired with its exact
// documented signature. Linux64 supports dlsym function
// addresses; no generic or caller-selected reinterpretation.
unsafe { std::mem::transmute::<*mut c_void, $ty>(address) }
}};
}
impl Api {
pub(crate) fn load() -> Result<Self> {
// SAFETY: a fixed NUL-terminated soname, no caller-provided paths;
// immediate local symbol resolution, with null checked before use.
// SAFETY: fixed NUL-terminated soname and immediate local lookup.
let handle = unsafe {
libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL)
};
if handle.is_null() {
return Err(Error::LibraryUnavailable);
}
let library = Library(handle);
macro_rules! symbol {
($name:literal, $ty:ty) => {{
// SAFETY: valid owned library handle and static C name.
let address = unsafe { libc::dlsym(library.0, $name.as_ptr()) };
if address.is_null() {
return Err(Error::MissingSymbol(
$name.to_str().expect("static ASCII symbol"),
));
}
// SAFETY: the fixed ABI name is paired with its exact
// documented signature. Linux64 supports dlsym function
// addresses; no generic or caller-selected reinterpretation.
unsafe { std::mem::transmute::<*mut c_void, $ty>(address) }
}};
}
let init = symbol!(c"cuInit", Init);
let version = symbol!(c"cuDriverGetVersion", DriverGetVersion);
let device = symbol!(c"cuDeviceGet", DeviceGet);
let create = symbol!(c"cuCtxCreate_v2", ContextCreateV2);
let destroy = symbol!(c"cuCtxDestroy_v2", ContextDestroyV2);
let push = symbol!(c"cuCtxPushCurrent_v2", ContextPushCurrentV2);
let pop = symbol!(c"cuCtxPopCurrent_v2", ContextPopCurrentV2);
let synchronize = symbol!(c"cuCtxSynchronize", ContextSynchronize);
let allocate = symbol!(c"cuMemAlloc_v2", MemAllocV2);
let free = symbol!(c"cuMemFree_v2", MemFreeV2);
let copy_from = symbol!(c"cuMemcpyHtoD_v2", MemcpyHtoDV2);
let copy_to = symbol!(c"cuMemcpyDtoH_v2", MemcpyDtoHV2);
let load_module = symbol!(c"cuModuleLoadData", ModuleLoadData);
let get_function = symbol!(c"cuModuleGetFunction", ModuleGetFunction);
let unload_module = symbol!(c"cuModuleUnload", ModuleUnload);
let launch_kernel = symbol!(c"cuLaunchKernel", LaunchKernel);
Self::resolve(Library(handle))
}
fn resolve(library: Library) -> Result<Self> {
// Evaluation order preserves all sixteen pre-init resolutions.
// The library moves only after every fallible symbol check.
Ok(Self {
init: symbol!(library, c"cuInit", Init),
version: symbol!(library, c"cuDriverGetVersion", DriverGetVersion),
device: symbol!(library, c"cuDeviceGet", DeviceGet),
create: symbol!(library, c"cuCtxCreate_v2", ContextCreateV2),
destroy: symbol!(library, c"cuCtxDestroy_v2", ContextDestroyV2),
push: symbol!(library, c"cuCtxPushCurrent_v2", ContextPushCurrentV2),
pop: symbol!(library, c"cuCtxPopCurrent_v2", ContextPopCurrentV2),
synchronize: symbol!(library, c"cuCtxSynchronize", ContextSynchronize),
allocate: symbol!(library, c"cuMemAlloc_v2", MemAllocV2),
free: symbol!(library, c"cuMemFree_v2", MemFreeV2),
copy_from: symbol!(library, c"cuMemcpyHtoD_v2", MemcpyHtoDV2),
copy_to: symbol!(library, c"cuMemcpyDtoH_v2", MemcpyDtoHV2),
load_module: symbol!(library, c"cuModuleLoadData", ModuleLoadData),
get_function: symbol!(library, c"cuModuleGetFunction", ModuleGetFunction),
unload_module: symbol!(library, c"cuModuleUnload", ModuleUnload),
launch_kernel: symbol!(library, c"cuLaunchKernel", LaunchKernel),
_library: library,
init,
version,
device,
create,
destroy,
push,
pop,
synchronize,
allocate,
free,
copy_from,
copy_to,
load_module,
get_function,
unload_module,
launch_kernel,
})
}
pub(crate) fn load_fixed_module(&self) -> Result<ModuleHandle> {
pub(crate) fn load_fixed_module(&self, operation: FixedOperation) -> Result<ModuleHandle> {
let mut module = std::ptr::null_mut();
// SAFETY: current owned context, writable module out pointer, and
// static trusted NUL-terminated PTX remains live indefinitely.
check("cuModuleLoadData", unsafe {
(self.load_module)(&mut module, FIXED_PTX.as_ptr().cast())
(self.load_module)(
&mut module,
match operation {
FixedOperation::VectorAdd => FIXED_PTX,
FixedOperation::Matvec => MATVEC_PTX,
}
.as_ptr()
.cast(),
)
})?;
if module.is_null() {
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
}
Ok(ModuleHandle(module as usize))
}
pub(crate) fn fixed_function(&self, module: ModuleHandle) -> Result<FunctionHandle> {
pub(crate) fn fixed_function(
&self,
module: ModuleHandle,
operation: FixedOperation,
) -> Result<FunctionHandle> {
let mut function = std::ptr::null_mut();
// SAFETY: live private module in current owner context; fixed C
// entry name; valid writable opaque function output.
@@ -228,7 +293,11 @@ mod enabled {
(self.get_function)(
&mut function,
module.0 as *mut c_void,
c"leleka_vector_add_f32".as_ptr(),
match operation {
FixedOperation::VectorAdd => c"leleka_vector_add_f32",
FixedOperation::Matvec => c"leleka_matvec_f32",
}
.as_ptr(),
)
})?;
if function.is_null() {
@@ -272,6 +341,33 @@ mod enabled {
)
})
}
pub(crate) fn launch_matvec(
&self,
function: FunctionHandle,
grid: u32,
arguments: &mut MatvecArguments,
) -> Result<()> {
// SAFETY: private trusted function in current owner context;
// checked shapes/extents/output identity and fixed geometry. Five
// pointers address initialized typed scalars in stable raw storage.
// Caller synchronizes each attempt or permanently retains storage.
check("cuLaunchKernel", unsafe {
(self.launch_kernel)(
function.0 as *mut c_void,
grid,
1,
1,
128,
1,
1,
0,
std::ptr::null_mut(),
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
std::ptr::null_mut(),
)
})
}
pub(crate) fn init(&self) -> Result<()> {
// SAFETY: resolved exact ABI, mandated zero flags, live library.
check("cuInit", unsafe { (self.init)(0) })
@@ -385,10 +481,14 @@ impl Api {
Err(Error::Disabled)
}
}
pub(crate) fn load_fixed_module(&self) -> Result<ModuleHandle> {
pub(crate) fn load_fixed_module(&self, _: FixedOperation) -> Result<ModuleHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn fixed_function(&self, module: ModuleHandle) -> Result<FunctionHandle> {
pub(crate) fn fixed_function(
&self,
module: ModuleHandle,
_: FixedOperation,
) -> Result<FunctionHandle> {
let _ = module.0;
Err(Error::UnsupportedPlatform)
}
@@ -405,6 +505,16 @@ impl Api {
let _ = (function.0, arguments.storage);
Err(Error::UnsupportedPlatform)
}
pub(crate) fn launch_matvec(
&self,
function: FunctionHandle,
_: u32,
arguments: &mut MatvecArguments,
) -> Result<()> {
let _ = (function.0, arguments.storage);
Err(Error::UnsupportedPlatform)
}
// These methods cannot be reached through the safe API: load always fails.
pub(crate) fn init(&self) -> Result<()> {
Err(Error::UnsupportedPlatform)
@@ -443,3 +553,48 @@ impl Api {
Err(Error::UnsupportedPlatform)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matvec_address_extents() {
assert_eq!(
BufferHandle(0).validate_extent(4),
Err(Error::InvalidMatvecShape)
);
assert_eq!(
BufferHandle(1).validate_extent(0),
Err(Error::InvalidMatvecShape)
);
assert_eq!(
BufferHandle(u64::MAX - 3).validate_extent(4),
Err(Error::InvalidMatvecShape)
);
assert_eq!(BufferHandle(u64::MAX - 4).validate_extent(4), Ok(()));
}
#[test]
fn matvec_raw_storage_survives_owner_moves() {
let arguments = MatvecArguments::new(
BufferHandle(11),
BufferHandle(22),
BufferHandle(33),
129,
u32::MAX,
);
let pointer = arguments.storage.as_ptr();
let moved = vec![arguments].pop().unwrap();
let churn: Vec<_> = (0..1024).map(|_| Box::new([0xdeadbeefu64; 8])).collect();
std::hint::black_box(&churn);
assert_eq!(moved.storage.as_ptr(), pointer);
// SAFETY: the still-owned raw allocation and every initialized field
// pointer remain live. Read exactly their documented scalar widths.
unsafe {
for (i, expected) in [11u64, 22, 33].into_iter().enumerate() {
assert_eq!(*(*pointer).parameters[i].cast::<u64>(), expected);
}
assert_eq!(*(*pointer).parameters[3].cast::<u32>(), 129);
assert_eq!(*(*pointer).parameters[4].cast::<u32>(), u32::MAX);
}
}
}
+307 -45
View File
@@ -28,6 +28,7 @@ pub enum Error {
},
ContextMismatch,
InvalidVectorShape,
InvalidMatvecShape,
OutputAliasesInput,
InvalidOrdinal,
InvalidSize,
@@ -45,14 +46,46 @@ pub enum Error {
},
}
impl Error {
fn environment_message(&self) -> Option<&'static str> {
Some(match self {
Self::Disabled => "CUDA Driver feature is disabled",
Self::UnsupportedPlatform => "CUDA Driver requires Linux with 64-bit pointers",
Self::LibraryUnavailable => "cannot load libcuda.so.1",
Self::InvalidOrdinal => "device ordinal must be nonnegative",
Self::HostAllocation => "cannot allocate owned host staging memory",
Self::ContextPoisoned => {
"context is poisoned after uncertain completion or restoration"
}
Self::UnexpectedContext => "CUDA pop returned a different context",
_ => return None,
})
}
fn validation_message(&self) -> Option<&'static str> {
Some(match self {
Self::ContextMismatch => "buffers must belong to this exact context",
Self::InvalidVectorShape => {
"vector shape must be nonempty f32 bytes with a bounded u32 count/grid"
}
Self::InvalidMatvecShape => {
"matvec requires exact nonempty bounded row-major f32 shapes"
}
Self::OutputAliasesInput => "output must not alias an input",
Self::InvalidSize => "byte size must be nonzero and fit isize",
Self::BudgetExceeded => "allocation exceeds context byte budget",
_ => return None,
})
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(message) = self
.environment_message()
.or_else(|| self.validation_message())
{
return f.write_str(message);
}
match self {
Self::Disabled => f.write_str("CUDA Driver feature is disabled"),
Self::UnsupportedPlatform => {
f.write_str("CUDA Driver requires Linux with 64-bit pointers")
}
Self::LibraryUnavailable => f.write_str("cannot load libcuda.so.1"),
Self::MissingSymbol(symbol) => write!(f, "missing CUDA Driver symbol {symbol}"),
Self::InvalidDriverValue(operation) => {
write!(f, "{operation} returned an invalid handle on success")
@@ -60,27 +93,13 @@ impl fmt::Display for Error {
Self::Driver { operation, code } => {
write!(f, "{operation} failed with CUDA code {code}")
}
Self::ContextMismatch => {
f.write_str("vector buffers must belong to this exact context")
}
Self::InvalidVectorShape => {
f.write_str("vector shape must be nonempty f32 bytes with a bounded u32 count/grid")
}
Self::OutputAliasesInput => f.write_str("vector output must not alias an input"),
Self::InvalidOrdinal => f.write_str("device ordinal must be nonnegative"),
Self::InvalidSize => f.write_str("byte size must be nonzero and fit isize"),
Self::BudgetExceeded => f.write_str("allocation exceeds context byte budget"),
Self::ShapeMismatch { expected, actual } => {
write!(f, "byte shape mismatch: expected {expected}, got {actual}")
}
Self::HostAllocation => f.write_str("cannot allocate owned host staging memory"),
Self::ContextPoisoned => {
f.write_str("context is poisoned after uncertain completion or restoration")
}
Self::UnexpectedContext => f.write_str("CUDA pop returned a different context"),
Self::Multiple { primary, secondary } => {
write!(f, "{primary}; subsequent error: {secondary}")
}
_ => unreachable!("static errors have a message"),
}
}
}
@@ -163,7 +182,8 @@ impl<'driver> Device<'driver> {
budget: byte_budget,
allocated: Cell::new(0),
poisoned: Cell::new(false),
kernel: Cell::new(None),
vector_add_kernel: Cell::new(None),
matvec_kernel: Cell::new(None),
})
}
}
@@ -175,7 +195,8 @@ pub struct Context<'driver> {
budget: usize,
allocated: Cell<usize>,
poisoned: Cell<bool>,
kernel: Cell<Option<FixedKernel>>,
vector_add_kernel: Cell<Option<FixedKernel>>,
matvec_kernel: Cell<Option<FixedKernel>>,
}
#[derive(Clone, Copy)]
struct FixedKernel {
@@ -183,6 +204,67 @@ struct FixedKernel {
function: ffi::FunctionHandle,
}
// Closed selector: callers cannot choose executable bytes, names or geometry.
#[derive(Clone, Copy)]
enum FixedOperation {
VectorAdd,
Matvec,
}
#[derive(Debug, PartialEq, Eq)]
struct MatvecShape {
matrix_bytes: usize,
vector_bytes: usize,
output_bytes: usize,
rows: u32,
columns: u32,
grid: u32,
}
fn matvec_shape(rows: usize, columns: usize) -> Result<MatvecShape> {
let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidMatvecShape)?;
let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidMatvecShape)?;
let bytes = |elements: Option<usize>| -> Result<usize> {
let bytes = elements
.and_then(|v| v.checked_mul(4))
.ok_or(Error::InvalidMatvecShape)?;
valid_size(bytes).map_err(|_| Error::InvalidMatvecShape)?;
Ok(bytes)
};
let matrix_bytes = bytes(rows.checked_mul(columns))?;
let vector_bytes = bytes(Some(columns))?;
let output_bytes = bytes(Some(rows))?;
let grid = u64::from(rows_abi).div_ceil(128);
if grid == 0 || grid > i32::MAX as u64 {
return Err(Error::InvalidMatvecShape);
}
Ok(MatvecShape {
matrix_bytes,
vector_bytes,
output_bytes,
rows: rows_abi,
columns: columns_abi,
grid: u32::try_from(grid).map_err(|_| Error::InvalidMatvecShape)?,
})
}
fn matvec_allocations(
matrix: Option<ffi::BufferHandle>,
vector: Option<ffi::BufferHandle>,
output: Option<ffi::BufferHandle>,
shape: &MatvecShape,
) -> Result<(ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle)> {
let matrix = matrix.ok_or(Error::ContextPoisoned)?;
let vector = vector.ok_or(Error::ContextPoisoned)?;
let output = output.ok_or(Error::ContextPoisoned)?;
if matrix == output || vector == output {
return Err(Error::OutputAliasesInput);
}
matrix.validate_extent(shape.matrix_bytes)?;
vector.validate_extent(shape.vector_bytes)?;
output.validate_extent(shape.output_bytes)?;
Ok((matrix, vector, output))
}
// Wider integer arithmetic also covers the final partial block at u32::MAX.
fn vector_shape(bytes: usize) -> Result<(u32, u32)> {
if valid_size(bytes).is_err() || !bytes.is_multiple_of(4) {
@@ -261,6 +343,28 @@ impl Context<'_> {
b: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
let (handles, count, grid) = self.vector_admission(a, b, output)?;
let [a_handle, b_handle, out_handle] = handles;
// Establish the owned parameter addresses after their stable heap
// placement, before any native mutation. No caller host data is used.
let mut arguments = ffi::LaunchArguments::new(a_handle, b_handle, out_handle, count);
let guard = self.enter()?;
let kernel = match self.fixed_kernel(FixedOperation::VectorAdd) {
Ok(kernel) => kernel,
Err(error) => return combine(Err(error), guard.finish()),
};
let launch = self
.driver
.api
.launch(kernel.function, grid, &mut arguments);
self.complete_launch(launch, arguments, guard)
}
fn vector_admission(
&self,
a: &DeviceBuffer<'_>,
b: &DeviceBuffer<'_>,
output: &DeviceBuffer<'_>,
) -> Result<([ffi::BufferHandle; 3], u32, u32)> {
if self.poisoned.get() {
return Err(Error::ContextPoisoned);
}
@@ -280,38 +384,98 @@ impl Context<'_> {
if a_handle == out_handle || b_handle == out_handle {
return Err(Error::OutputAliasesInput);
}
// Establish the owned parameter addresses after their stable heap
// placement, before any native mutation. No caller host data is used.
let mut arguments = ffi::LaunchArguments::new(a_handle, b_handle, out_handle, count);
Ok(([a_handle, b_handle, out_handle], count, grid))
}
fn complete_launch<T>(
&self,
launch: Result<()>,
arguments: T,
guard: CurrentGuard<'_, '_>,
) -> Result<()> {
// A launch error may describe earlier asynchronous work. Synchronize
// every attempted launch; preserve launch/sync/pop error order.
let sync = self.driver.api.synchronize();
if sync.is_err() {
self.poisoned.set(true);
// Both scalars and their table may still be read. The raw owner
// remains forgotten even if later context destruction succeeds.
std::mem::forget(arguments);
}
combine(combine(launch, sync), guard.finish())
}
/// Compute each row's dot product in ascending column order with separate
/// binary32 multiply/add rounding. All buffers are exact whole allocations;
/// output is usable as a computed vector only after a successful return.
pub fn matvec_f32(
&self,
matrix: &DeviceBuffer<'_>,
vector: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
rows: usize,
columns: usize,
) -> Result<()> {
let (shape, handles) = self.matvec_admission([matrix, vector, output], rows, columns)?;
let [matrix_handle, vector_handle, output_handle] = handles;
let mut arguments = ffi::MatvecArguments::new(
matrix_handle,
vector_handle,
output_handle,
shape.rows,
shape.columns,
);
let guard = self.enter()?;
let kernel = match self.fixed_kernel() {
let kernel = match self.fixed_kernel(FixedOperation::Matvec) {
Ok(kernel) => kernel,
Err(error) => return combine(Err(error), guard.finish()),
};
let launch = self
.driver
.api
.launch(kernel.function, grid, &mut arguments);
// A launch error can describe earlier asynchronous work. Synchronize
// after EVERY attempted launch; preserve launch/sync/pop error order.
let sync = self.driver.api.synchronize();
if sync.is_err() {
self.poisoned.set(true);
// Both boxed scalars and their pointer table may still be read.
// One poisoned context admits no further launch or explicit frees.
std::mem::forget(arguments);
}
combine(combine(launch, sync), guard.finish())
.launch_matvec(kernel.function, shape.grid, &mut arguments);
self.complete_launch(launch, arguments, guard)
}
fn fixed_kernel(&self) -> Result<FixedKernel> {
if let Some(kernel) = self.kernel.get() {
fn matvec_admission(
&self,
buffers: [&DeviceBuffer<'_>; 3],
rows: usize,
columns: usize,
) -> Result<(MatvecShape, [ffi::BufferHandle; 3])> {
let [matrix, vector, output] = buffers;
if self.poisoned.get() || self.handle.is_none() {
return Err(Error::ContextPoisoned);
}
if !std::ptr::eq(self, matrix.context)
|| !std::ptr::eq(self, vector.context)
|| !std::ptr::eq(self, output.context)
{
return Err(Error::ContextMismatch);
}
let shape = matvec_shape(rows, columns)?;
if matrix.bytes != shape.matrix_bytes
|| vector.bytes != shape.vector_bytes
|| output.bytes != shape.output_bytes
{
return Err(Error::InvalidMatvecShape);
}
let handles = matvec_allocations(matrix.handle, vector.handle, output.handle, &shape)?;
Ok((shape, [handles.0, handles.1, handles.2]))
}
fn kernel_slot(&self, operation: FixedOperation) -> &Cell<Option<FixedKernel>> {
match operation {
FixedOperation::VectorAdd => &self.vector_add_kernel,
FixedOperation::Matvec => &self.matvec_kernel,
}
}
fn fixed_kernel(&self, operation: FixedOperation) -> Result<FixedKernel> {
let slot = self.kernel_slot(operation);
if let Some(kernel) = slot.get() {
return Ok(kernel);
}
let module = self.driver.api.load_fixed_module()?;
match self.driver.api.fixed_function(module) {
let module = self.driver.api.load_fixed_module(operation)?;
match self.driver.api.fixed_function(module, operation) {
Ok(function) => {
let kernel = FixedKernel { module, function };
self.kernel.set(Some(kernel));
slot.set(Some(kernel));
Ok(kernel)
}
Err(error) => {
@@ -325,9 +489,9 @@ impl Context<'_> {
}
}
}
fn unload_kernel(&self) -> Result<()> {
fn unload_kernel(&self, operation: FixedOperation) -> Result<()> {
// Consume BEFORE attempting unload; even an error can invalidate it.
let Some(kernel) = self.kernel.take() else {
let Some(kernel) = self.kernel_slot(operation).take() else {
return Ok(());
};
if self.poisoned.get() {
@@ -352,7 +516,11 @@ impl Context<'_> {
self.destroy()
}
fn destroy(&mut self) -> Result<()> {
let unload = self.unload_kernel();
// Fixed teardown order; shared poison suppresses the second native unload.
let unload = combine(
self.unload_kernel(FixedOperation::VectorAdd),
self.unload_kernel(FixedOperation::Matvec),
);
if let Some(handle) = self.handle.take() {
// cuCtxDestroy accepts an owned non-current context. Pushing here
// would add a stack entry for a handle invalidated by destruction.
@@ -525,6 +693,100 @@ mod tests {
}
assert!(vector_shape((u32::MAX as usize + 1) * 4).is_err());
}
#[test]
fn matvec_shape_boundaries() {
for (m, n) in [
(0, 1),
(1, 0),
(usize::MAX, 1),
(1, usize::MAX),
(u32::MAX as usize + 1, 1),
(1, u32::MAX as usize + 1),
(u32::MAX as usize, u32::MAX as usize),
] {
assert_eq!(matvec_shape(m, n), Err(Error::InvalidMatvecShape));
}
for m in [1u32, 127, 128, 129, 1025, u32::MAX] {
let shape = matvec_shape(m as usize, 1).unwrap();
assert_eq!(shape.rows, m);
assert_eq!(shape.matrix_bytes, m as usize * 4);
assert_eq!(shape.output_bytes, m as usize * 4);
assert_eq!(shape.grid as u64, u64::from(m).div_ceil(128));
}
let shape = matvec_shape(1, u32::MAX as usize).unwrap();
assert_eq!(shape.columns, u32::MAX);
assert_eq!(shape.vector_bytes, u32::MAX as usize * 4);
let largest_columns = (isize::MAX as usize / 4) / u32::MAX as usize;
assert!(matvec_shape(u32::MAX as usize, largest_columns).is_ok());
assert_eq!(
matvec_shape(u32::MAX as usize, largest_columns + 1),
Err(Error::InvalidMatvecShape)
);
// Element count is deliberately not restricted to u32.
assert!(matvec_shape(65536, 65536).is_ok());
}
#[test]
fn matvec_allocation_identity_and_absent_handles() {
let shape = matvec_shape(1, 1).unwrap();
let h = |v| Some(ffi::BufferHandle::synthetic(v));
for handles in [(h(4), h(8), h(4)), (h(4), h(8), h(8))] {
assert!(matches!(
matvec_allocations(handles.0, handles.1, handles.2, &shape),
Err(Error::OutputAliasesInput)
));
}
for handles in [(None, h(8), h(12)), (h(4), None, h(12)), (h(4), h(8), None)] {
assert!(matches!(
matvec_allocations(handles.0, handles.1, handles.2, &shape),
Err(Error::ContextPoisoned)
));
}
for handles in [
(h(u64::MAX - 3), h(8), h(12)),
(h(4), h(u64::MAX - 3), h(12)),
(h(4), h(8), h(u64::MAX - 3)),
] {
assert!(matches!(
matvec_allocations(handles.0, handles.1, handles.2, &shape),
Err(Error::InvalidMatvecShape)
));
}
assert!(matvec_allocations(h(4), h(4), h(12), &shape).is_ok());
}
#[cfg(not(feature = "cuda-driver"))]
#[test]
fn matvec_private_admission_refuses_without_cuda() {
let driver = Driver {
api: Rc::new(ffi::Api),
version: 0,
};
let context = Context {
driver: &driver,
handle: None,
budget: 64,
allocated: Cell::new(12),
poisoned: Cell::new(false),
vector_add_kernel: Cell::new(None),
matvec_kernel: Cell::new(None),
};
let make = |handle| DeviceBuffer {
context: &context,
handle,
bytes: 4,
_thread: PhantomData,
};
let matrix = make(Some(ffi::BufferHandle::synthetic(4)));
let vector = make(Some(ffi::BufferHandle::synthetic(8)));
let mut output = make(Some(ffi::BufferHandle::synthetic(12)));
assert_eq!(
context.matvec_f32(&matrix, &vector, &mut output, 1, 1),
Err(Error::ContextPoisoned)
);
// No native context exists in this test. Pure allocation identity and
// extent instruments supply the remaining impossible-safe-call cases.
assert_eq!(context.allocated_bytes(), 12);
assert!(context.matvec_kernel.get().is_none());
}
#[cfg(not(feature = "cuda-driver"))]
#[test]
fn default_load_rejects_before_driver_use() {
+33
View File
@@ -0,0 +1,33 @@
// Trusted row-major serial binary32 recurrence, embedded with final NUL.
.version 7.0
.target sm_75
.address_size 64
.visible .entry leleka_matvec_f32(
.param .u64 matrix, .param .u64 vector, .param .u64 output,
.param .u32 rows, .param .u32 columns )
{
.reg .pred %p<2>; .reg .b32 %r<4>;
.reg .b64 %rd<15>; .reg .f32 %f<4>;
ld.param.u64 %rd0, [matrix]; ld.param.u64 %rd1, [vector];
ld.param.u64 %rd2, [output]; ld.param.u32 %r2, [rows]; ld.param.u32 %r3, [columns];
mov.u32 %r0, %ctaid.x; mov.u32 %r1, %tid.x;
mul.wide.u32 %rd3, %r0, 128; cvt.u64.u32 %rd4, %r1;
add.u64 %rd3, %rd3, %rd4; cvt.u64.u32 %rd4, %r2;
setp.ge.u64 %p0, %rd3, %rd4; @%p0 bra DONE;
cvt.u64.u32 %rd5, %r3; mul.lo.u64 %rd6, %rd3, %rd5;
mov.u64 %rd7, 0; mov.f32 %f3, 0f00000000;
LOOP:
add.u64 %rd8, %rd6, %rd7; shl.b64 %rd8, %rd8, 2;
add.u64 %rd9, %rd0, %rd8; shl.b64 %rd10, %rd7, 2;
add.u64 %rd11, %rd1, %rd10;
ld.global.f32 %f0, [%rd9]; ld.global.f32 %f1, [%rd11];
mul.rn.f32 %f2, %f0, %f1; add.rn.f32 %f3, %f3, %f2;
add.u64 %rd7, %rd7, 1; setp.lt.u64 %p1, %rd7, %rd5; @%p1 bra LOOP;
shl.b64 %rd12, %rd3, 2; add.u64 %rd13, %rd2, %rd12;
st.global.f32 [%rd13], %f3;
DONE: ret;
}
+83 -20
View File
@@ -17,11 +17,12 @@ static int context_live(CUcontext ctx){for(size_t i=0;i<16;i++)if(contexts[i]==c
static int live_context;
static unsigned failed_mask;
static struct {void *raw,*ptr;size_t size;CUcontext owner;} buffers[16];
static struct {void *handle,*function;CUcontext owner;} modules[16];
static struct {void *handle,*function;CUcontext owner;int matvec;} modules[16];
static size_t next_module;
static void **pending_args;
static uint64_t pending_values[3];
static uint32_t pending_n;
static uint32_t pending_n,pending_columns;
static int pending_matvec;
static CUcontext pending_owner;
static const void *pending_host;
static void *pending_device;
@@ -54,12 +55,29 @@ static void check_canary(size_t i) {
if(!raw)return;
for(size_t j=0;j<8;j++)if(raw[j]!=0xa5||raw[8+buffers[i].size+j]!=0xa5){trace("canary",1,i);abort();}
}
static void compute_pending_kernel(void) {
float *a=(float *)(uintptr_t)pending_values[0];
float *b=(float *)(uintptr_t)pending_values[1],*out=(float *)(uintptr_t)pending_values[2];
if(pending_matvec){
/* Volatile rounds each operation to binary32. Build flags forbid
contraction/reassociation; this fixture never interprets PTX. */
for(uint64_t r=0;r<pending_n;r++){
volatile float sum=0.0f;
for(uint64_t c=0;c<pending_columns;c++){
volatile float product=a[r*pending_columns+c]*b[c];
sum=sum+product;
}
out[r]=sum;
}
trace("pending_matvec",0,pending_columns);
} else for(uint32_t i=0;i<pending_n;i++)out[i]=a[i]+b[i];
}
static void complete_pending(void) {
if(pending_args){
for(size_t i=0;i<3;i++)if(*(uint64_t *)pending_args[i]!=pending_values[i])abort();
if(*(uint32_t *)pending_args[3]!=pending_n)abort();
float *a=(float *)(uintptr_t)pending_values[0],*b=(float *)(uintptr_t)pending_values[1],*out=(float *)(uintptr_t)pending_values[2];
for(uint32_t i=0;i<pending_n;i++)out[i]=a[i]+b[i];
if(pending_matvec&&*(uint32_t *)pending_args[4]!=pending_columns)abort();
compute_pending_kernel();
trace("pending_launch",0,pending_n);
pending_args=NULL;pending_n=0;
}
@@ -68,9 +86,13 @@ static void complete_pending(void) {
size_t sum=0;for(size_t i=0;i<pending_bytes;i++)sum+=((const unsigned char *)pending_host)[i];
const unsigned char expected[8]={0,1,2,3,255,128,85,170};
int exact=pending_bytes==sizeof(expected)&&memcmp(pending_host,expected,sizeof(expected))==0;
trace("pending_htod",exact||getenv("MOCK_CUDA_VECTOR")?0:1,sum);memcpy(pending_device,pending_host,pending_bytes);
trace("pending_htod",exact||getenv("MOCK_CUDA_VECTOR")?0:1,sum);
memcpy(pending_device,pending_host,pending_bytes);
}
if(pending_destination&&pending_device){
trace("pending_dtoh",0,pending_bytes);
memcpy(pending_destination,pending_device,pending_bytes);
}
if(pending_destination&&pending_device){trace("pending_dtoh",0,pending_bytes);memcpy(pending_destination,pending_device,pending_bytes);}
pending_host=NULL;pending_device=NULL;pending_destination=NULL;pending_bytes=0;
}
static int require_context(void) {return context_live(current)?0:201;}
@@ -136,43 +158,84 @@ CUresult cuMemcpyDtoH_v2(void *host,CUdeviceptr ptr,size_t bytes) {
/* Independent fixed vector ABI fixture. Arithmetic here is a CPU reference;
it neither interprets nor executes PTX. */
static int exact_image(const char *ptx,int matvec) {
const char *path=getenv(matvec?"MOCK_CUDA_MATVEC_PTX":"MOCK_CUDA_ADD_PTX");
if(!path)return 0;
FILE *source=fopen(path,"rb");if(!source)return 0;
unsigned char expected[16385];size_t length=fread(expected,1,16384,source);
if(ferror(source)||!feof(source)||!length){fclose(source);return 0;}
fclose(source);expected[length]=0;
if(strlen(ptx)!=length||memcmp(ptx,expected,length+1))return 0;
return 1;
}
CUresult cuModuleLoadData(void **result,const void *image) {
if(fault(12))return 700;if(require_context())return 201;
const char *ptx=image;
if(!ptx||!strstr(ptx,".version 7.0")||!strstr(ptx,".target sm_75")||!strstr(ptx,".address_size 64")||!strstr(ptx,".entry leleka_vector_add_f32")||!strstr(ptx,"add.rn.f32"))return 218;
if(!ptx||!strstr(ptx,".version 7.0")||!strstr(ptx,".target sm_75")||!strstr(ptx,".address_size 64"))return 218;
int matvec=strstr(ptx,".entry leleka_matvec_f32")!=NULL;
if(!matvec&&!strstr(ptx,".entry leleka_vector_add_f32"))return 218;
if(!exact_image(ptx,matvec))return 218;
if(getenv("MOCK_CUDA_NULL_LOAD")){*result=NULL;trace("load_null",0,0);return 0;}
if(next_module>=16)return 2;
size_t slot=next_module++;modules[slot].handle=(void *)(uintptr_t)(0x100+slot);
modules[slot].function=(void *)(uintptr_t)(0x200+slot);modules[slot].owner=current;
*result=modules[slot].handle;trace("load",0,0);return 0;
modules[slot].matvec=matvec;
*result=modules[slot].handle;trace("load",0,0);
trace(matvec?"module_matvec":"module_add",0,slot);return 0;
}
CUresult cuModuleGetFunction(void **result,void *module,const char *name) {
if(fault(13))return 700;if(require_context()||strcmp(name,"leleka_vector_add_f32"))return 201;
if(fault(13))return 700;if(require_context())return 201;
if(getenv("MOCK_CUDA_NULL_FUNCTION")){*result=NULL;trace("lookup_null",0,0);return 0;}
for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){*result=modules[i].function;trace("lookup",0,0);return 0;}
for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){
if(strcmp(name,modules[i].matvec?"leleka_matvec_f32":"leleka_vector_add_f32"))return 201;
*result=modules[i].function;trace("lookup",0,0);return 0;}
return 201;
}
CUresult cuModuleUnload(void *module) {
if(pending_args){trace("unsafe_pending_unload",0,0);abort();}
if(fault(14))return 700;if(require_context())return 201;
for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){memset(&modules[i],0,sizeof(modules[i]));trace("unload",0,0);return 0;}
for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){
trace(modules[i].matvec?"unload_matvec":"unload_add",0,i);
memset(&modules[i],0,sizeof(modules[i]));trace("unload",0,0);return 0;
}
return 201;
}
CUresult cuLaunchKernel(void *function,unsigned gx,unsigned gy,unsigned gz,unsigned bx,unsigned by,unsigned bz,unsigned shared,void *stream,void **params,void **extra) {
static int capture_arguments(void **params,int matvec,uint32_t n,uint32_t columns,uintptr_t stack_address) {
for(size_t i=0;i<(matvec?5u:4u);i++){
uintptr_t arg=(uintptr_t)params[i];if(!arg||(arg>stack_address-1048576&&arg<stack_address+1048576))return 0;
if(i<3){
uint64_t value=*(uint64_t *)params[i];
size_t expected=(size_t)n*4;
if(matvec&&i==0)expected*=columns;
if(matvec&&i==1)expected=(size_t)columns*4;
if(!lookup(value,expected))return 0;pending_values[i]=value;
}
}
if(pending_values[2]==pending_values[0]||pending_values[2]==pending_values[1])return 0;
return 1;
}
static void record_geometry(int matvec,uint32_t n,uint32_t columns,unsigned gx) {
if(matvec){trace("matvec_rows",0,n);trace("matvec_columns",0,columns);}
trace("geometry",0,gx);trace("arguments",0,n);
}
CUresult cuLaunchKernel(void *function,unsigned gx,unsigned gy,unsigned gz,
unsigned bx,unsigned by,unsigned bz,unsigned shared,
void *stream,void **params,void **extra) {
if(require_context()||!params||extra||stream||shared||gy!=1||gz!=1||bx!=128||by!=1||bz!=1)return 201;
int found=0;for(size_t i=0;i<16;i++)if(modules[i].function==function&&modules[i].owner==current)found=1;
int found=0,matvec=0;
for(size_t i=0;i<16;i++)if(modules[i].function==function&&modules[i].owner==current){
found=1;matvec=modules[i].matvec;
}
if(!found)return 201;
uintptr_t stack_address=(uintptr_t)&found;
uintptr_t table_address=(uintptr_t)params;
if(table_address>stack_address-1048576&&table_address<stack_address+1048576){trace("stack_arguments",1,0);return 1;}
uint32_t n=*(uint32_t *)params[3];
if(!n||gx!=(n+127ull)/128)return 1;
for(size_t i=0;i<3;i++){
uintptr_t arg=(uintptr_t)params[i];if(arg>stack_address-1048576&&arg<stack_address+1048576)return 1;
uint64_t value=*(uint64_t *)params[i];if(!lookup(value,(size_t)n*4))return 1;pending_values[i]=value;
}
if(pending_values[2]==pending_values[0]||pending_values[2]==pending_values[1])return 1;
pending_args=params;pending_n=n;pending_owner=current;
trace("geometry",0,gx);trace("arguments",0,n);
uint32_t columns=matvec?*(uint32_t *)params[4]:0;
if(matvec&&!columns)return 1;
if(!capture_arguments(params,matvec,n,columns,stack_address))return 1;
pending_args=params;pending_n=n;pending_columns=columns;pending_matvec=matvec;pending_owner=current;
record_geometry(matvec,n,columns,gx);
if(fault(15))return 700;trace("launch",0,n);return 0;
}
File diff suppressed because it is too large Load Diff
+501
View File
@@ -0,0 +1,501 @@
# Fixed CUDA f32 matrix-vector requirements
Bounded requirements delta for served item **STRA-140**, parent **STRA-102**,
read fresh on 2026-10-08. Written against source revision
`b9519f967af43514331e29e778bd2605d8e4b98b` before implementation. The active MCP
item and [project charter](../PROJECT_CHARTER.md) are the business/specification
authority; this file is the task's reviewable requirements artifact, not a second
project backlog or an assertion that implementation has passed qualification.
The [bootstrap contract](cuda-driver-bootstrap.md) owns driver loading, platform,
copy staging and resource ownership. The [vector-add contract](cuda-fixed-vector-add.md)
owns the existing fixed operation. STRA-140 adds one bounded fixed matvec action
without changing either historical qualification receipt. Production remains
independent of Python, Strata and a CUDA Toolkit runtime dependency.
## Scope, actor and outcome
An internal engine developer explicitly enables `cuda-driver`, loads the driver,
creates a private context and supplies three owned device buffers and dimensions
to `Context::matvec_f32`. The matrix is contiguous row-major f32, the vector has
one value per column, and the output has one value per row. Success means the
attempted kernel completed and the caller's previous context was restored.
Using `Context::matvec_f32`, the developer can compute the recurrence below over
valid owned buffers, yielding a completed output or structured failure. Invalid
inputs must yield failure before any CUDA mutation. After uncertain completion
or restoration, future work on the context must yield refusal without native work.
This unit is an application/library deliverable with executable automated
verification. It introduces no serving endpoint, deployment integration, model
loader, inference, tensor view/stride, transposition, batching, quantization,
arbitrary executable, caller stream or caller launch geometry. Default feature
admission stays off. It establishes neither model compatibility nor a speed/SLO
claim; the serial column recurrence is a correctness baseline.
## FR-MATVEC-1 — exact shapes, bounds and ownership
The public interface takes an immutable matrix buffer, immutable vector buffer,
exclusive mutable output buffer, and host `usize` row/column dimensions. Dimensions
are checked before conversion to the private ABI; no truncating cast is allowed.
| Quantity | Required admission bound / meaning |
| --- | --- |
| Rows `M` | `1 <= M <= u32::MAX` (4,294,967,295) |
| Columns `N` | `1 <= N <= u32::MAX` (4,294,967,295) |
| Matrix elements | Checked `M * N`; product need not fit u32 |
| Matrix bytes | Checked `4 * M * N`, exactly the matrix buffer length |
| Vector bytes | Checked `4 * N`, exactly the vector buffer length |
| Output bytes | Checked `4 * M`, exactly the output buffer length |
| Every byte length | Nonzero, fits host `usize`, and `<= isize::MAX` |
| Allocation capacity | Existing context byte budget bounds actual live allocations; matvec allocates no device buffer implicitly |
| Launch | Fixed block `(128, 1, 1)`; checked `grid.x = ceil(M / 128)`, `1 <= grid.x <= i32::MAX`; grid y/z one |
| Addressing | 64-bit row/index/byte offsets; checked allocation address ranges cannot wrap |
These are representation and ownership limits, not a promise that the GPU has
enough memory or will admit the fixed launch. On Linux64 the matrix constraint
is `M * N <= floor(isize::MAX / 4) = 2,305,843,009,213,693,951` elements,
further restricted by actual owned allocation sizes and the caller's context
budget. The three buffers normally require `4 * (M*N + N + M)` live bytes,
alongside other context allocations. When the two inputs share one allocation,
charge that allocation once, as the existing allocation accounting does.
The safe API currently exposes only whole owned allocations: `DeviceBuffer::len`
is an exact byte length, with no distinct logical length, spare capacity,
subslice, offset view, cloned handle or raw/imported pointer API. Consequently an
oversized buffer is invalid even if it could contain the requested tensor.
Check each expected byte length for exact equality; do not accept a prefix.
Also reject odd/nonmultiple-four lengths. Shape and overflow refusal must be
possible without allocating a giant test buffer or executing CUDA.
Both inputs and output must belong to this exact `Context` instance. Equal device
ordinals or separate contexts on the same device do not suffice. Reject poisoned
contexts and absent/released resource handles before push/load/lookup/launch.
No validation refusal changes output bytes, allocation accounting or cache state.
### Output alias contract
Inputs may share the same immutable allocation when exact shape checks permit
it; for whole buffers that means `M = 1`. A caller may reuse an output allocation
between completed calls, but output must be a distinct allocation from both
inputs during each call. Rust's immutable input and exclusive mutable output
borrows prevent a safe caller from passing the same buffer as input and output.
Defensively reject equality of output/input device allocation identities before
native mutation, matching the existing vector-add check. Do not create a public
unsafe bypass to test that defense.
Distinct valid live whole allocations from the same CUDA allocator do not
overlap. The present API therefore needs no tensor-view overlap semantics. A
future imported pointer or view API would require a separately specified range
overlap contract before it could consume this operation. Validate non-wrapping
address extents in the private boundary so arithmetic does not rely on silent
u64 wrapping; invalid synthetic address extents must never be launched. Private
alias tests exercise allocation-identity refusal; they do not invent a public
view/import facility.
## FR-MATVEC-2 — deterministic arithmetic and access
For every row `r = 0 .. M-1`, define binary32 recurrence:
```text
s = +0.0_f32
for c = 0 .. N-1 in ascending order:
p = round_nearest_even_f32(matrix[r*N + c] * vector[c])
s = round_nearest_even_f32(s + p)
output[r] = s
```
Use a separate `mul.rn.f32` followed by `add.rn.f32` for every column. No FMA,
floating-point MAD, reassociation, parallel/warp/tree reduction, approximate
operation, saturation, `.ftz`, or f64 accumulator may replace this recurrence.
The accumulator starts at positive zero, including for `N = 1`; it does not
initialize from the first product. All f32 bit patterns are valid inputs.
Signed zeros, subnormals, overflow and infinities follow these operations. NaN
results are compared by classification; NaN payload and sign are not guaranteed.
The arithmetic follows NVIDIA's archived PTX definitions for
[multiply](https://docs.nvidia.com/cuda/archive/13.0.1/parallel-thread-execution/index.html#floating-point-instructions-mul)
and [add](https://docs.nvidia.com/cuda/archive/13.0.1/parallel-thread-execution/index.html#floating-point-instructions-add).
Explicit rounding modifiers preserve the required separate operation semantics;
assembler acceptance alone does not demonstrate installed-driver execution.
One thread owns one row, checks `r < M` before any memory access, loops columns
in order and stores output once after the last addition. Other threads may
process other rows independently. Compute `r`, `r*N+c` and scaled offsets with
64-bit arithmetic, including threads in the last partial block. The loop must
terminate correctly at `N = u32::MAX`; increments and comparisons may not wrap
into another iteration. Matrix/vector are never written. Threads beyond `M`
perform no read or write. No atomics, shared-memory reductions, external symbols
or indirect calls participate.
## FR-MATVEC-3 — trusted executable and fixed launch ABI
Embed one bounded NUL-terminated matvec PTX image containing exactly the fixed
matvec entry `leleka_matvec_f32`. Preserve the existing image's PTX 7.0,
`sm_75`, and `.address_size 64` baseline; incompatible driver/target combinations
return explicit failures. No fallback or external PTX lookup is allowed.
The private `kernelParams` table has five entries, in this order:
| Position | Value stored in owned host argument storage | ABI width |
| --- | --- | --- |
| 0 | Matrix device allocation address | u64 |
| 1 | Vector device allocation address | u64 |
| 2 | Output device allocation address | u64 |
| 3 | Rows `M` | u32 |
| 4 | Columns `N` | u32 |
Each table entry points to its typed host scalar, not directly to a device
address interpreted as a host pointer. Shared bytes are zero; stream and
`extra` are null. Geometry comes only from FR-MATVEC-1. The existing fixed
16-symbol loader suffices; no new driver symbol, caller executable/name,
function/module handle, callback or launch option enters the public API.
Cache only a fully loaded/validated matvec module and non-null function under
its owner context. Repeated successful calls reuse that cache; separate contexts
never share it. The matvec cache adds at most one usable module/function per
context. It must coexist with the existing vector-add cache without replacing,
misidentifying or invalidating vector-add's function. Cache topology and shared
cleanup integration require the ARCH decision below before implementation.
## FR-MATVEC-4 — completion, argument lifetime and faults
Create and stabilize all scalar storage and its five-entry pointer table before
CUDA mutation. Maintain the existing raw-owned stable allocation discipline:
moving the argument owner must not move or retag referenced storage. No caller
host pointer is retained. Scalars/table stay live through mandatory completion.
Push the owned context, check load/lookup and non-null success handles, attempt
the launch once, then synchronize after **every attempted launch**, even a
launch returning failure. Preserve primary and subsequent sync/pop errors in
operation order. Load/lookup failure does not count as an attempted launch.
After every successful push, attempt pop and verify it popped the owned handle.
Return success only when launch, synchronization and restoration all succeed.
After native execution failure, output is unspecified and cannot be presented
as a successfully computed result. A launch failure followed by successful sync
and restoration follows existing policy; it does not by itself imply poisoning.
Never retry a failed launch automatically.
Failed sync makes completion uncertain: poison the context, permanently retain
all potentially referenced host argument storage, keep buffers/module contained
by the context, and refuse future allocate/copy/sync/kernel work without native
calls. Do not reclaim retained argument storage merely because a later destroy
succeeds. A failed or mismatched pop likewise poisons the context; successful
sync alone cannot justify a success result after restoration failure. Existing
copy staging and thread/borrow safety remain part of the contract.
## FR-MATVEC-5 — cache cleanup and teardown
On lookup failure after load, consume the local usable module handle before its
single unload attempt in the owned current context. Preserve lookup, unload and
pop failures in order. Failed unload poisons the context; no retry, cache
publication, handle reuse or healthy cache reinitialization is allowed.
Healthy teardown unloads each usable owned fixed module at most once after work
completed, before context destruction. Pending/uncertain work or a poisoned
context must never be followed by explicit module unload or buffer free.
Any unload/restoration failure must suppress further unsafe cleanup mutations;
context destruction remains the final containment attempt. Explicit fallible
close reports errors; drop stays best effort and nonpanicking. Failed destroy
retains the loaded library. Permanently failed driver cleanup is not a cleanup
success; repeated poisoned contexts may accumulate resources, so this unit
cannot claim process-wide recovery or bounded serving memory.
## Security and non-functional acceptance
| Dimension | Metric / threshold | Verification |
| --- | --- | --- |
| Critical usability | One typed synchronous operation, structured failure, no public raw launch surface | API/source review and synthetic caller |
| Reliability / performance | Success requires launch+sync+restoration; zero automatic retries; one mandatory completion sync per attempted launch; no latency/throughput assertion | ABI and fault traces |
| Capacity / concurrency | Checked bounds above; whole allocations within context budget; creating thread only; at most one additional usable matvec cache/context | Boundary, accounting, cache and compile gates |
| Security / tenancy | In-process context isolation; no network/tenant admission is introduced; zero foreign-context/aliased-output launches; only private fixed executable | Ownership, adversarial alias and ABI review |
| Audit / retention | Only synthetic fixtures; generated traces/artifacts outside Git; record exact source/tool identities and cleanup | Artifact and tracked-file inspection |
| Observability | Fixed operation names and driver codes; preserve primary/cleanup order; errors disclose no pointer/PTX dumps | Error assertions/review |
| Accessibility / i18n | No UI surface or new locale; structured errors remain available to the existing caller | Public-surface review |
| Rate / admission | Synchronous operation on one owning thread with the existing byte budget; no process recovery/rate SLA | API, budget and poison checks |
| Deploy / rollback | Existing opt-in default off; no production consumer or new runtime dependency; caller can omit the new operation | Feature/dependency/consumer inspection |
| Support | Load/lookup/launch/sync/cleanup failures diagnosable; no new production SLA | Fault matrix and documented residuals |
| AI dependence | Zero model/LLM calls in this operation | Consumer/source inspection |
| Integrity / consistency | Inputs unchanged; exact recurrence; no success for partial/uncertain output; only bounded fixed cache persists | Oracle, canary and trace checks |
| Backup / recovery | No durable data created; uncertain teardown retained/reported, never claimed recovered | Fault/source review |
| Privacy | No PII/model/request data in committed fixtures or gate evidence | Fixture/artifact review |
| Maintainability | Existing 16-symbol ABI; bounded fixed matvec module; no new normal dependency | Source/ABI/dependency review |
| Compatibility | Linux64 explicit opt-in; preserve bootstrap/vector-add and ownership behavior; static-musl loader stays unqualified | Existing regression and platform gates |
| Cost / efficiency | CPU-only fixture and offline assembly for this unit; no GPU/device/driver/model access | Recorded container guards and commands |
## Acceptance mapping and planned verification
Expected values come from this recurrence, independently recorded fixtures and
the official ABI, not from wrapper code or PTX parsing. The fake driver witnesses
host argument/dataflow and cleanup; it does not execute PTX. The mock's arithmetic
and oracle must have contraction/reassociation disabled and establish binary32
rounding at each multiply and add; a tolerant f64 dot product is not the oracle.
Declare **zero finite-bit tolerance** against this reference before verification;
compare signed zero bits and non-finite classifications, excluding NaN payloads.
| Served acceptance criterion | Requirement(s) | Required positive and adversarial evidence |
| --- | --- | --- |
| AC-1: checked typed operation | FR-MATVEC-1 | Exact shapes, rectangular matrix and whole-allocation ownership; zero M/N; each dimension u32 max/max+1; checked product/scaling/isize/address/grid bounds; one-byte short/long and nonmultiple4 lengths for each buffer; foreign context on same device; output aliases each input; accepted immutable same-input case M=1; poisoned/refused handles. Refusals produce zero new CUDA trace entries and unchanged accounting/output/cache. Giant limits use pure/private admission instruments, not giant allocations. |
| AC-2: trusted executable | FR-MATVEC-3, FR-MATVEC-5 | Exact PTX bytes/hash and entry; five argument widths/order/values; fixed grid/block/shared/stream/extra; cache reuse and separate contexts; interleave matvec/vector-add; missing fixed symbols fail pre-init; no public arbitrary PTX/name/geometry API. |
| AC-3: column order and separate rounding | FR-MATVEC-2 | Distinct rows/columns detect transpose/stride errors; M=1 and N=1; M=127/128/129 and larger partial block; varying N; input/canary preservation; independent order/FMA-sensitive fixtures; PTX instruction/control-flow inspection plus pinned offline assembly and inspectable emitted instruction evidence. |
| AC-4: lifetime and poison/cleanup | FR-MATVEC-4, FR-MATVEC-5 | Delayed mock reads retained five-argument table/scalars at sync and containment after failed sync, with allocator churn; push/load/lookup/null-success/launch/sync/pop/wrong-pop/unload/destroy faults; launch+sync+pop and lookup+unload combinations; no unload/free while pending; no retry/reuse; preserved error order; healthy unload before destroy and one unload attempt per module. |
| AC-5: CPU and GPU-hidden gates | All | Preserve existing bootstrap/vector-add mock, default/platform, thread/lifetime compile, format and enabled-FFI lint gates; run new ABI/oracle/boundary/fault checks in disposable Linux CPU fixture; pinned offline PTX assembly with no installed driver calls or exposed GPU/device. Report actual counts and receipts; no GPU/model/quality/speed inference. |
Arithmetic adversaries must include the row `[2^24, 1, -2^24]` with all-one
vector (ascending recurrence yields positive zero; a reordered sum can yield
one), and row `[-1, 1+2^-23]` with vector `[1, 1-2^-23]` (separate rounding yields
positive zero; fusing the second multiply/add yields `-2^-46`). Add signed-zero,
subnormal, ties, overflow, infinity and NaN-classification fixtures. These are
fixture expectations, not measured GPU results.
The offline gate must record exact PTX (including its embedded NUL) and assembler
output hashes, pinned image/tool version, target/flags, full argv, source/commit,
host/container architecture, environment/device guards, test counts, exit codes,
and cleanup. Inspect executable instructions/control flow, not comments or the
mere presence of opcode substrings. Establish the ascending loop and separate
multiply/add/no FMA in the recorded offline artifact; its claim is limited to
that tool/target. Installed-driver JIT/numerical execution remains separate.
Keep generated artifacts out of Git and remove only owned disposable resources.
```mermaid
sequenceDiagram
participant Caller as Internal caller
participant Context as Owned Rust context
participant Driver as Fixed Driver ABI
Caller->>Context: matvec_f32(matrix, vector, output, M, N)
Context->>Context: Validate shape, ownership, alias, poison and bounds
alt Validation refusal
Context-->>Caller: Structured error, no CUDA mutation
else Valid
Context->>Context: Own stable five-argument storage
Context->>Driver: Push owned context
Driver-->>Context: Push result
alt Push failure
Context-->>Caller: Structured push error, no launch
else Owned context entered
opt Cache absent
Context->>Driver: Load trusted matvec, look up fixed entry
Driver-->>Context: Handles or load/lookup failure
end
alt Kernel available
Context->>Driver: Attempt fixed launch once
Driver-->>Context: Launch result
Context->>Driver: Mandatory synchronize, including launch error
Driver-->>Context: Completion result
opt Completion uncertain
Context->>Context: Poison and retain referenced storage/resources
end
else No kernel
Context->>Driver: Single safe partial-module cleanup if needed
end
Context->>Driver: Pop, verify owned handle
Driver-->>Context: Restoration result
Context-->>Caller: Success only if launch, sync and restoration succeeded
end
end
```
## Lifecycle and architecture inputs
**Design need: architectural.** The new public buffer operation crosses the safe
Rust ownership/validation boundary into private FFI and fixed executable code,
and adds a second fixed-kernel lifetime under the existing context poison and
teardown state. This classification comes from served AC-2/AC-4 and the existing
`Context::kernel`, `fixed_kernel`, `unload_kernel`, `LaunchArguments` and
`DeviceBuffer` source at the pinned revision. It requires an ARCH pass before DEV.
This BA artifact does not select cache topology or author an architecture option
matrix.
ARCH must confirm the single-thread-per-row, ascending-column mapping and checked
u64 addresses meet the caps; five stable host arguments preserve raw ownership;
matvec and vector-add retain distinct function identities; the additional cache
stays bounded; and an unload/pop fault while tearing down either operation
prevents unsafe subsequent unload/free while preserving final destruction/error
reporting. Return any incompatible requirement for refinement before code changes.
BA has resolved the served row/column and output-alias questions from the fixed
u32 launch convention and exact whole-buffer ownership surface, with overflow
checks above. No user clarification remains for those routine constraints.
Architecture confirmation remains outstanding. No new business-rule conflict was
found with the referenced bootstrap/vector-add/charter invariants.
Lifecycle inputs for root coordination: clarification deliverable is this
contract; design needs the ARCH decision; backend deliverable is the bounded
typed operation and private PTX/FFI integration; testing deliverable is executable
automated CPU and offline assembly evidence. No frontend, visual-composition,
marketing or deployment/runtime-operation artifact is requested. Those scope
observations are not lifecycle waivers or stage closures; root records applicable
stages and gate evidence through the active served process. Existing task
estimates are not re-estimated by this BA unit.
No active host-local `.leasevibe.yaml` pointer was supplied and none is present in
this worktree; host settings are unavailable, never inferred or copied. Root
owns coordination records. This BA unit writes only this file, performs no build,
test suite, assembly, GPU, inference, server, commit or publication operation,
and reports no implementation gate as passed. Static-musl loading, installed
driver/JIT execution, whole-model quality/protocol and paired performance remain
the separate qualification boundaries named in the foundation contracts.
Standing Defaults (§0.10): report honestly, do not cut corners, follow applicable
rules, continue the authorized backlog through root coordination, and be concise.
## Architecture decision
**Status: selected for implementation.** This decision is bounded to STRA-140 at
`b9519f967af43514331e29e778bd2605d8e4b98b`. The user authorized completion and
autonomous routine implementation choices; root confirmed that authorization for
these reversible local seams. It selects no new technology, serving topology or
model scope. FR-MATVEC-1 through FR-MATVEC-5 remain the governing contract.
### Drivers and alternatives
Workload archetype: synchronous, explicitly enabled, single-thread-owned numerical
library operation. RPS, latency SLO and production recovery are unspecified because
this unit has no serving consumer or throughput claim.
| Driver | Evidence / constraint | Design consequence |
| --- | --- | --- |
| Correctness and completion | Charter priorities; FR-MATVEC-2/-4 | Serial ascending recurrence and mandatory completion before success |
| Capacity / concurrency | FR-MATVEC-1/-3; existing `Context` and `Rc` ownership | Two bounded fixed caches per context, creating thread only |
| Isolation and operability | Existing `enter`, `CurrentGuard`, `combine`, `destroy` | One context poison state; ordered fallible cleanup and final containment |
| Cost / deployment | Existing `cuda-driver` opt-in, fixed16 ABI and libc dependency | No new runtime dependency or installed Toolkit requirement |
| Data / organization | Three transient owned buffers; existing Rust/FFI boundary | Data Model: N/A for this operation; no durable state, UI or new team/process boundary |
| Option | Workload / scale | Latency / cold load | Operations / cost | Debugging / readiness | Isolation | Portability / lock-in |
| --- | --- | --- | --- | --- | --- | --- |
| **A: two named cache slots, closed private operation selector** | Exact two-operation bound | Each image loads once on first valid use | Two modules maximum; existing cleanup machinery | Distinct identities, localized source changes | Context owns both; shared poison | Existing Driver/PTX limits only |
| B: one combined image and two functions | Bounded, but couples existing operation to new image | One module load; matvec bytes load for vector-add callers | One unload, broader regression surface | Changes historical vector-add image identity | Same owner and poison | Same Driver/PTX limits |
| C: replaceable single cache or generic kernel registry | Replacement causes reload; registry adds unnecessary growth policy | Reloads or generalized lookup | More invalidation/ownership policy | More state and generic dispatch to audit | Requires extra eviction/lifetime rules | Encourages a future arbitrary executable surface |
- A pros: preserves vector-add executable identity, isolates lazy initialization,
and makes the two-module bound explicit. Cons: cleanup must sequence two slots.
- B pros: one module lifecycle. Cons: changes the already qualified image and
couples vector-add admission to matvec loading; rejected for this bounded delta.
- C pros: replacement can cap one module, and a registry can accommodate future
operations. Cons: adds reloads or speculative generality; rejected because the
requirements need coexistence of exactly two trusted operations.
**Architecture Decision: A.** **Architecture Alternatives Considered: B and C**
with the rejection reasons above. The architecture-strategy user-decision step
is satisfied by the existing implementation authorization confirmed by root;
there is no new unresolved external architecture choice to request.
### Selected source seams and invariants
In `crates/cuda-driver/src/lib.rs`, retain `FixedKernel` and introduce two named
`Cell<Option<FixedKernel>>` slots for vector-add and matvec. A private closed
`FixedOperation` enum selects only those slots and their trusted FFI bindings.
It carries no caller bytes, names, handles or launch options. Publish a slot only
after module load and non-null function lookup both succeed. Cache reuse is
per-operation and per-context; no process/global map or eviction is introduced.
Keep safe validation and orchestration in `lib.rs`; all raw pointer handling
stays in `ffi.rs`. Add a pure checked matvec shape helper producing three expected
byte lengths, ABI rows/columns and row grid. Require exact buffer lengths and
exact context identity, live context/buffer handles, and output allocation
inequality before native calls. Use checked dimensions/product/scaling and
`valid_size`; compute ceil(M/128) in u64 before bounded conversion. Add a private
FFI extent check using checked u64 base-plus-byte-length for each live buffer;
synthetic wraparound refuses before `enter`. Inputs sharing the same whole
allocation remain valid when M=1. A structured matvec shape/range error may be
added; ownership, alias and poison errors retain their existing meanings and
driver errors retain operation/code and `combine` ordering.
In `ffi.rs`, embed `matvec.ptx` with a final NUL alongside the unchanged vector-add
image. The closed selector matches each image and fixed C entry name explicitly.
Extend both enabled and unsupported API implementations consistently; keep the
existing sixteen symbol resolutions and their pre-init missing-symbol behavior.
Keep vector-add's four-argument launch unchanged; add a private matvec launch
with the same fixed geometry/shared/stream/extra policy and five-argument owner.
Do not introduce a public or crate-generic raw parameter launch interface.
Matvec argument storage contains three u64 addresses, two separate u32 scalars
(rows, columns), and five host parameter pointers. Convert its allocation with
`Box::into_raw` before forming field pointers using raw projections; its moving
owner contains only `NonNull` and never recreates a reference to the whole
allocation while the pointers are live. Populate every scalar/table entry before
`enter`. Reconstruct the Box exactly once before any launch or after successful
sync; on failed sync permanently forget the owner, including its pointer table.
Moving the owner or borrowing the owner for launch must not move/retag the
storage. A later successful destroy never reclaims forgotten arguments.
`matvec.ptx` uses the fixed five-entry ABI and PTX7.0/sm_75/address64 baseline.
Compute row as wide block-index times 128 plus widened thread-index, guard row
against widened M before memory access, and use u64 for N, column counter,
row*N+column and byte offsets. A u64 counter allows N=u32::MAX to terminate
without wrap. Begin with positive-zero bits, issue separate `mul.rn.f32` then
`add.rn.f32` for each ascending column, and store once. This is a correctness
baseline; neither source shape nor offline assembler acceptance proves installed
driver execution or performance.
Both operations use the same `poisoned` cell and `CurrentGuard`. After an attempted
launch, synchronize exactly once even on launch error, then attempt and verify
pop after every successful push. Compose launch, sync and pop errors in that
order. Lookup failure consumes its local module before one unload attempt;
unload failure poisons the shared context, and no partial cache is published.
Load/lookup failure has no launch sync. No automatic launch or unload retry occurs.
Refactor `unload_kernel` into a bounded slot-cleanup helper and sequential
`unload_kernels`: vector-add slot first, then matvec slot. Each helper consumes
its usable slot before an unload attempt, checks shared poison before push,
unloads only with the owned context current, then finishes the guard. A push,
unload, failed pop or wrong-pop failure poisons the context before another slot
can mutate CUDA. Thus failure in the first cleanup suppresses second unload;
failure in the second still suppresses later explicit frees. A poisoned slot is
only discarded as a usable Rust handle; its native resource remains contained
by the context. `destroy` always performs the final owned non-current context
destruction attempt and preserves earlier cleanup errors; failed destroy retains
the library. Existing buffer free admission through `enter` supplies the shared
poison defense. Drop stays nonpanicking. This is containment, not recovery.
The level above this change comprises typed owned resources in `lib.rs`, private
Driver bindings and argument ownership in `ffi.rs`, and trusted executable bytes
in PTX; `Context` orchestrates those boundaries. This change belongs inside those
existing units because they own shape admission, module lifetime and completion.
A serving/model layer or public general kernel executor would be appropriate
only if separately authorized consumer/launch contracts existed; neither does.
No durable-state capability or persistence-layer change is introduced.
### Handoff and revisit conditions
Required DEV paths are `crates/cuda-driver/src/lib.rs` (API, checked admission,
cache and teardown, inline pure boundary tests), `crates/cuda-driver/src/ffi.rs`
(closed fixed bindings, extent validation and argument ownership, inline private
tests), new `crates/cuda-driver/src/matvec.ptx`, and
`scripts/test-cuda-fixed-ptx.sh` (extend existing pinned offline gate, including
inspectable instruction/control-flow evidence). Automated fixture integration
belongs to the separately routed test owner in existing
`crates/cuda-driver/tests/mock_cuda.c`,
`crates/cuda-driver/tests/mock_driver.rs` and
`scripts/test-cuda-driver-bootstrap.sh`; this decision does not transfer its claim.
No DevOps/IaC work, dependency, CI topology or new child task is implied.
FR-MATVEC acceptance cases remain mandatory. In addition to shape/rounding cases,
the cross-operation witnesses must interleave add/matvec/add and matvec/add/matvec,
prove distinct function/module identity and one lazy load per slot, and inject
each slot's unload/pop failure with both caches populated. After any poison,
attempt the other operation, allocation, copy, sync and releases: none may call
CUDA. Delayed mock reads must dereference all five arguments at sync and pending
containment after owner movement/allocator churn; no unload/free may precede
uncertain completion. Pure boundary tests cover address wrap and giant geometry
without allocating giant buffers. The independent oracle retains zero finite-bit
tolerance, signed-zero bits and non-finite classification limits declared above.
The safe Rust to private native execution crossing merits §809 review; root
records the canonical served threat-model artifact before DESIGN closes, using
the trust-boundary input returned with this decision. No committed threat-model
copy substitutes for that served carrier. LIGHT/FULL, implementation and GPU
gates remain root-coordinated; this section reports no such gate as passed.
Revisit only when a separately specified third fixed operation needs generalized
reuse, asynchronous completion is introduced, or views/imported pointers create
range overlap. First specify its admission/ownership/cleanup contract, then
extend or replace these seams under a new decision and qualification gates.
Rollback for this unit is omission of the new API/image changes and restoration
of the existing vector-add cache path; no stored data migration is needed.
Screened companion decisions (argument layout, u64 counter, fixed teardown order)
are reversible local choices or directly required by FR-MATVEC, so none satisfies
all three grounds for an additional durable ADR. No BA correction is required;
installed-driver/JIT, static-musl loading, model quality and paired performance
remain separately qualified boundaries. No implementation ambiguity remains.
+96 -3
View File
@@ -9,6 +9,7 @@ import re
import shutil
import stat
import subprocess
import sys
import tempfile
import uuid
@@ -17,6 +18,9 @@ NAME = 'strata-next-linux-x86_64-musl'
FILES = {NAME, 'PROVENANCE.json', 'SHA256SUMS'}
# Official Ubuntu 26.04 linux/amd64 manifest, observed 2026-10-04; glibc is probed.
BASE = 'ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794'
PROBE_INFRA_TIMEOUT = 120
PROBE_APP_TIMEOUT = 30
PROBE_OUTPUT_LIMIT = 64 * 1024
def digest(path):
@@ -124,18 +128,107 @@ def docker(*args, timeout=30, check=True):
check=check, timeout=timeout)
def _bounded_output(value, stream):
if not isinstance(value, str) or len(value.encode('utf-8')) > PROBE_OUTPUT_LIMIT:
raise ValueError(f'isolated CLI {stream} exceeds {PROBE_OUTPUT_LIMIT}-byte limit')
return value
def _report_best_effort(message):
try:
print(message, file=sys.stderr, flush=True)
except BaseException:
pass
def _safe_report(message):
try:
_report_best_effort(message)
except BaseException:
pass
def _diagnose_owned_container(name):
for label, args in (
('inspect', ('inspect', '--format', '{{json .State}}', name)),
('logs', ('logs', '--tail', '40', name)),
):
try:
result = docker(*args, timeout=8, check=False)
output = (result.stdout or '') + (result.stderr or '')
if len(output.encode('utf-8')) > PROBE_OUTPUT_LIMIT:
output = '[earlier output truncated]\n' + output[-PROBE_OUTPUT_LIMIT:]
_safe_report(
f'Owned runtime-image probe {label} (exit {result.returncode}):\n{output}')
except BaseException as error:
_safe_report(
f'Owned runtime-image probe {label} unavailable: {type(error).__name__}')
def isolated_run(image, arguments, *, entrypoint=None):
name = 'strata-image-probe-' + uuid.uuid4().hex
args = ['run', '--name', name, '--rm', '--platform', 'linux/amd64', '--network', 'none',
args = ['create', '--name', name, '--platform', 'linux/amd64', '--network', 'none',
'--read-only', '--user', '65532:65532', '--cap-drop', 'ALL',
'--security-opt', 'no-new-privileges', '-e', 'CUDA_VISIBLE_DEVICES=',
'-e', 'NVIDIA_VISIBLE_DEVICES=void']
if entrypoint:
args += ['--entrypoint', entrypoint]
primary_error = None
try:
return docker(*args, image, *arguments).stdout
created = docker(*args, image, *arguments, timeout=PROBE_INFRA_TIMEOUT)
_bounded_output(created.stdout, 'create output')
docker('start', name, timeout=PROBE_INFRA_TIMEOUT)
waited = docker('wait', name, timeout=PROBE_APP_TIMEOUT, check=False)
_bounded_output(waited.stdout, 'wait status')
_bounded_output(waited.stderr, 'wait stderr')
if waited.returncode:
raise subprocess.CalledProcessError(
waited.returncode, ['docker', 'wait', name],
output=waited.stdout, stderr=waited.stderr)
if not re.fullmatch(r'(?:0|[1-9][0-9]{0,2})\n?', waited.stdout):
raise ValueError('docker wait returned a malformed CLI exit status')
exit_status = int(waited.stdout.rstrip('\n'))
if exit_status > 255:
raise ValueError('docker wait returned a CLI exit status outside 0..255')
logs = docker('logs', name, timeout=30, check=False)
stdout = _bounded_output(logs.stdout, 'stdout')
stderr = _bounded_output(logs.stderr, 'stderr')
if logs.returncode:
raise subprocess.CalledProcessError(
logs.returncode, ['docker', 'logs', name], output=stdout, stderr=stderr)
if exit_status:
raise subprocess.CalledProcessError(
exit_status, ['docker', 'container', 'probe', name],
output=stdout, stderr=stderr)
if stderr:
_report_best_effort(f'Runtime-image probe stderr:\n{stderr}')
return stdout
except BaseException as error:
primary_error = error
try:
_diagnose_owned_container(name)
except BaseException as diagnostic_error:
_safe_report(
f'Owned runtime-image probe diagnostics failed: {type(diagnostic_error).__name__}')
raise
finally:
docker('rm', '-f', name, check=False)
cleanup_error = None
try:
result = docker('rm', '-f', name, timeout=10, check=False)
if result.returncode:
cleanup_error = subprocess.CalledProcessError(
result.returncode, ['docker', 'rm', '-f', name],
output=result.stdout, stderr=result.stderr)
except BaseException as error:
cleanup_error = error
if cleanup_error is not None:
if primary_error is None:
raise cleanup_error
_safe_report(
f'Owned runtime-image probe cleanup failed after '
f'{type(primary_error).__name__}: {type(cleanup_error).__name__}')
def assemble(args):
+1 -2
View File
@@ -5,8 +5,6 @@ repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py"
python3 "${repo_root}/scripts/test-benchmark-harness.py"
python3 "${repo_root}/scripts/test-paired-report.py"
python3 "${repo_root}/scripts/test-paired-markdown.py"
python3 "${repo_root}/scripts/test-native-service.py"
python3 "${repo_root}/scripts/test-native-api.py"
python3 "${repo_root}/scripts/test-native-menu.py"
@@ -16,6 +14,7 @@ python3 "${repo_root}/scripts/test-static-cuda-profile.py"
python3 "${repo_root}/scripts/test-static-cuda-elf.py"
python3 "${repo_root}/scripts/test-linux-package.py"
python3 "${repo_root}/scripts/test-runtime-image.py"
python3 "${repo_root}/scripts/test-ple-config-parity.py"
python3 "${repo_root}/scripts/test-gitea-release.py"
python3 "${repo_root}/scripts/test-keyless-routing.py"
+439
View File
@@ -0,0 +1,439 @@
#!/usr/bin/env python3
"""Offline, secret-safe preflight for the Qwen GPU-PLE profile migration.
This can prove selected settings and the explicitly supplied KAR file digest.
It cannot certify deployed parity: credential, model-pack, MTP and incomplete
environment identity remain unverified unless separately established. The
legacy input must be an operator-supplied redacted projection, not the complete
original config; this proves no credential equivalence. Credential-bearing JSON
is rejected with a static category after parsing and must not be supplied.
"""
import argparse
import hashlib
import json
import os
import re
import stat
import sys
from pathlib import Path
PINNED_ARCHIVE_SHA256 = '536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5'
PINNED_NATIVE_SHARD = 'Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf'
PINNED_NATIVE_MANIFEST = 'qwen3.8-flash-next-iq3-s.json'
MAX_JSON_BYTES = 1024 * 1024
MAX_ARCHIVE_BYTES = 100 * 1024**3
MAX_ASSET_BUNDLES = 16
U64_MAX = (1 << 64) - 1
LEGACY_KEYS = {'exe', 'args', 'cwd', 'log'}
FILE_CONFIG_KEYS = {
'queue_timeout_s', 'mtp_pack', 'response_history_dir', 'assets',
'native_model', 'gpu_requirement', 'cuda_memory', 'engine_probe',
'shutdown_grace_s', 'max_in_flight_requests', 'api_key_file', 'bind',
'model', 'engine',
}
ENGINE_KEYS = {
'executable', 'args', 'startup_timeout_s', 'generation_timeout_s',
'max_restarts', 'tokenizer_dir',
}
ASSET_KEYS = {'manifest', 'directory'}
NATIVE_MODEL_KEYS = {'manifest', 'source_dir', 'output', 'runtime_profile'}
CUDA_MEMORY_KEYS = {'required_mib', 'reserve_mib'}
NONSECRET_ENV = {
'STRATA_BIND', 'STRATA_MODEL_ID', 'STRATA_ENGINE_EXE',
'STRATA_ENGINE_ARGS_JSON', 'STRATA_STARTUP_TIMEOUT_S',
'STRATA_GENERATION_TIMEOUT_S', 'STRATA_MAX_WORKER_RESTARTS',
'STRATA_TOKENIZER_DIR', 'STRATA_MAX_IN_FLIGHT_REQUESTS',
'STRATA_QUEUE_TIMEOUT_S', 'STRATA_SHUTDOWN_GRACE_S',
'STRATA_RESPONSE_HISTORY_DIR', 'CUDA_VISIBLE_DEVICES',
}
REQUIRED_SETTINGS = {
'--max-context': '262144', '--kv': 'int8', '--kv-resident': '32768',
'--spec': '4', '--spec-min-p': '0.5', '--expert-cache': 'auto',
'--prefill': 'auto', '--vram-reserve-mib': '700',
}
PLE_FLAGS = ('--ple-kar', '--ple-kar-level', '--ple-kar-gpu-cache-mib')
UNVERIFIED = {
'authentication_equivalence', 'legacy_pack_content_equivalence',
'mtp_content_equivalence', 'native_runtime_defaults', 'http_capacity_policy',
'worker_slot_count', 'request_model_identity', 'source_config_projection',
}
class InvalidInput(ValueError):
pass
def _pairs(pairs):
result = {}
for key, value in pairs:
if key in result:
raise InvalidInput('duplicate_json_key')
result[key] = value
return result
def _constant(_value):
raise InvalidInput('nonstandard_json_constant')
def read_json(path):
try:
with open_regular(path, 'invalid_json') as stream:
if os.fstat(stream.fileno()).st_size > MAX_JSON_BYTES:
raise InvalidInput('json_size_limit')
data = stream.read(MAX_JSON_BYTES + 1)
if len(data) > MAX_JSON_BYTES:
raise InvalidInput('json_size_limit')
return json.loads(data.decode('utf-8'), object_pairs_hook=_pairs,
parse_constant=_constant)
except InvalidInput:
raise
except (OSError, UnicodeError, json.JSONDecodeError, RecursionError, OverflowError):
raise InvalidInput('invalid_json') from None
def open_regular(path, category):
# O_NOFOLLOW and O_NONBLOCK are required together: never fall back to
# following a symlink or waiting for a FIFO on unsupported platforms.
if not hasattr(os, 'O_NOFOLLOW') or not hasattr(os, 'O_NONBLOCK'):
raise InvalidInput('safe_file_open_unavailable')
flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
if hasattr(os, 'O_CLOEXEC'):
flags |= os.O_CLOEXEC
try:
fd = os.open(os.fspath(path), flags)
except (OSError, TypeError, ValueError):
raise InvalidInput(category) from None
try:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise InvalidInput(category)
return os.fdopen(fd, 'rb')
except BaseException as error:
try:
os.close(fd)
except OSError:
pass
if isinstance(error, InvalidInput):
raise
if isinstance(error, OSError):
raise InvalidInput(category) from None
raise
def _keys(value, allowed, category):
if not isinstance(value, dict) or not set(value).issubset(allowed):
raise InvalidInput(category)
def _string(value):
return isinstance(value, str) and bool(value)
def _strings(value):
return isinstance(value, list) and all(isinstance(item, str) for item in value)
def validate_legacy(value):
if isinstance(value, dict) and 'api_key' in value:
raise InvalidInput('legacy_credential_present')
_keys(value, LEGACY_KEYS, 'legacy_schema')
if set(value) != LEGACY_KEYS or not all(_string(value[key]) for key in ('exe', 'cwd', 'log')):
raise InvalidInput('legacy_schema')
if not _strings(value['args']):
raise InvalidInput('legacy_schema')
def validate_candidate(value):
_keys(value, FILE_CONFIG_KEYS, 'candidate_schema')
if 'engine' not in value or not isinstance(value['engine'], dict):
raise InvalidInput('candidate_schema')
_keys(value['engine'], ENGINE_KEYS, 'candidate_schema')
engine = value['engine']
if not _string(engine.get('executable')) or not _strings(engine.get('args', [])):
raise InvalidInput('candidate_schema')
for key, low, high in (('startup_timeout_s', 1, 3600),
('generation_timeout_s', 1, 86400),
('max_restarts', 0, 3)):
if key in engine and (type(engine[key]) is not int or not low <= engine[key] <= high):
raise InvalidInput('candidate_schema')
if 'tokenizer_dir' in engine and not _string(engine['tokenizer_dir']):
raise InvalidInput('candidate_schema')
if 'native_model' not in value or not isinstance(value['native_model'], dict):
raise InvalidInput('candidate_schema')
_keys(value['native_model'], NATIVE_MODEL_KEYS, 'candidate_schema')
if set(value['native_model']) != NATIVE_MODEL_KEYS or value['native_model'].get('runtime_profile') != 'qwen4exp-flash-next':
raise InvalidInput('candidate_schema')
for key in ('manifest', 'source_dir', 'output'):
if not _string(value['native_model'].get(key)):
raise InvalidInput('candidate_schema')
assets = value.get('assets', [])
if (not isinstance(assets, list) or len(assets) > MAX_ASSET_BUNDLES or
not all(isinstance(asset, dict) for asset in assets)):
raise InvalidInput('candidate_schema')
for asset in assets:
_keys(asset, ASSET_KEYS, 'candidate_schema')
if set(asset) != ASSET_KEYS or not all(_string(asset[key]) for key in ASSET_KEYS):
raise InvalidInput('candidate_schema')
if 'cuda_memory' in value:
_keys(value['cuda_memory'], CUDA_MEMORY_KEYS, 'candidate_schema')
if set(value['cuda_memory']) != CUDA_MEMORY_KEYS:
raise InvalidInput('candidate_schema')
required, reserve = (value['cuda_memory'][key] for key in ('required_mib', 'reserve_mib'))
if (type(required) is not int or type(reserve) is not int or required <= 0 or reserve < 0 or
required > U64_MAX or reserve > U64_MAX or required + reserve > U64_MAX):
raise InvalidInput('candidate_schema')
if 'gpu_requirement' in value and value['gpu_requirement'] != 'cuda-13.0-linux':
raise InvalidInput('candidate_schema')
for key in ('mtp_pack', 'response_history_dir', 'api_key_file', 'bind', 'model'):
if key in value and not _string(value[key]):
raise InvalidInput('candidate_schema')
if 'queue_timeout_s' in value and (type(value['queue_timeout_s']) is not int or
not 1 <= value['queue_timeout_s'] <= 86400):
raise InvalidInput('candidate_schema')
if 'shutdown_grace_s' in value and (type(value['shutdown_grace_s']) is not int or
not 0 <= value['shutdown_grace_s'] <= 20):
raise InvalidInput('candidate_schema')
if 'max_in_flight_requests' in value and (type(value['max_in_flight_requests']) is not int or
not 1 <= value['max_in_flight_requests'] <= 256):
raise InvalidInput('candidate_schema')
if 'engine_probe' in value and type(value['engine_probe']) is not bool:
raise InvalidInput('candidate_schema')
if 'mtp_pack' not in value or not _string(value['mtp_pack']):
raise InvalidInput('candidate_schema')
if 'tokenizer_dir' in engine:
raise InvalidInput('candidate_schema')
def validate_context(value):
_keys(value, {'legacy', 'candidate', 'environment_complete'}, 'service_context_schema')
if set(value) != {'legacy', 'candidate', 'environment_complete'} or not isinstance(value['environment_complete'], bool):
raise InvalidInput('service_context_schema')
for side in ('legacy', 'candidate'):
item = value[side]
allowed = {'bind', 'cwd', 'log', 'effective_slots', 'environment'}
required = allowed - {'effective_slots'}
_keys(item, allowed, 'service_context_schema')
if not required.issubset(item) or not all(_string(item[k]) for k in ('bind', 'cwd', 'log')):
raise InvalidInput('service_context_schema')
if ('effective_slots' in item and
(type(item['effective_slots']) is not int or item['effective_slots'] < 0)):
raise InvalidInput('service_context_schema')
env = item['environment']
if not isinstance(env, dict) or not set(env).issubset(NONSECRET_ENV):
raise InvalidInput('service_context_schema')
if not all(isinstance(v, str) for v in env.values()):
raise InvalidInput('service_context_schema')
def option_values(arguments, name):
found = []
index = 0
while index < len(arguments):
token = arguments[index]
if token == name:
if index + 1 >= len(arguments) or arguments[index + 1].startswith('--'):
raise InvalidInput('engine_arguments')
found.append(arguments[index + 1])
index += 2
elif token.startswith(name + '='):
found.append(token[len(name) + 1:])
index += 1
else:
index += 1
if len(found) > 1:
raise InvalidInput('duplicate_engine_option')
return found
def strip_legacy_migrations(arguments):
result = []
migrated = {'--pack', '--native', '--mtp'}
seen = set()
index = 0
while index < len(arguments):
token = arguments[index]
name = token.split('=', 1)[0]
if name in migrated:
if name in seen or token != name or index + 1 >= len(arguments) or arguments[index + 1].startswith('--'):
raise InvalidInput('legacy_model_arguments')
seen.add(name)
index += 2
else:
result.append(token)
index += 1
if seen != migrated:
raise InvalidInput('legacy_model_arguments')
return result
def ple_selection(arguments, archive_path):
"""Return argv without its PLE tuple and whether the exact tuple was present."""
seen = [token for token in arguments
if any(token == flag or token.startswith(flag + '=') for flag in PLE_FLAGS)]
if not seen:
return list(arguments), False
expected = [PLE_FLAGS[0], str(archive_path), PLE_FLAGS[1], '2', PLE_FLAGS[2], '64']
if arguments[-len(expected):] != expected:
raise InvalidInput('ple_arguments')
if len(seen) != len(PLE_FLAGS):
raise InvalidInput('ple_arguments')
return list(arguments[:-len(expected)]), True
def check_archive(path, expected):
if not re.fullmatch(r'[0-9a-f]{64}', expected) or expected != PINNED_ARCHIVE_SHA256:
raise InvalidInput('archive_pin')
try:
stream = open_regular(path, 'archive_file')
with stream:
if os.fstat(stream.fileno()).st_size > MAX_ARCHIVE_BYTES:
raise InvalidInput('archive_size_limit')
_verify_archive_stream(stream, expected)
except InvalidInput:
raise
except OSError:
raise InvalidInput('archive_file') from None
def _verify_archive_stream(stream, expected):
digest = hashlib.sha256()
size = 0
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
size += len(chunk)
if size > MAX_ARCHIVE_BYTES:
raise InvalidInput('archive_size_limit')
digest.update(chunk)
if digest.hexdigest() != expected:
raise InvalidInput('archive_digest')
def compare(legacy, candidate, context, archive_path, archive_sha, expected_executable,
expected_bind, expected_log):
validate_legacy(legacy)
validate_candidate(candidate)
validate_context(context)
check_archive(archive_path, archive_sha)
mismatches = []
unverified = sorted(UNVERIFIED)
engine = candidate['engine']
legacy_args = legacy['args']
candidate_args = engine.get('args', [])
legacy_env = context['legacy']['environment']
candidate_env = context['candidate']['environment']
effective_executable = candidate_env.get('STRATA_ENGINE_EXE', engine['executable'])
effective_bind = candidate_env.get('STRATA_BIND', candidate.get('bind', '127.0.0.1:8081'))
if effective_executable != expected_executable or not _string(expected_executable):
mismatches.append('executable_selection')
slots = [context[side].get('effective_slots') for side in ('legacy', 'candidate')]
if any(value is None for value in slots):
unverified.append('worker_slot_count')
elif slots != [1, 1]:
mismatches.append('slot_count')
if context['legacy']['cwd'] != context['candidate']['cwd']:
mismatches.append('working_directory')
if context['candidate']['bind'] != expected_bind or effective_bind != context['candidate']['bind']:
mismatches.append('bind_selection')
if context['candidate']['log'] != expected_log:
mismatches.append('log_selection')
for name in set(legacy_env) | set(candidate_env):
if legacy_env.get(name) == candidate_env.get(name):
continue
if name == 'STRATA_BIND':
# The bind delta is explicit and independently checked above.
continue
if name == 'STRATA_ENGINE_EXE' and candidate_env.get(name) == expected_executable:
# The executable delta is explicit and independently checked above.
continue
mismatches.append('environment_delta')
break
effective_args = candidate_args
if 'STRATA_ENGINE_ARGS_JSON' in candidate_env:
try:
override = json.loads(candidate_env['STRATA_ENGINE_ARGS_JSON'], object_pairs_hook=_pairs,
parse_constant=_constant)
except (InvalidInput, json.JSONDecodeError):
mismatches.append('engine_arguments')
else:
if not _strings(override):
mismatches.append('engine_arguments')
else:
effective_args = override
if effective_args != candidate_args:
mismatches.append('engine_arguments')
if 'STRATA_ENGINE_ARGS_JSON' in legacy_env:
mismatches.append('environment_delta')
if not context['environment_complete']:
unverified.append('effective_environment')
try:
legacy_base, _had_legacy_ple = ple_selection(legacy_args, archive_path)
legacy_base = strip_legacy_migrations(legacy_base)
candidate_base, had_candidate_ple = ple_selection(effective_args, archive_path)
expected_base = legacy_base + [
PLE_FLAGS[0], str(archive_path), PLE_FLAGS[1], '2', PLE_FLAGS[2], '64']
if not had_candidate_ple or candidate_base != legacy_base or effective_args != expected_base:
mismatches.append('engine_arguments')
for flag, wanted in REQUIRED_SETTINGS.items():
if option_values(legacy_args, flag) != [wanted] or option_values(effective_args, flag) != [wanted]:
mismatches.append('profile_settings')
for flag in ('--pack', '--native', '--gguf', '--mtp'):
if option_values(effective_args, flag):
mismatches.append('native_asset_mapping')
legacy_mtp = option_values(legacy_args, '--mtp')
legacy_native = option_values(legacy_args, '--native')
if legacy_mtp != [candidate.get('mtp_pack')]:
mismatches.append('mtp_asset_mapping')
if (len(legacy_native) != 1 or Path(legacy_native[0]).name != PINNED_NATIVE_SHARD or
Path(candidate['native_model']['source_dir']) != Path(legacy_native[0]).parent or
Path(candidate['native_model']['manifest']).name != PINNED_NATIVE_MANIFEST):
mismatches.append('model_selection')
except InvalidInput as error:
mismatches.append(error.args[0] if error.args and error.args[0] in {
'legacy_model_arguments', 'duplicate_engine_option', 'engine_arguments', 'ple_arguments'
} else 'engine_arguments')
if candidate.get('mtp_pack') not in [asset['directory'] for asset in candidate.get('assets', [])]:
mismatches.append('mtp_asset_mapping')
if context['legacy']['bind'] == '' or context['legacy']['log'] == '':
mismatches.append('service_context')
if candidate.get('api_key_file') is None:
mismatches.append('authentication_configuration')
# The candidate's strict schema is checked, but source pack/MTP contents and
# credentials are intentionally not opened by this preflight.
return {
'status': 'mismatch' if mismatches else 'incomplete' if unverified else 'verified',
'mismatches': sorted(set(mismatches)),
'unverified': sorted(set(unverified)),
}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--legacy-config', required=True,
help='operator-supplied redacted projection (exe/args/cwd/log only; never the original file or api_key)')
parser.add_argument('--candidate-config', required=True)
parser.add_argument('--service-context', required=True)
parser.add_argument('--archive', required=True)
parser.add_argument('--archive-sha256', required=True)
parser.add_argument('--expected-executable', required=True)
parser.add_argument('--expected-bind', required=True)
parser.add_argument('--expected-log', required=True)
args = parser.parse_args(argv)
try:
result = compare(read_json(args.legacy_config), read_json(args.candidate_config),
read_json(args.service_context), args.archive, args.archive_sha256,
args.expected_executable, args.expected_bind, args.expected_log)
except InvalidInput as error:
result = {'status': 'mismatch', 'mismatches': [error.args[0]], 'unverified': sorted(UNVERIFIED)}
except Exception:
result = {'status': 'mismatch', 'mismatches': ['internal_validation_error'],
'unverified': sorted(UNVERIFIED)}
print(json.dumps(result, sort_keys=True))
return {'verified': 0, 'mismatch': 1, 'incomplete': 2}[result['status']]
if __name__ == '__main__':
sys.exit(main())
+139 -453
View File
@@ -1,379 +1,69 @@
#!/usr/bin/env python3
"""Descriptively compare two private, sequential bench-chat-paired.py runs.
"""Compare two private, sequential runs of bench-chat-paired.py.
No performance/model-quality qualification follows from this offline report.
Useful on one GPU when both model arms cannot fit in VRAM together. The output
is a descriptive paired report; load order and disk/cache drift still matter.
"""
import argparse
import datetime as dt
import json
import math
import os
from pathlib import Path
import statistics
import sys
MAX_INPUT_BYTES = 32 * 1024 * 1024
MAX_CASES = 64
MAX_PAIRS = 4096
MAX_REPEATS = 100
MAX_NUMBER = 1e12
COUNT_FIELDS = {"prompt_n", "predicted_n", "cache_n", "draft_n", "draft_accepted_n"}
USAGE_COUNTS = {"prompt_tokens", "completion_tokens", "total_tokens", "input_tokens",
"output_tokens", "cached_tokens", "reasoning_tokens",
"accepted_prediction_tokens", "rejected_prediction_tokens"}
# Canonical private metadata keys. Presence is an operator assertion, not proof.
PROVENANCE_FIELDS = (
"engine_commit", "control_plane_commit", "model_sha256", "quantization",
"gpu", "driver", "cuda_toolkit", "power_limit_watts", "context_tokens",
"kv_configuration", "slots", "batch_size", "speculation", "cache_state",
"workload_sha256", "quality_gate_result", "draft_acceptance_rate",
"expert_cache_hit_rate", "kv_streaming_hit_rate",
)
LIMITATION = (
"Descriptive only: sequential model loads and requests may drift with I/O, "
"cache state and load order; repeats may be correlated. Synthetic/CPU "
"results and supplied metadata do not qualify GPU inference, end-to-end "
"agent performance or model quality. Pooled cases/categories depend on "
"their case composition; uncertainty assumes independent pairs sharing "
"a common population median."
)
def reject(message):
# Fixed field names only; never include values from a private report.
raise ValueError(message)
def integer(value, minimum=0, maximum=int(MAX_NUMBER)):
return type(value) is int and minimum <= value <= maximum
def number(value, positive=False):
return (type(value) in (int, float) and math.isfinite(value)
and (value > 0 if positive else value >= 0) and value <= MAX_NUMBER)
def label(value):
return isinstance(value, str) and bool(value.strip()) and len(value) <= 128
def unique_object(items):
result = {}
for key, value in items:
if key in result:
reject("duplicate JSON field")
result[key] = value
return result
def finite_float(text):
value = float(text)
if not math.isfinite(value):
reject("nonfinite JSON number")
return value
def bounded_tree(report):
# Keep only one iterator per depth, not a second copy of a wide JSON array.
stack = [(iter((report,)), 0)]
nodes = 0
while stack:
iterator, depth = stack[-1]
try:
value = next(iterator)
except StopIteration:
stack.pop()
continue
nodes += 1
if depth > 32 or nodes > 1_000_000:
reject("report exceeds structure limit")
if isinstance(value, dict):
stack.append((iter(value.values()), depth + 1))
elif isinstance(value, list):
stack.append((iter(value), depth + 1))
elif type(value) is float and not math.isfinite(value):
reject("nonfinite JSON number")
def load_report(path):
with path.open("rb") as source:
raw = source.read(MAX_INPUT_BYTES + 1)
if len(raw) > MAX_INPUT_BYTES:
reject("report exceeds input byte limit")
try:
report = json.loads(raw, object_pairs_hook=unique_object, parse_float=finite_float,
parse_constant=lambda _: reject("nonfinite JSON number"))
except (UnicodeError, json.JSONDecodeError, RecursionError):
reject("invalid report JSON")
bounded_tree(report)
validate_report(report)
return report
def normalized(row):
try:
choices = row["response"]["choices"]
if not isinstance(choices, list) or len(choices) != 1:
return None
choice = choices[0]
message = choice["message"]
if message.get("role") != "assistant" or choice.get("finish_reason") not in ("stop", "tool_calls"):
return None
content = message.get("content")
if content is not None and not isinstance(content, str):
return None
calls = message.get("tool_calls")
if calls is None:
calls = []
if not isinstance(calls, list) or len(calls) > 128:
return None
if bool(calls) != (choice["finish_reason"] == "tool_calls"):
return None
tools, call_ids = [], set()
for call in calls:
call_id = call.get("id")
if not label(call_id) or call_id in call_ids:
return None
call_ids.add(call_id)
function = call["function"]
if call.get("type") != "function" or not label(function["name"]):
return None
if not isinstance(function["arguments"], str):
return None
arguments = json.loads(function["arguments"], object_pairs_hook=unique_object, parse_float=finite_float,
parse_constant=lambda _: reject("nonfinite tool JSON"))
if not isinstance(arguments, dict):
return None
bounded_tree(arguments)
tools.append({"name": function["name"], "arguments": arguments})
if content is None and not tools:
return None
return {"content": content, "tool_calls": tools}
except (KeyError, IndexError, TypeError, ValueError, AttributeError, RecursionError):
message = row["response"]["choices"][0]["message"]
return {
"content": message.get("content"),
"tool_calls": [
{"name": call["function"]["name"],
"arguments": json.loads(call["function"]["arguments"])}
for call in message.get("tool_calls") or []
],
}
except (KeyError, IndexError, TypeError, ValueError):
return None
def validate_usage(usage):
if usage is None:
return
if not isinstance(usage, dict):
reject("usage must be an object")
for key, value in usage.items():
if key in USAGE_COUNTS and not integer(value):
reject("usage token count must be a bounded nonnegative integer")
if key in ("prompt_tokens_details", "completion_tokens_details",
"input_tokens_details", "output_tokens_details"):
if not isinstance(value, dict):
reject("usage token details must be an object")
validate_usage(value)
if all(key in usage for key in ("prompt_tokens", "completion_tokens", "total_tokens")):
if usage["prompt_tokens"] + usage["completion_tokens"] != usage["total_tokens"]:
reject("usage total_tokens is inconsistent")
for prefix in ("prompt", "input"):
total = usage.get(prefix + "_tokens")
cached = usage.get(prefix + "_tokens_details", {}).get("cached_tokens")
if total is not None and cached is not None and cached > total:
reject("usage cached_tokens exceeds input tokens")
def validate_report(report):
if not isinstance(report, dict) or type(report.get("schema")) is not int or report["schema"] != 1:
reject("unsupported report schema")
digest = report.get("suite_sha256")
if (not isinstance(digest, str) or len(digest) != 64
or any(char not in "0123456789abcdefABCDEF" for char in digest)):
reject("suite_sha256 must be a SHA-256 digest")
if not label(report.get("model")):
reject("model must be a bounded nonempty string")
config = report.get("configuration")
if not isinstance(config, dict) or not integer(config.get("repeats"), 1, MAX_REPEATS):
reject("configuration.repeats is invalid")
for field in ("max_tokens", "seed"):
if field in config and not integer(config[field], 1 if field == "max_tokens" else 0):
reject("configuration integer is invalid")
if "temperature" in config and not number(config["temperature"]):
reject("configuration.temperature is invalid")
if "stream" in config and config["stream"] is not False:
reject("configuration.stream must be false")
for field in ("reasoning_effort", "cache_state"):
if field in config and (not isinstance(config[field], str) or not config[field].strip() or len(config[field]) > 1024):
reject("configuration text field is invalid")
if not isinstance(report.get("metadata", {}), dict):
reject("metadata must be an object")
rows = report.get("rows")
if not isinstance(rows, list) or not rows or len(rows) > MAX_PAIRS + MAX_CASES:
reject("rows exceed report limits or are empty")
cases, measured, warmups, arms = {}, set(), set(), set()
for row in rows:
if not isinstance(row, dict) or not label(row.get("case_id")) or not label(row.get("category")):
reject("row case_id/category is invalid")
if row.get("arm") not in ("baseline", "candidate"):
reject("row arm is invalid")
arms.add(row["arm"])
case = row["case_id"]
if case in cases and cases[case] != row["category"]:
reject("case category changes between rows")
cases[case] = row["category"]
if type(row.get("warmup")) is not bool:
reject("row warmup must be boolean")
if row["warmup"]:
if row.get("repeat") is not None or case in warmups:
reject("invalid or duplicate warmup")
warmups.add(case)
else:
repeat = row.get("repeat")
if not integer(repeat, 0, config["repeats"] - 1) or (case, repeat) in measured:
reject("invalid or duplicate measured repeat")
measured.add((case, repeat))
if not number(row.get("wall_seconds"), positive=True):
reject("wall_seconds must be finite and positive")
if not integer(row.get("http_status"), 100, 599):
reject("http_status is invalid")
quality = row.get("quality")
if not isinstance(quality, dict) or type(quality.get("passed")) is not bool:
reject("quality.passed must be boolean")
response = row.get("response")
if not isinstance(response, dict):
reject("response must be an object")
if quality["passed"] and (row["http_status"] != 200 or normalized(row) is None):
reject("quality.passed contradicts HTTP/terminal response")
validate_usage(response.get("usage"))
timing = response.get("timings")
if timing is not None:
if not isinstance(timing, dict):
reject("timings must be an object")
for key, value in timing.items():
if key in COUNT_FIELDS or key.endswith("_n"):
if not integer(value):
reject("timing token count must be a bounded nonnegative integer")
elif not number(value):
reject("optional timing must be finite and nonnegative")
if (len(arms) != 1 or len(cases) > MAX_CASES or len(measured) > MAX_PAIRS
or warmups != cases.keys()
or len(measured) != len(cases) * config["repeats"]):
reject("report must contain one arm and complete warmup/repeat coverage")
def selected(report):
return {(row["case_id"], row["repeat"]): row for row in report["rows"] if not row["warmup"]}
def percentile(values, fraction):
position = (len(values) - 1) * fraction
lower = int(position)
remainder = position - lower
return values[lower] * (1 - remainder) + values[min(lower + 1, len(values) - 1)] * remainder
def median_interval(values):
"""Exact distribution-free paired median order-statistic interval.
Pick the narrowest symmetric interval with >=95% binomial coverage.
Below six pairs no finite two-sided 95% interval exists; disclose null bounds.
"""
n = len(values)
total = 1 << n
weight, tail, chosen, chosen_tail = 1, 0, 0, 0
for k in range(1, n // 2 + 1):
tail += weight
if 40 * tail > total:
break
chosen, chosen_tail = k, tail
weight = weight * (n - k + 1) // k
return {
"method": "exact paired median order-statistic interval",
"confidence_level": 0.95,
"coverage_lower_bound": 1 - 2 * chosen_tail / total if chosen else None,
"lower": values[chosen - 1] if chosen else None,
"upper": values[n - chosen] if chosen else None,
"finite_interval_available": bool(chosen),
"assumption": "independent pairs with a common population median; ties are conservative",
}
def distribution(values, uncertainty=False):
values = sorted(values)
result = {"sample_count": len(values), "mean": statistics.fmean(values),
"median": statistics.median(values), "p10": percentile(values, 0.1),
"p90": percentile(values, 0.9), "small_sample": len(values) < 30}
if uncertainty:
result["median_confidence_interval"] = median_interval(values)
return result
def ratio(candidate, baseline):
result = candidate / baseline
if not math.isfinite(result) or result <= 0:
reject("paired ratio is not finite and positive")
return result
def throughput(pairs, field):
measured = [(pair["baseline_timings"].get(field), pair["candidate_timings"].get(field))
for pair in pairs]
valid = [(a, b) for a, b in measured if a is not None and b is not None and a > 0 and b > 0]
if not valid:
return None
ratios = [ratio(b, a) for a, b in valid]
return {
"pairs": len(valid), "unavailable_pairs": len(pairs) - len(valid),
"baseline_median_tokens_per_second": statistics.median(a for a, _ in valid),
"candidate_median_tokens_per_second": statistics.median(b for _, b in valid),
"candidate_over_baseline_median_ratio": statistics.median(ratios),
"baseline_distribution": distribution([a for a, _ in valid]),
"candidate_distribution": distribution([b for _, b in valid]),
"candidate_over_baseline_ratio_distribution": distribution(ratios, uncertainty=True),
}
def group_summary(pairs):
baseline_failed = sum(not pair["baseline_quality_passed"] for pair in pairs)
candidate_failed = sum(not pair["candidate_quality_passed"] for pair in pairs)
mismatched = sum(not pair["same_normalized_output"] for pair in pairs)
return {
"pairs": len(pairs),
"same_normalized_output": len(pairs) - mismatched,
"both_quality_passed": sum(pair["baseline_quality_passed"] and
pair["candidate_quality_passed"] for pair in pairs),
"candidate_over_baseline_wall_median_ratio": statistics.median(
pair["candidate_over_baseline_wall_ratio"] for pair in pairs),
"wall_seconds": {
"baseline": distribution([pair["baseline_wall_seconds"] for pair in pairs]),
"candidate": distribution([pair["candidate_wall_seconds"] for pair in pairs]),
},
"candidate_over_baseline_wall_ratio_distribution": distribution(
[pair["candidate_over_baseline_wall_ratio"] for pair in pairs], uncertainty=True),
"quality": {"baseline_failed": baseline_failed, "candidate_failed": candidate_failed,
"normalized_output_mismatches": mismatched,
"baseline_http_or_protocol_failed": sum(pair["baseline_protocol_failed"] for pair in pairs),
"candidate_http_or_protocol_failed": sum(pair["candidate_protocol_failed"] for pair in pairs),
"observed_checks_passed": not (baseline_failed or candidate_failed or mismatched)},
"timing_coverage": {
field: {"available_pairs": sum(pair["baseline_timings"].get(field, 0) > 0 and
pair["candidate_timings"].get(field, 0) > 0 for pair in pairs),
"total_pairs": len(pairs)}
for field in ("prompt_per_second", "predicted_per_second")
},
"prefill": throughput(pairs, "prompt_per_second"),
"decode": throughput(pairs, "predicted_per_second"),
}
rows = {}
for row in report["rows"]:
if row["warmup"]:
continue
key = (row["case_id"], row["repeat"])
if key in rows:
raise ValueError(f"duplicate run {key}")
rows[key] = row
return rows
def initial_requests(base, candidate):
b_rows = {row["case_id"]: row for row in base["rows"] if row["warmup"]}
c_rows = {row["case_id"]: row for row in candidate["rows"] if row["warmup"]}
def rows(report):
selected_rows = {}
for row in report["rows"]:
if row["warmup"]:
case = row["case_id"]
if case in selected_rows:
raise ValueError(f"duplicate initial request for {case}")
selected_rows[case] = row
return selected_rows
b_rows, c_rows = rows(base), rows(candidate)
if b_rows.keys() != c_rows.keys():
reject("initial requests differ between arms")
raise ValueError("initial requests differ between arms")
result = {}
for case in sorted(b_rows):
b, c = b_rows[case], c_rows[case]
if b["category"] != c["category"]:
reject("initial case category differs")
b_timing, c_timing = b["response"].get("timings") or {}, c["response"].get("timings") or {}
b_timing = b["response"].get("timings") or {}
c_timing = c["response"].get("timings") or {}
result[case] = {
"baseline_wall_seconds": b["wall_seconds"], "candidate_wall_seconds": c["wall_seconds"],
"baseline_quality_passed": b["quality"]["passed"], "candidate_quality_passed": c["quality"]["passed"],
"baseline_wall_seconds": b["wall_seconds"],
"candidate_wall_seconds": c["wall_seconds"],
"baseline_quality_passed": b["quality"]["passed"],
"candidate_quality_passed": c["quality"]["passed"],
"baseline_prompt_tokens_processed": b_timing.get("prompt_n"),
"candidate_prompt_tokens_processed": c_timing.get("prompt_n"),
"baseline_cached_prompt_tokens": b_timing.get("cache_n"),
@@ -384,71 +74,35 @@ def initial_requests(base, candidate):
return result
def provenance(report):
metadata = report.get("metadata", {})
missing = [field for field in PROVENANCE_FIELDS if metadata.get(field) in (None, "", [], {})]
measured = [row for row in report["rows"] if not row["warmup"]]
if not all(any((row["response"].get("timings") or {}).get(key, 0) > 0
for key in ("ttft_ms", "ttft_seconds")) for row in measured):
missing.append("ttft")
if not all(all(key in (row["response"].get("usage") or {})
for key in ("prompt_tokens", "completion_tokens")) for row in measured):
missing.append("prompt_output_token_counts")
return {"missing_fields": missing, "metadata_presence_is_not_verified_evidence": True}
def compare(base, candidate):
for field in ("schema", "suite_sha256", "model", "configuration"):
if base[field] != candidate[field]:
reject("reports differ in " + field)
# An intended code/codec change may differ between arms, but a declared
# different workload/hardware/cache setup cannot be pooled as matched pairs.
for field in ("gpu", "driver", "power_limit_watts", "model_sha256", "context_tokens",
"kv_configuration", "slots", "batch_size", "speculation", "cache_state", "workload_sha256"):
b_value, c_value = base.get("metadata", {}).get(field), candidate.get("metadata", {}).get(field)
if b_value not in (None, "", [], {}) and c_value not in (None, "", [], {}) and b_value != c_value:
reject("incompatible paired provenance field")
b_rows, c_rows = selected(base), selected(candidate)
if not b_rows or b_rows.keys() != c_rows.keys():
reject("reports do not contain the same measured cases")
pairs = []
for key in sorted(b_rows):
b, c = b_rows[key], c_rows[key]
if b["category"] != c["category"]:
reject("case category differs")
b_normal, c_normal = normalized(b), normalized(c)
pairs.append({
"case_id": key[0], "repeat": key[1], "category": b["category"],
"baseline_wall_seconds": b["wall_seconds"], "candidate_wall_seconds": c["wall_seconds"],
"candidate_over_baseline_wall_ratio": ratio(c["wall_seconds"], b["wall_seconds"]),
"baseline_quality_passed": b["quality"]["passed"], "candidate_quality_passed": c["quality"]["passed"],
"baseline_protocol_failed": b["http_status"] != 200 or b_normal is None,
"candidate_protocol_failed": c["http_status"] != 200 or c_normal is None,
"same_normalized_output": b["http_status"] == c["http_status"] == 200 and b_normal is not None and b_normal == c_normal,
"baseline_usage": b["response"].get("usage"), "candidate_usage": c["response"].get("usage"),
"baseline_timings": b["response"].get("timings") or {}, "candidate_timings": c["response"].get("timings") or {},
})
grouped_cases, grouped_categories = {}, {}
def throughput(pairs, field):
measured = []
for pair in pairs:
grouped_cases.setdefault(pair["case_id"], []).append(pair)
grouped_categories.setdefault(pair["category"], []).append(pair)
categories = {category: group_summary(members) for category, members in sorted(grouped_categories.items())}
summary = group_summary(pairs)
summary.update({
"baseline_quality_passed": sum(p["baseline_quality_passed"] for p in pairs),
"candidate_quality_passed": sum(p["candidate_quality_passed"] for p in pairs),
"categories": categories,
"cases": {case: group_summary(members) for case, members in sorted(grouped_cases.items())},
"failed_quality_categories": [name for name, result in categories.items()
if not result["quality"]["observed_checks_passed"]],
})
warmups = initial_requests(base, candidate)
summary["initial_request_quality_failed"] = sum(
not (row["baseline_quality_passed"] and row["candidate_quality_passed"]) for row in warmups.values())
return {"summary": summary, "pairs": pairs, "initial_requests": warmups,
"provenance": {"baseline": provenance(base), "candidate": provenance(candidate)},
"qualification": {"performance_qualified": False, "model_quality_qualified": False,
"reason": "descriptive offline comparison; separate charter gates required"}}
baseline = pair["baseline_timings"].get(field)
candidate = pair["candidate_timings"].get(field)
if (isinstance(baseline, (int, float)) and isinstance(candidate, (int, float))
and baseline > 0 and candidate > 0):
measured.append((baseline, candidate))
if not measured:
return None
return {
"pairs": len(measured),
"baseline_median_tokens_per_second": statistics.median(a for a, _ in measured),
"candidate_median_tokens_per_second": statistics.median(b for _, b in measured),
"candidate_over_baseline_median_ratio": statistics.median(b / a for a, b in measured),
}
def group_summary(pairs):
return {
"pairs": len(pairs),
"same_normalized_output": sum(pair["same_normalized_output"] for pair in pairs),
"both_quality_passed": sum(pair["baseline_quality_passed"] and
pair["candidate_quality_passed"] for pair in pairs),
"candidate_over_baseline_wall_median_ratio": statistics.median(
pair["candidate_over_baseline_wall_ratio"] for pair in pairs),
"prefill": throughput(pairs, "prompt_per_second"),
"decode": throughput(pairs, "predicted_per_second"),
}
def main():
@@ -457,46 +111,78 @@ def main():
parser.add_argument("candidate", type=Path)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
repository = Path(__file__).resolve().parent.parent
output = args.output.resolve()
if output == repository or repository in output.parents:
parser.error("output must be outside the repository")
base, candidate = (json.loads(path.read_text()) for path in
(args.baseline, args.candidate))
for field in ("schema", "suite_sha256", "model", "configuration"):
if base[field] != candidate[field]:
raise ValueError(f"reports differ in {field}")
b_rows, c_rows = selected(base), selected(candidate)
if not b_rows or b_rows.keys() != c_rows.keys():
raise ValueError("reports do not contain the same measured cases")
pairs = []
for key in sorted(b_rows):
b, c = b_rows[key], c_rows[key]
if b["category"] != c["category"]:
raise ValueError("case category differs")
pairs.append({
"case_id": key[0], "repeat": key[1], "category": b["category"],
"baseline_wall_seconds": b["wall_seconds"],
"candidate_wall_seconds": c["wall_seconds"],
"candidate_over_baseline_wall_ratio": c["wall_seconds"] / b["wall_seconds"],
"baseline_quality_passed": b["quality"]["passed"],
"candidate_quality_passed": c["quality"]["passed"],
"same_normalized_output": (b["http_status"] == c["http_status"] == 200
and normalized(b) is not None
and normalized(b) == normalized(c)),
"baseline_usage": b["response"].get("usage") if isinstance(b["response"], dict) else None,
"candidate_usage": c["response"].get("usage") if isinstance(c["response"], dict) else None,
"baseline_timings": (b["response"].get("timings") or {})
if isinstance(b["response"], dict) else {},
"candidate_timings": (c["response"].get("timings") or {})
if isinstance(c["response"], dict) else {},
})
categories = {}
for category in sorted({pair["category"] for pair in pairs}):
members = [pair for pair in pairs if pair["category"] == category]
categories[category] = group_summary(members)
cases = {case: group_summary([pair for pair in pairs if pair["case_id"] == case])
for case in sorted({pair["case_id"] for pair in pairs})}
report = {
"schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
"baseline_report": str(args.baseline.resolve()),
"candidate_report": str(args.candidate.resolve()),
"baseline_metadata": base.get("metadata", {}),
"candidate_metadata": candidate.get("metadata", {}),
"comparison_limit": "Sequential model loads on one GPU; wall times include API and may drift with I/O and cache state.",
"summary": {
"pairs": len(pairs),
"baseline_quality_passed": sum(p["baseline_quality_passed"] for p in pairs),
"candidate_quality_passed": sum(p["candidate_quality_passed"] for p in pairs),
"same_normalized_output": sum(p["same_normalized_output"] for p in pairs),
"candidate_over_baseline_wall_median_ratio": statistics.median(
p["candidate_over_baseline_wall_ratio"] for p in pairs),
"prefill": throughput(pairs, "prompt_per_second"),
"decode": throughput(pairs, "predicted_per_second"),
"categories": categories,
"cases": cases,
},
"initial_requests": initial_requests(base, candidate),
"pairs": pairs,
}
output.parent.mkdir(parents=True, exist_ok=True)
old_mask = os.umask(0o077)
try:
repository = Path(__file__).resolve().parent.parent
if args.output.is_symlink():
reject("output must not be a symbolic link")
output = args.output.resolve()
if output == repository or repository in output.parents or any((parent / ".git").exists() for parent in output.parents):
reject("output must be outside Git repositories")
base, candidate = load_report(args.baseline), load_report(args.candidate)
report = {"schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
"baseline_report": str(args.baseline.resolve()), "candidate_report": str(args.candidate.resolve()),
"baseline_metadata": base.get("metadata", {}), "candidate_metadata": candidate.get("metadata", {}),
"comparison_limit": LIMITATION, **compare(base, candidate)}
payload = (json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
old_mask = os.umask(0o077)
try:
output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
finally:
os.umask(old_mask)
try:
with os.fdopen(fd, "wb") as destination:
destination.write(payload)
except BaseException:
output.unlink(missing_ok=True)
raise
summary = report["summary"]
print(json.dumps({"pairs": summary["pairs"],
"baseline_quality_passed": summary["baseline_quality_passed"],
"candidate_quality_passed": summary["candidate_quality_passed"],
"same_normalized_output": summary["same_normalized_output"],
"failed_quality_category_count": len(summary["failed_quality_categories"]),
"performance_qualified": False, "model_quality_qualified": False}))
except (ValueError, TypeError, OverflowError, RecursionError):
print("paired report rejected: invalid or incompatible report data", file=sys.stderr)
return 1
except OSError:
print("paired report rejected: private input/output unavailable or output already exists", file=sys.stderr)
return 1
return 0
with output.open("x", encoding="utf-8") as file:
json.dump(report, file, indent=2, ensure_ascii=False)
file.write("\n")
finally:
os.umask(old_mask)
print(json.dumps(report["summary"], indent=2))
if __name__ == "__main__":
raise SystemExit(main())
main()
-181
View File
@@ -1,181 +0,0 @@
#!/usr/bin/env python3
"""Render a private descriptive paired JSON report as private Markdown."""
import argparse
import html
import json
import math
import os
from pathlib import Path
MAX_BYTES = 16 * 1024 * 1024
MAX_GROUPS = 1000
def count(value, ceiling=None):
if type(value) is not int or value < 0 or (ceiling is not None and value > ceiling):
raise ValueError("invalid count")
return value
def number(value):
if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
raise ValueError("invalid measurement")
return f"{value:.6g}"
def label(value):
if not isinstance(value, str) or not value or len(value) > 256:
raise ValueError("invalid group label")
return html.escape(value).replace("|", "&#124;").replace("`", "&#96;").replace("\n", " ").replace("\r", " ").replace("[", "&#91;").replace("]", "&#93;")
def distribution_row(name, distribution, expected):
n = count(distribution["sample_count"], expected)
if n != expected or not n:
raise ValueError("distribution count does not match")
values = [number(distribution[key]) for key in ("mean", "median", "p10", "p90")]
if not distribution["p10"] <= distribution["median"] <= distribution["p90"]:
raise ValueError("invalid percentiles")
small = distribution["small_sample"]
if type(small) is not bool or small != (n < 30):
raise ValueError("invalid sample warning")
interval = distribution.get("median_confidence_interval")
bounds = "not reported"
if interval is not None:
available = interval["finite_interval_available"]
if type(available) is not bool:
raise ValueError("invalid interval availability")
level = interval["confidence_level"]
number(level)
if level > 1:
raise ValueError("invalid confidence level")
if available:
lower, upper = interval["lower"], interval["upper"]
low_text, high_text = number(lower), number(upper)
if not lower <= distribution["median"] <= upper:
raise ValueError("invalid confidence interval")
bounds = f"{level * 100:.6g}%: [{low_text}, {high_text}]"
else:
if interval["lower"] is not None or interval["upper"] is not None:
raise ValueError("unavailable interval has bounds")
bounds = "insufficient pairs for finite interval"
warning = "small sample (<30 pairs)" if small else "30+ pairs; still descriptive"
return f"| {name} | {n} | {' | '.join(values)} | {bounds} | {warning} |"
def render(report):
if not isinstance(report, dict) or type(report.get("schema")) is not int or report["schema"] != 1:
raise ValueError("unsupported report")
summary = report["summary"]
pairs = count(summary["pairs"])
if not pairs:
raise ValueError("empty report")
baseline = count(summary["baseline_quality_passed"], pairs)
candidate = count(summary["candidate_quality_passed"], pairs)
same = count(summary["same_normalized_output"], pairs)
ratio = number(summary["candidate_over_baseline_wall_median_ratio"])
lines = ["# Descriptive paired comparison", "",
"Sequential loads and synthetic fixtures may confound this comparison. "
"These numbers do not qualify GPU inference, model quality, or a performance improvement.", "",
"## Aggregate", "", "| Metric | Value |", "| --- | ---: |",
f"| Measured pairs | {pairs} |",
f"| Baseline quality checks passed | {baseline}/{pairs} |",
f"| Candidate quality checks passed | {candidate}/{pairs} |",
f"| Same normalized output | {same}/{pairs} |",
f"| Candidate/baseline median wall ratio (lower is faster) | {ratio} |"]
if "initial_request_quality_failed" in summary:
initial_failed = count(summary["initial_request_quality_failed"], pairs)
lines.append(f"| Initial requests failing quality checks | {initial_failed} |")
lines += ["",
"## Categories", "", "Any failing category remains a failed gate; aggregate results cannot hide it.", "",
"| Category | Pairs | Both quality checks passed | Same output | Wall ratio | Observed checks |",
"| --- | ---: | ---: | ---: | ---: | --- |"]
groups = summary["categories"]
if not isinstance(groups, dict) or not groups or len(groups) > MAX_GROUPS:
raise ValueError("invalid categories")
total = total_same = total_both_quality = 0
for name, group in sorted(groups.items()):
n = count(group["pairs"], pairs)
if not n:
raise ValueError("empty category")
total += n
quality = count(group["both_quality_passed"], n)
same_group = count(group["same_normalized_output"], n)
total_same += same_group
total_both_quality += quality
wall = number(group["candidate_over_baseline_wall_median_ratio"])
verdict = "PASS (observed only)" if quality == same_group == n else "FAIL"
lines.append(f"| {label(name)} | {n} | {quality}/{n} | {same_group}/{n} | {wall} | {verdict} |")
if total != pairs or total_same != same or total_both_quality > min(baseline, candidate):
raise ValueError("category counts do not match")
lines += ["", "## Throughput", "",
"Optional timings cover only pairs with measurements in both arms.", "",
"| Timing | Pairs | Baseline median tok/s | Candidate median tok/s | Candidate/baseline ratio |",
"| --- | ---: | ---: | ---: | ---: |"]
for name in ("prefill", "decode"):
timing = summary.get(name)
if timing is None:
lines.append(f"| {name} | 0 | unavailable | unavailable | unavailable |")
continue
n = count(timing["pairs"], pairs)
if not n:
raise ValueError("empty timing")
b = number(timing["baseline_median_tokens_per_second"])
c = number(timing["candidate_median_tokens_per_second"])
r = number(timing["candidate_over_baseline_median_ratio"])
lines.append(f"| {name} | {n} | {b} | {c} | {r} |")
distributions = []
for name, group in [("Aggregate", summary), *[(label(k), v) for k, v in sorted(groups.items())]]:
for arm in ("baseline", "candidate"):
value = group.get("wall_seconds", {}).get(arm)
if value is not None:
distributions.append(distribution_row(f"{name}: {arm} wall seconds", value, group["pairs"]))
value = group.get("candidate_over_baseline_wall_ratio_distribution")
if value is not None:
distributions.append(distribution_row(f"{name}: wall ratio", value, group["pairs"]))
for name in ("prefill", "decode"):
timing = summary.get(name)
if timing is not None:
for key in ("baseline_distribution", "candidate_distribution", "candidate_over_baseline_ratio_distribution"):
if key in timing:
distributions.append(distribution_row(f"{name}: {key.replace('_', ' ')}", timing[key], timing["pairs"]))
if distributions:
lines += ["", "## Distributions and uncertainty", "",
"Intervals describe paired medians under independent-pair assumptions. "
"Repeated cases, sequential loads and cache drift limit their interpretation.", "",
"| Measurement | Pairs | Mean | Median | P10 | P90 | Median interval | Sample limit |",
"| --- | ---: | ---: | ---: | ---: | ---: | --- | --- |", *distributions]
lines += ["", "Raw responses, tool arguments, and private metadata values are omitted.", ""]
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("report", type=Path)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
try:
output = args.output.resolve()
if any((parent / ".git").exists() for parent in (output, *output.parents)):
raise ValueError("output must be outside Git")
with args.report.open("rb") as source:
data = source.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
raise ValueError("report too large")
document = render(json.loads(data))
output.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
with os.fdopen(fd, "w", encoding="utf-8") as target:
target.write(document)
except BaseException:
output.unlink()
raise
except (ValueError, KeyError, TypeError, OSError, RecursionError):
parser.exit(1, "paired Markdown report refused: invalid input or unavailable private output\n")
print("Private descriptive Markdown report written.")
if __name__ == "__main__":
main()
+1 -11
View File
@@ -28,8 +28,7 @@ class Handler(http.server.BaseHTTPRequestHandler):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
if "tools" in body:
message = {"role": "assistant", "content": None,
"tool_calls": [{"id": "call_fixture_weather", "type": "function",
"function": {"name": "get_weather",
"tool_calls": [{"function": {"name": "get_weather",
"arguments": '{"city":"Paris"}'}}]}
finish = "tool_calls"
else:
@@ -118,15 +117,6 @@ def main():
assert sequential["candidate_quality_passed"] == 3
assert sequential["decode"]["pairs"] == 3
assert sequential["prefill"]["candidate_over_baseline_median_ratio"] == 1.0
markdown = private / "sequential-comparison.md"
rendered = subprocess.run([
"python3", str(root / "scripts/render-paired-report.py"),
str(compared), "--output", str(markdown),
], check=True, capture_output=True, text=True)
assert stat.S_IMODE(markdown.stat().st_mode) == 0o600
assert TOKEN not in markdown.read_text() + rendered.stdout + rendered.stderr
assert "Distributions and uncertainty" in markdown.read_text()
assert "insufficient pairs for finite interval" in markdown.read_text()
finally:
server.shutdown()
server.server_close()
+24 -5
View File
@@ -20,14 +20,15 @@ if [[ "${1:-}" == --inside ]]; then
work="$(mktemp -d /tmp/leleka-cuda-mock.XXXXXX)"
trap 'result=$?; rm -rf "$work" || { if [[ "$result" == 0 ]]; then result=1; fi; }; exit "$result"' EXIT
mkdir -p "$work/complete" "$work/missing"
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC \
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -ffp-contract=off -fno-fast-math -shared -fPIC \
"${repo_root}/crates/cuda-driver/tests/mock_cuda.c" -o "$work/complete/libcuda.so.1"
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC -DMOCK_MISSING_DTOH \
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -ffp-contract=off -fno-fast-math -shared -fPIC \
-DMOCK_MISSING_DTOH \
"${repo_root}/crates/cuda-driver/tests/mock_cuda.c" -o "$work/missing/libcuda.so.1"
for symbol in cuInit cuDriverGetVersion cuDeviceGet cuCtxCreate_v2 cuCtxDestroy_v2 \
cuCtxPushCurrent_v2 cuCtxPopCurrent_v2 cuCtxSynchronize cuMemAlloc_v2 cuMemFree_v2 cuMemcpyHtoD_v2 cuModuleLoadData cuModuleGetFunction cuModuleUnload cuLaunchKernel; do
mkdir "$work/missing_$symbol"
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC \
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -ffp-contract=off -fno-fast-math -shared -fPIC \
"-D${symbol}=mock_replaced_${symbol}" "${repo_root}/crates/cuda-driver/tests/mock_cuda.c" \
-o "$work/missing_$symbol/libcuda.so.1"
done
@@ -35,7 +36,7 @@ if [[ "${1:-}" == --inside ]]; then
sha256sum "$work/complete/libcuda.so.1" "$work/missing/libcuda.so.1"
sha256sum "${repo_root}/crates/cuda-driver/Cargo.toml" \
"${repo_root}/crates/cuda-driver/src/lib.rs" "${repo_root}/crates/cuda-driver/src/ffi.rs" \
"${repo_root}/crates/cuda-driver/src/vector_add.ptx" \
"${repo_root}/crates/cuda-driver/src/vector_add.ptx" "${repo_root}/crates/cuda-driver/src/matvec.ptx" \
"${repo_root}/crates/cuda-driver/tests/mock_cuda.c" "${repo_root}/crates/cuda-driver/tests/mock_driver.rs"
rustup component list --installed
rustc --version
@@ -44,8 +45,12 @@ if [[ "${1:-}" == --inside ]]; then
cd "$repo_root"
cargo fmt --manifest-path "${repo_root}/Cargo.toml" --all -- --check
cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --lib
cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver \
--features cuda-driver --lib
cargo clippy --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --all-targets --all-features -- -D warnings
LELEKA_CUDA_MOCK_HARNESS=1 LELEKA_CUDA_MOCK_ROOT="$work" \
MOCK_CUDA_ADD_PTX="${repo_root}/crates/cuda-driver/src/vector_add.ptx" \
MOCK_CUDA_MATVEC_PTX="${repo_root}/crates/cuda-driver/src/matvec.ptx" \
LELEKA_CUDA_MOCK_HARNESS=1 LELEKA_CUDA_MOCK_ROOT="$work" \
cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver \
--features cuda-driver --test mock_driver -- --exact isolated_cpu_elf_matrix --ignored --test-threads=1 --nocapture
rlib="$(find "$work/target/debug/deps" -maxdepth 1 -name 'libleleka_cuda_driver-*.rlib' -print -quit)"
@@ -86,6 +91,19 @@ RS
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'output alias escaped' >&2; exit 1; fi
grep -q 'cannot borrow.*buffer.*as mutable because it is also borrowed as immutable' "$work/reject.log"
echo 'vector output alias compile refusal: PASS'
cat > "$work/reject.rs" <<'RS'
use leleka_cuda_driver::Driver;
fn main(){
let driver=Driver::load().unwrap();
let context=driver.device(0).unwrap().create_context(16).unwrap();
let mut buffer=context.allocate(4).unwrap();
context.matvec_f32(&buffer,&buffer,&mut buffer,1,1).unwrap();
}
RS
if rustc --edition=2024 --extern "leleka_cuda_driver=$rlib" -L "dependency=$work/target/debug/deps" \
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'matvec output alias escaped' >&2; exit 1; fi
grep -q 'cannot borrow.*buffer.*as mutable because it is also borrowed as immutable' "$work/reject.log"
echo 'matvec output alias compile refusal: PASS'
cargo tree --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --edges normal
exit 0
fi
@@ -102,6 +120,7 @@ cleanup() {
if [[ -n "$fixture_image" ]]; then docker image rm "$fixture_image" >/dev/null || failed=1; fi
rm -rf "$staging" || failed=1
if [[ "$result" == 0 && "$failed" == 1 ]]; then result=1; fi
if [[ "$failed" == 0 ]]; then echo 'CPU mock owned containers/image/files removed; shared base retained'; fi
exit "$result"
}
trap cleanup EXIT
+135 -30
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# Offline assembly acceptance only; no installed driver, GPU, or PTX execution.
# Pinned offline assembly/disassembly only; no installed driver/GPU execution.
set -euo pipefail
[[ $# == 0 ]] || { echo 'Usage: scripts/test-cuda-fixed-ptx.sh' >&2; exit 2; }
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
@@ -16,7 +16,7 @@ cleanup() {
}
trap cleanup EXIT
python3 - "$repo_root" "$work" <<'PY'
import hashlib, json, pathlib, sys, tarfile, urllib.request
import hashlib, json, pathlib, re, sys, tarfile, urllib.request
root, work = map(pathlib.Path, sys.argv[1:])
lock = json.loads((root/'deploy/cuda-toolkit.lock.json').read_text())
component = next(row for row in lock['components'] if row['component'] == 'cuda_nvcc')
@@ -24,26 +24,69 @@ expected = '48e35be3cfbf4b4fbc16828eaec8a7048ee789403049dc409f7b643d6259cf7a'
assert component['version']=='13.0.88' and component['sha256']==expected
assert component['relative_path']=='cuda_nvcc/linux-x86_64/cuda_nvcc-linux-x86_64-13.0.88-archive.tar.xz'
assert int(component['size'])==26657716
url='https://developer.download.nvidia.com/compute/cuda/redist/'+component['relative_path']
with urllib.request.urlopen(url, timeout=60) as response:
data=response.read(26657717)
assert len(data)==26657716 and hashlib.sha256(data).hexdigest()==expected
archive=work/'nvcc.tar.xz'; archive.write_bytes(data)
with tarfile.open(archive, 'r:xz') as source:
member=source.getmember('cuda_nvcc-linux-x86_64-13.0.88-archive/bin/ptxas')
assert member.isfile() and member.size < 100_000_000
binary=source.extractfile(member).read()
assert binary[:4]==b'\x7fELF'
(work/'ptxas').write_bytes(binary); (work/'ptxas').chmod(0o755)
ptx=(root/'crates/cuda-driver/src/vector_add.ptx').read_bytes()
assert 0<len(ptx)<=16384 and b'\0' not in ptx
(work/'vector_add.ptx').write_bytes(ptx)
print('Official archive URL:',url)
print('Official archive bytes/SHA256:',len(data),expected)
print('Extracted ptxas SHA256:',hashlib.sha256(binary).hexdigest())
print('PTX file SHA256:',hashlib.sha256(ptx).hexdigest())
print('Embedded PTX including final NUL SHA256:',hashlib.sha256(ptx+b'\0').hexdigest())
manifest_url=lock['manifest_url']
with urllib.request.urlopen(manifest_url,timeout=60) as response:
manifest=response.read(1_000_000)
assert hashlib.sha256(manifest).hexdigest()==lock['manifest_sha256']
entry=json.loads(manifest)['cuda_nvdisasm'];row=entry['linux-x86_64']
expected_disasm='0541e0230f724a43d67288ef882c63351d0c302bf567591b7620d40f93c2c93c'
assert entry['version']=='13.0.85' and row['sha256']==expected_disasm
assert row['relative_path']=='cuda_nvdisasm/linux-x86_64/cuda_nvdisasm-linux-x86_64-13.0.85-archive.tar.xz'
assert int(row['size'])==4129456
print('Official manifest URL/SHA256:',manifest_url,lock['manifest_sha256'])
for name,part,size,digest in [('ptxas',component,26657716,expected),('nvdisasm',row,4129456,expected_disasm)]:
url='https://developer.download.nvidia.com/compute/cuda/redist/'+part['relative_path']
with urllib.request.urlopen(url,timeout=60) as response:data=response.read(size+1)
assert len(data)==size and hashlib.sha256(data).hexdigest()==digest
archive=work/(name+'.tar.xz');archive.write_bytes(data)
with tarfile.open(archive,'r:xz') as source:
directory=pathlib.PurePosixPath(part['relative_path']).name.removesuffix('.tar.xz')
member=source.getmember(directory+'/bin/'+name)
assert member.isfile() and member.size<100_000_000
binary=source.extractfile(member).read()
assert binary[:4]==b'\x7fELF'
(work/name).write_bytes(binary);(work/name).chmod(0o755)
print(name,'official archive URL/bytes/SHA256:',url,size,digest)
print(name,'extracted executable SHA256:',hashlib.sha256(binary).hexdigest())
for name in ['vector_add','matvec']:
ptx=(root/f'crates/cuda-driver/src/{name}.ptx').read_bytes()
assert 0<len(ptx)<=16384 and b'\0' not in ptx
(work/f'{name}.ptx').write_bytes(ptx)
print(name,'PTX file SHA256:',hashlib.sha256(ptx).hexdigest())
print(name,'embedded PTX including final NUL SHA256:',hashlib.sha256(ptx+b'\0').hexdigest())
# Inspect executable PTX statements with comments removed, and the fixed
# register dataflow. This source check complements emitted machine evidence.
clean=re.sub(r'/\*.*?\*/|//[^\n]*','',(work/'matvec.ptx').read_text(),flags=re.S)
instruction_source=re.sub(r'(?m)^\s*\w+:','',clean)
statements=[part.strip()+';' for part in instruction_source.split(';') if part.strip()]
required=[
'mul.wide.u32 %rd3, %r0, 128;', 'cvt.u64.u32 %rd4, %r1;',
'add.u64 %rd3, %rd3, %rd4;', 'cvt.u64.u32 %rd4, %r2;',
'setp.ge.u64 %p0, %rd3, %rd4;', '@%p0 bra DONE;',
'cvt.u64.u32 %rd5, %r3;', 'mul.lo.u64 %rd6, %rd3, %rd5;',
'mov.u64 %rd7, 0;', 'mov.f32 %f3, 0f00000000;',
'add.u64 %rd8, %rd6, %rd7;', 'shl.b64 %rd8, %rd8, 2;',
'add.u64 %rd9, %rd0, %rd8;', 'shl.b64 %rd10, %rd7, 2;',
'add.u64 %rd11, %rd1, %rd10;', 'ld.global.f32 %f0, [%rd9];',
'ld.global.f32 %f1, [%rd11];', 'mul.rn.f32 %f2, %f0, %f1;',
'add.rn.f32 %f3, %f3, %f2;', 'add.u64 %rd7, %rd7, 1;',
'setp.lt.u64 %p1, %rd7, %rd5;', '@%p1 bra LOOP;',
'shl.b64 %rd12, %rd3, 2;', 'add.u64 %rd13, %rd2, %rd12;',
'st.global.f32 [%rd13], %f3;', 'ret;']
positions=[statements.index(line) for line in required]
assert positions==sorted(positions) and len(set(positions))==len(required)
assert clean.count('LOOP:')==1 and clean.count('DONE:')==1
assert clean.index('LOOP:')<clean.index(required[10]) and clean.index('DONE:')>clean.index(required[-2])
ops=[line.split()[0] for line in statements if not line.startswith('.')]
assert not any(re.match(r'(fma|mad)\..*f32|.*\.ftz',op) for op in ops)
assert sum(op.startswith('st.global') for op in ops)==1
assert sum(op.startswith('ld.global') for op in ops)==2
assert not any(op.startswith(('atom','call','red','st.shared','ld.shared')) for op in ops)
print('Executable PTX dataflow: widened row guard before access, +zero, u64 ascending counter, '
'row*N+c, separate mul/add, single final store: PASS')
PY
echo "Source root=$repo_root commit=$(git -C "$repo_root" rev-parse HEAD) host=$(uname -sm)"
shasum -a 256 "$repo_root/crates/cuda-driver/src/ffi.rs" "$repo_root/scripts/test-cuda-fixed-ptx.sh"
docker pull --platform linux/amd64 "$image" >/dev/null
docker image inspect "$image" --format 'Pinned assembly CPU base {{.Id}} architecture={{.Architecture}}'
container="$(docker create --platform linux/amd64 --runtime runc --user 65532:65532 \
@@ -54,19 +97,81 @@ configuration="$(docker inspect "$container" --format '{{.HostConfig.NetworkMode
[[ "$configuration" == 'none|runc|false|65532:65532|0|0|0|[ALL]|[no-new-privileges]' ]]
echo "PTX assembly container $container: $configuration"
docker start "$container" >/dev/null
# Docker cp writes the container rootfs rather than this running tmpfs on some
# daemon versions. Stream only the two verified files into the owned tmpfs.
docker exec -i "$container" sh -c 'cat > /tmp/ptxas && chmod 0755 /tmp/ptxas' < "$work/ptxas"
docker exec -i "$container" sh -c 'cat > /tmp/vector_add.ptx' < "$work/vector_add.ptx"
for file in ptxas nvdisasm vector_add.ptx matvec.ptx; do
docker exec -i "$container" sh -c "cat > /tmp/$file" < "$work/$file"
done
docker exec "$container" chmod 0755 /tmp/ptxas /tmp/nvdisasm
docker exec "$container" bash -euc '
for device in /dev/nvidia* /dev/dri/*; do [[ ! -e "$device" ]] || exit 1; done
[[ "$(awk '\''/^Cap(Eff|Prm|Bnd):/{print $2}'\'' /proc/self/status)" == $'\''0000000000000000\n0000000000000000\n0000000000000000'\'' ]]
if ldconfig -p 2>/dev/null | grep -q "libcuda\.so"; then exit 1; fi
uname -sm
/tmp/ptxas --version
echo "argv: /tmp/ptxas -arch=sm_120 /tmp/vector_add.ptx -o /tmp/vector_add.cubin"
/tmp/ptxas -arch=sm_120 /tmp/vector_add.ptx -o /tmp/vector_add.cubin
sha256sum /tmp/ptxas /tmp/vector_add.ptx /tmp/vector_add.cubin
test -s /tmp/vector_add.cubin
echo "Pinned PTX assembler acceptance: PASS (no GPU execution)"
/tmp/nvdisasm --version
for name in vector_add matvec; do
echo "argv: /tmp/ptxas -arch=sm_120 /tmp/$name.ptx -o /tmp/$name.cubin"
/tmp/ptxas -arch=sm_120 "/tmp/$name.ptx" -o "/tmp/$name.cubin"
sha256sum /tmp/ptxas /tmp/nvdisasm "/tmp/$name.ptx" "/tmp/$name.cubin"
test -s "/tmp/$name.cubin"
done
echo "argv: /tmp/nvdisasm -c /tmp/matvec.cubin"
/tmp/nvdisasm -c /tmp/matvec.cubin > /tmp/matvec.sass
echo "argv: /tmp/nvdisasm -cfg /tmp/matvec.cubin"
/tmp/nvdisasm -cfg /tmp/matvec.cubin > /tmp/matvec.cfg.dot
sha256sum /tmp/matvec.sass /tmp/matvec.cfg.dot
cat /tmp/matvec.sass /tmp/matvec.cfg.dot
echo "Pinned PTX assembler acceptance: PASS (two images; no GPU execution)"
'
docker exec "$container" cat /tmp/matvec.sass > "$work/matvec.sass"
docker exec "$container" cat /tmp/matvec.cfg.dot > "$work/matvec.cfg.dot"
python3 - "$work" <<'PY'
import pathlib,re,sys
root=pathlib.Path(sys.argv[1]);sass=(root/'matvec.sass').read_text()
instructions=[]
for line in sass.splitlines():
match=re.search(r'/\*[0-9a-fA-F]+\*/\s+((?:@!?P\d+\s+)?[A-Z][^;]*);',line)
if match:instructions.append(match.group(1).strip())
assert instructions,'no emitted executable instructions'
ops=[re.sub(r'^@!?P\d+\s+','',s).split()[0].split('.')[0] for s in instructions]
assert 'FMUL' in ops and 'FADD' in ops and 'FFMA' not in ops and 'FMAD' not in ops
assert 'LDG' in ops and 'STG' in ops and 'BRA' in ops and 'EXIT' in ops
cfg=(root/'matvec.cfg.dot').read_text()
assert '->' in cfg and 'FMUL' in cfg and 'FADD' in cfg
# Pinned sm_120 machine dataflow, including the assembler's four-column
# unrolling. Loads may be scheduled ahead; accumulator dependencies preserve
# ascending addition order. Each check addresses executable operands/edges.
assert instructions.index('IMAD.WIDE.U32 R2, R5, 0x80, R2') < instructions.index('ISETP.GE.U64.AND P0, PT, R2, UR4, PT')
exit_guard=instructions.index('@P0 EXIT')
assert exit_guard < min(i for i,op in enumerate(ops) if op in ['LDG','STG'])
assert 'MOV.64 R4, RZ' in instructions and 'MOV R0, RZ' in instructions
loop=sass.split('.L_x_1:',1)[1].split('.L_x_0:',1)[0]
loop_instructions=[s for s in instructions if s in [
'FMUL R15, R14, R15', 'FADD R15, R15, R0',
'FMUL R18, R18, R19', 'FMUL R20, R20, R21',
'FADD R15, R15, R18', 'FADD R15, R15, R20',
'FMUL R22, R22, R23', 'FADD R0, R15, R22']]
assert loop_instructions==[
'FMUL R15, R14, R15', 'FADD R15, R15, R0',
'FMUL R18, R18, R19', 'FMUL R20, R20, R21',
'FADD R15, R15, R18', 'FADD R15, R15, R20',
'FMUL R22, R22, R23', 'FADD R0, R15, R22']
for statement in ['IADD.64 R4, R4, 0x4','ISETP.GE.U64.AND P1, PT, R4, UR6, PT',
'LDG.E R15, desc[UR8][R12.64]', 'LDG.E R14, desc[UR8][R16.64]',
'LDG.E R19, desc[UR8][R12.64+0x4]', 'LDG.E R18, desc[UR8][R16.64+0x4]',
'LDG.E R21, desc[UR8][R12.64+0x8]', 'LDG.E R20, desc[UR8][R16.64+0x8]',
'LDG.E R23, desc[UR8][R12.64+0xc]', 'LDG.E R22, desc[UR8][R16.64+0xc]']:
assert statement in loop
assert '".L_x_1":exit0:e -> ".L_x_1":entry:n' in cfg
assert 'FADD R0, R0, R13' in instructions and 'FADD R0, R0, R19' in instructions
assert '@P0 FMUL R7, R8, R11' in instructions and '@P0 FADD R0, R0, R7' in instructions
assert ops.count('STG')==1
# HFMA2 here materializes integer address high-half zero only; it is not an
# f32 recurrence operation. Explicitly identify it instead of hiding it.
assert [s for s in instructions if 'HFMA2' in s]==['HFMA2 R3, -RZ, RZ, 0, 0']
print('Emitted dataflow/CFG: row guard, positive-zero accumulator, u64 column induction, '
'ascending four/two/one column additions and final single store: PASS')
print('HFMA2 R3 zero materialization is address initialization; no FFMA/FMAd in binary32 recurrence')
print('Actual emitted instruction counts:',len(instructions),{op:ops.count(op) for op in sorted(set(ops))})
print('Emitted separate FMUL/FADD, no FMA/MAD, guarded memory/control-flow artifact: PASS; '
'inspect printed operands/loop edges for this pinned target only')
PY
-104
View File
@@ -1,104 +0,0 @@
#!/usr/bin/env python3
"""Owned synthetic CLI tests for private paired Markdown publication."""
import copy
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
SCRIPT = Path(__file__).with_name("render-paired-report.py")
class MarkdownTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(prefix="leleka-paired-md-")
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.source = self.root / "input.json"
self.output = self.root / "report.md"
self.report = {"schema": 1, "metadata": {"private": "PRIVATE_VALUE"},
"pairs": [{"response": "PRIVATE_RESPONSE"}], "summary": {
"pairs": 2, "baseline_quality_passed": 2, "candidate_quality_passed": 1,
"same_normalized_output": 1, "candidate_over_baseline_wall_median_ratio": 0.8,
"categories": {"tool|<script>[link](url)": {
"pairs": 2, "both_quality_passed": 1, "same_normalized_output": 1,
"candidate_over_baseline_wall_median_ratio": 0.8}},
"prefill": None, "decode": {"pairs": 2,
"baseline_median_tokens_per_second": 100,
"candidate_median_tokens_per_second": 125,
"candidate_over_baseline_median_ratio": 1.25}}}
def run_report(self, report=None, output=None):
self.source.write_text(json.dumps(self.report if report is None else report))
return subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.source),
"--output", str(output or self.output)], text=True,
capture_output=True, timeout=10)
def test_summary_quality_limits_and_privacy(self):
result = self.run_report()
self.assertEqual(result.returncode, 0, result.stderr)
document = self.output.read_text()
self.assertIn("1/2", document)
self.assertIn("0.8", document)
self.assertIn("1.25", document)
self.assertIn("do not qualify GPU inference", document)
self.assertIn("&#124;", document)
self.assertNotIn("<script>", document)
for secret in ("PRIVATE_VALUE", "PRIVATE_RESPONSE"):
self.assertNotIn(secret, document + result.stdout + result.stderr)
self.assertNotIn("tool|", result.stdout + result.stderr)
self.assertEqual(self.output.stat().st_mode & 0o777, 0o600)
def test_no_overwrite(self):
self.output.write_text("keep")
self.assertNotEqual(self.run_report().returncode, 0)
self.assertEqual(self.output.read_text(), "keep")
def test_invalid_measurements_publish_nothing(self):
for value in (0, -1, True, float("nan"), float("inf"), "0.8"):
with self.subTest(value=value):
report = copy.deepcopy(self.report)
report["summary"]["candidate_over_baseline_wall_median_ratio"] = value
self.assertNotEqual(self.run_report(report).returncode, 0)
self.assertFalse(self.output.exists())
def test_counts_must_match(self):
report = copy.deepcopy(self.report)
report["summary"]["categories"][next(iter(report["summary"]["categories"]))]["pairs"] = 1
self.assertNotEqual(self.run_report(report).returncode, 0)
self.assertFalse(self.output.exists())
def test_distribution_and_small_sample_interval(self):
self.report["summary"]["candidate_over_baseline_wall_ratio_distribution"] = {
"sample_count": 2, "mean": 0.8, "median": 0.8, "p10": 0.7, "p90": 0.9,
"small_sample": True, "median_confidence_interval": {
"confidence_level": 0.95, "finite_interval_available": False,
"lower": None, "upper": None}}
self.assertEqual(self.run_report().returncode, 0)
document = self.output.read_text()
self.assertIn("small sample (<30 pairs)", document)
self.assertIn("insufficient pairs for finite interval", document)
def test_interval_not_allowed_to_hide_invalid_bounds(self):
self.report["summary"]["candidate_over_baseline_wall_ratio_distribution"] = {
"sample_count": 2, "mean": 0.8, "median": 0.8, "p10": 0.7, "p90": 0.9,
"small_sample": True, "median_confidence_interval": {
"confidence_level": 0.95, "finite_interval_available": True,
"lower": 0.9, "upper": 1.0}}
self.assertNotEqual(self.run_report().returncode, 0)
self.assertFalse(self.output.exists())
def test_git_output_refused(self):
git = self.root / "checkout"
git.mkdir()
(git / ".git").write_text("gitdir: ignored")
output = git / "private.md"
self.assertNotEqual(self.run_report(output=output).returncode, 0)
self.assertFalse(output.exists())
if __name__ == "__main__":
unittest.main()
-301
View File
@@ -1,301 +0,0 @@
#!/usr/bin/env python3
"""Independent, offline synthetic regression checks for private paired reports."""
import copy
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parent.parent
SCRIPT = ROOT / "scripts/compare-chat-reports.py"
PRIVATE = "PRIVATE_SYNTHETIC_SENTINEL_7863"
def response():
return {"choices": [{"message": {"role": "assistant", "content": "OK"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 20, "completion_tokens": 2, "total_tokens": 22},
"timings": {"prompt_n": 20, "predicted_n": 2, "prompt_per_second": 200.0,
"predicted_per_second": 50.0}}
def report(walls=(1., 2., 3., 4., 5., 6.), case="case", category="arithmetic"):
rows = []
for repeat, wall in [(None, 10000.), *enumerate(walls)]:
rows.append({"arm": "baseline", "case_id": case, "category": category,
"repeat": repeat, "warmup": repeat is None, "wall_seconds": wall,
"http_status": 200, "quality": {"passed": True}, "response": response()})
return {"schema": 1, "suite_sha256": "a" * 64, "model": "synthetic-only",
"configuration": {"repeats": len(walls), "temperature": 0, "seed": 42},
"metadata": {}, "rows": rows}
class PairedReports(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="paired-report-private-")
self.addCleanup(self.temp.cleanup)
self.directory = Path(self.temp.name)
self.b, self.c, self.out = (self.directory / name for name in ("baseline.json", "candidate.json", "comparison.json"))
def invoke(self, baseline, candidate, output=None):
self.b.write_text(json.dumps(baseline))
self.c.write_text(json.dumps(candidate))
result = subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.b), str(self.c),
"--output", str(output or self.out)], text=True, capture_output=True, timeout=15)
self.assertNotIn(PRIVATE, result.stdout + result.stderr)
return result
def compare(self, baseline, candidate):
result = self.invoke(baseline, candidate)
self.assertEqual(result.returncode, 0, result.stderr)
return json.loads(self.out.read_text())
def refuse(self, baseline, candidate):
self.out.unlink(missing_ok=True)
result = self.invoke(baseline, candidate)
self.assertNotEqual(result.returncode, 0)
self.assertFalse(self.out.exists(), "invalid input must not publish a report")
self.assertNotIn("Traceback", result.stderr)
def test_known_outlier_distribution_and_exact_interval(self):
result = self.compare(report((1.,) * 6), report((1., 2., 3., 4., 5., 100.)))
group = result["summary"]["cases"]["case"]
stats = group["candidate_over_baseline_wall_ratio_distribution"]
self.assertEqual(stats["sample_count"], 6)
self.assertAlmostEqual(stats["mean"], 115 / 6)
self.assertEqual(stats["median"], 3.5)
self.assertEqual(stats["p10"], 1.5)
self.assertEqual(stats["p90"], 52.5)
ci = stats["median_confidence_interval"]
# For six independent pairs, extrema cover the median except both
# all-below/all-above events: 1 - 2*(1/2)^6 = 31/32.
self.assertEqual((ci["lower"], ci["upper"]), (1., 100.))
self.assertEqual(ci["coverage_lower_bound"], 31 / 32)
self.assertTrue(stats["small_sample"])
self.assertEqual(result["summary"]["categories"]["arithmetic"], group)
self.assertEqual(group["wall_seconds"]["baseline"]["mean"], 1)
def test_pair_ratios_are_not_ratio_of_arm_medians(self):
baseline, candidate = report((1., 2., 100.) * 2), report((2., 100., 101.) * 2)
for row in baseline["rows"]:
row["response"]["timings"]["predicted_per_second"] = row["wall_seconds"]
for row in candidate["rows"]:
row["response"]["timings"]["predicted_per_second"] = row["wall_seconds"]
summary = self.compare(baseline, candidate)["summary"]
self.assertEqual(summary["candidate_over_baseline_wall_median_ratio"], 2)
self.assertEqual(summary["decode"]["candidate_over_baseline_median_ratio"], 2)
self.assertEqual(summary["decode"]["candidate_median_tokens_per_second"] /
summary["decode"]["baseline_median_tokens_per_second"], 50)
def test_small_n_has_no_fabricated_finite_confidence(self):
stats = self.compare(report((2.,)), report((1.,)))["summary"]["candidate_over_baseline_wall_ratio_distribution"]
ci = stats["median_confidence_interval"]
self.assertEqual(stats["median"], .5)
self.assertFalse(ci["finite_interval_available"])
self.assertIsNone(ci["lower"])
self.assertIsNone(ci["upper"])
self.assertTrue(stats["small_sample"])
def test_independent_binomial_order_statistic_references(self):
# Published binomial tail values/reference ranks, independent of the
# comparator's recurrence. Values 1..n make each rank unambiguous.
for n, bounds, coverage in ((5, (None, None), None),
(9, (2, 8), .9609375),
(30, (10, 21), .9572260547429323)):
with self.subTest(n=n):
self.out.unlink(missing_ok=True)
data = self.compare(report((1.,) * n), report(tuple(range(1, n + 1))))
stats = data["summary"]["candidate_over_baseline_wall_ratio_distribution"]
ci = stats["median_confidence_interval"]
self.assertEqual((ci["lower"], ci["upper"]), bounds)
if coverage is None:
self.assertIsNone(ci["coverage_lower_bound"])
else:
self.assertAlmostEqual(ci["coverage_lower_bound"], coverage)
self.assertEqual(stats["small_sample"], n < 30)
def test_deterministic_and_order_independent(self):
baseline, candidate = report(), report((2., 1., 4., 3., 9., 7.))
first = self.compare(baseline, candidate)
self.out.unlink()
baseline["rows"].reverse()
candidate["rows"].reverse()
second = self.compare(baseline, candidate)
self.assertEqual(first["summary"], second["summary"])
self.assertEqual(first["pairs"], second["pairs"])
def test_failed_category_cannot_be_averaged_into_pass(self):
baseline, candidate = report(), report()
baseline["rows"] += report(case=PRIVATE, category="tool-integrity")["rows"]
candidate["rows"] += report(case=PRIVATE, category="tool-integrity")["rows"]
candidate["rows"][-1].update(http_status=500, response={"error": PRIVATE}, quality={"passed": False})
result = self.compare(baseline, candidate)
summary = result["summary"]
self.assertTrue(summary["categories"]["arithmetic"]["quality"]["observed_checks_passed"])
failed = summary["categories"]["tool-integrity"]["quality"]
self.assertEqual(failed["candidate_failed"], 1)
self.assertEqual(failed["candidate_http_or_protocol_failed"], 1)
self.assertFalse(failed["observed_checks_passed"])
self.assertFalse(summary["quality"]["observed_checks_passed"])
self.assertEqual(summary["failed_quality_categories"], ["tool-integrity"])
self.assertFalse(result["qualification"]["performance_qualified"])
self.assertFalse(result["qualification"]["model_quality_qualified"])
def test_optional_cached_zero_rates_are_disclosed_not_divided(self):
baseline, candidate = report(), report()
for row in baseline["rows"] + candidate["rows"]:
row["response"]["timings"]["prompt_per_second"] = 0
row["response"]["timings"]["prompt_n"] = 0
row["response"]["timings"]["cache_n"] = 20
candidate["rows"][-1]["response"].pop("timings")
summary = self.compare(baseline, candidate)["summary"]
self.assertIsNone(summary["prefill"])
self.assertEqual(summary["timing_coverage"]["prompt_per_second"]["available_pairs"], 0)
self.assertEqual(summary["decode"]["pairs"], 5)
self.assertEqual(summary["decode"]["unavailable_pairs"], 1)
def test_invalid_numeric_and_structural_rows_refused(self):
mutations = [
lambda r: r.update(wall_seconds=0), lambda r: r.update(wall_seconds=-1),
lambda r: r.update(wall_seconds=float("nan")), lambda r: r.update(wall_seconds=float("inf")),
lambda r: r.update(wall_seconds=True), lambda r: r.update(wall_seconds="2"),
lambda r: r.update(http_status=True), lambda r: r.update(http_status=99),
lambda r: r.update(http_status=500), lambda r: r.update(quality={"passed": 1}),
lambda r: r.update(quality={"passed": "false"}), lambda r: r.update(response=[]),
lambda r: r.update(warmup="false"), lambda r: r.update(repeat=True),
lambda r: r["response"].update(timings=[]),
lambda r: r["response"]["timings"].update(predicted_per_second=float("nan")),
lambda r: r["response"]["timings"].update(predicted_per_second=-1),
lambda r: r["response"]["timings"].update(predicted_per_second=True),
lambda r: r["response"]["timings"].update(prompt_n=2.5),
lambda r: r["response"].update(usage="bad"),
lambda r: r["response"]["usage"].update(total_tokens=1),
lambda r: r["response"]["usage"].update(completion_tokens=True),
lambda r: r["response"]["usage"].update(prompt_tokens_details={"cached_tokens": 21}),
]
for index, mutate in enumerate(mutations):
with self.subTest(index=index):
candidate = report()
mutate(candidate["rows"][1])
self.refuse(report(), candidate)
def test_pairing_warmups_categories_and_bounds_refused(self):
mutations = [lambda r: r["rows"].append(copy.deepcopy(r["rows"][1])),
lambda r: r["rows"].append(copy.deepcopy(r["rows"][0])),
lambda r: r["rows"].pop(), lambda r: r["rows"].pop(0),
lambda r: r["rows"][1].update(category="other"),
lambda r: r["rows"][1].update(case_id=PRIVATE),
lambda r: r["rows"][1].update(arm="candidate"),
lambda r: r["configuration"].update(repeats=101),
lambda r: r["configuration"].update(repeats=True),
lambda r: r["configuration"].update(max_tokens=True),
lambda r: r["configuration"].update(stream=True),
lambda r: r.update(schema=True), lambda r: r.update(suite_sha256="bad"),
lambda r: r.update(metadata=[])]
for index, mutate in enumerate(mutations):
with self.subTest(index=index):
candidate = report()
mutate(candidate)
self.refuse(report(), candidate)
baseline, candidate = report(), report()
baseline["metadata"]["gpu"] = "fixture-a"
candidate["metadata"]["gpu"] = "fixture-b"
self.refuse(baseline, candidate)
def test_malformed_tools_and_incomplete_terminals_refused(self):
call = {"id": "call_fixture", "type": "function", "function": {"name": "synthetic", "arguments": '{"x":1}'}}
for invalid in ("missing-id", "empty-id", "whitespace-id", "whitespace-name", "duplicate-id", "overflow", "duplicate-field", "list-arguments", "incomplete"):
with self.subTest(invalid=invalid):
candidate = report()
choice = candidate["rows"][1]["response"]["choices"][0]
choice.update(finish_reason="tool_calls", message={"role": "assistant", "content": None, "tool_calls": [copy.deepcopy(call)]})
calls = choice["message"]["tool_calls"]
if invalid == "missing-id": calls[0].pop("id")
if invalid == "empty-id": calls[0]["id"] = ""
if invalid == "whitespace-id": calls[0]["id"] = " \t"
if invalid == "whitespace-name": calls[0]["function"]["name"] = " \t"
if invalid == "duplicate-id": calls.append(copy.deepcopy(calls[0]))
if invalid == "overflow": calls[0]["function"]["arguments"] = '{"x":1e309}'
if invalid == "duplicate-field": calls[0]["function"]["arguments"] = '{"x":1,"x":2}'
if invalid == "list-arguments": calls[0]["function"]["arguments"] = '[1]'
if invalid == "incomplete": choice["finish_reason"] = "length"
self.refuse(report(), candidate)
def test_failure_terminals_never_count_as_protocol_equivalence(self):
baseline, candidate = report(), report()
for row in baseline["rows"] + candidate["rows"]:
row["quality"]["passed"] = False
row["response"]["choices"][0]["finish_reason"] = "length"
summary = self.compare(baseline, candidate)["summary"]
self.assertEqual(summary["same_normalized_output"], 0)
self.assertEqual(summary["quality"]["candidate_http_or_protocol_failed"], 6)
self.assertFalse(summary["quality"]["observed_checks_passed"])
def test_case_pair_and_nested_json_work_limits(self):
baseline = report((1.,))
for index in range(1, 65):
baseline["rows"] += report((1.,), case=f"case-{index}")["rows"]
self.refuse(baseline, copy.deepcopy(baseline))
baseline = report((1.,) * 100)
for index in range(1, 41):
baseline["rows"] += report((1.,) * 100, case=f"case-{index}")["rows"]
self.refuse(baseline, copy.deepcopy(baseline))
baseline = report()
nested = {}
for _ in range(33):
nested = {"nested": nested}
baseline["metadata"] = nested
self.refuse(baseline, report())
def test_provenance_names_only_and_never_automatic_qualification(self):
baseline, candidate = report(), report()
baseline["metadata"] = candidate["metadata"] = {"operator_note": PRIVATE, "quality_gate_result": "claimed-pass"}
result = self.compare(baseline, candidate)
missing = result["provenance"]["candidate"]["missing_fields"]
self.assertIn("gpu", missing)
self.assertIn("ttft", missing)
self.assertNotIn("quality_gate_result", missing)
self.assertNotIn(PRIVATE, json.dumps(result["provenance"]))
self.assertIn("Synthetic/CPU", result["comparison_limit"])
self.assertFalse(result["qualification"]["model_quality_qualified"])
def test_private_mode_no_overwrite_and_no_git_output(self):
old_mask = os.umask(0)
try:
self.compare(report(), report())
finally:
os.umask(old_mask)
self.assertEqual(self.out.stat().st_mode & 0o777, 0o600)
original = self.out.read_bytes()
self.assertNotEqual(self.invoke(report(), report()).returncode, 0)
self.assertEqual(self.out.read_bytes(), original)
git_directory = self.directory / "fake-git"
git_directory.mkdir()
(git_directory / ".git").write_text("gitdir: fixture")
output = git_directory / "report.json"
self.assertNotEqual(self.invoke(report(), report(), output).returncode, 0)
self.assertFalse(output.exists())
symlink = self.directory / "link.json"
destination = self.directory / "nonexistent.json"
symlink.symlink_to(destination)
self.assertNotEqual(self.invoke(report(), report(), symlink).returncode, 0)
self.assertFalse(destination.exists())
def test_duplicate_json_and_oversize_refused_without_private_diagnostic(self):
self.c.write_text(json.dumps(report()))
self.b.write_text('{"schema":1,"schema":1,"private":"' + PRIVATE + '"}')
result = subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.b), str(self.c), "--output", str(self.out)], capture_output=True, text=True, timeout=15)
self.assertNotEqual(result.returncode, 0)
self.assertNotIn(PRIVATE, result.stdout + result.stderr)
self.assertFalse(self.out.exists())
with self.b.open("wb") as source:
source.truncate(32 * 1024 * 1024 + 1)
result = subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.b), str(self.c), "--output", str(self.out)], capture_output=True, text=True, timeout=15)
self.assertNotEqual(result.returncode, 0)
self.assertFalse(self.out.exists())
if __name__ == "__main__":
unittest.main()
+357
View File
@@ -0,0 +1,357 @@
#!/usr/bin/env python3
"""Synthetic, offline tests for the secret-safe PLE parity preflight."""
import importlib.util
import hashlib
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('parity', Path(__file__).with_name('check-ple-config-parity.py'))
parity = importlib.util.module_from_spec(spec)
spec.loader.exec_module(parity)
class ParityTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.archive = self.root / 'synthetic.kar'
self.archive.write_bytes(b'synthetic archive bytes')
self.archive_sha = hashlib.sha256(self.archive.read_bytes()).hexdigest()
self.legacy_args = [
'--pack', '/models/current-pack', '--native',
'/models/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf',
'--max-context', '262144', '--kv', 'int8', '--kv-resident', '32768',
'--spec', '4', '--spec-min-p', '0.5', '--expert-cache', 'auto',
'--prefill', 'auto', '--vram-reserve-mib', '700', '--mtp', '/models/mtp-v1',
]
self.candidate_executable = '/runtime/strata-next'
self.ple = ['--ple-kar', str(self.archive), '--ple-kar-level', '2',
'--ple-kar-gpu-cache-mib', '64']
self.legacy = {'exe': '/legacy/strata', 'args': list(self.legacy_args),
'cwd': '/srv/qwen', 'log': '/var/log/old-engine.log'}
self.candidate = {
'bind': '127.0.0.1:18081',
'api_key_file': str(self.root / 'unread-api-key'),
'max_in_flight_requests': 1,
'engine': {'executable': self.candidate_executable,
'args': self.legacy_args_after_migration() + self.ple,
'startup_timeout_s': 600, 'max_restarts': 0},
'native_model': {'manifest': '/fixtures/qwen3.8-flash-next-iq3-s.json',
'source_dir': '/models', 'output': '/models/new-pack',
'runtime_profile': 'qwen4exp-flash-next'},
'assets': [{'manifest': '/fixtures/mtp-manifest.json',
'directory': '/models/mtp-v1'}],
'mtp_pack': '/models/mtp-v1',
}
self.context = {
'legacy': {'bind': '192.168.1.196:18081', 'cwd': '/srv/qwen',
'log': '/var/log/old-engine.log', 'effective_slots': 1,
'environment': {}},
'candidate': {'bind': '127.0.0.1:18081', 'cwd': '/srv/qwen',
'log': 'systemd-journal', 'effective_slots': 1,
'environment': {}},
'environment_complete': True,
}
self.expected_sha = parity.PINNED_ARCHIVE_SHA256
def legacy_args_after_migration(self):
result = []
skip = False
for token in self.legacy_args:
if skip:
skip = False
elif token in {'--pack', '--native', '--mtp'}:
skip = True
else:
result.append(token)
return result
def run_compare(self, *, legacy=None, candidate=None, context=None):
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha):
return parity.compare(legacy or self.legacy, candidate or self.candidate,
context or self.context, self.archive, self.archive_sha,
self.candidate_executable, '127.0.0.1:18081', 'systemd-journal')
def test_baseline_to_gpu_ple_is_incomplete_not_full_pass(self):
result = self.run_compare()
self.assertEqual(result['status'], 'incomplete')
self.assertEqual(result['mismatches'], [])
self.assertEqual(set(result['unverified']), parity.UNVERIFIED)
self.assertIn('request_model_identity', result['unverified'])
def test_already_ple_selected_in_original_is_preserved_exactly(self):
legacy = json.loads(json.dumps(self.legacy))
legacy['args'] += self.ple
candidate = json.loads(json.dumps(self.candidate))
candidate['engine']['args'] = self.legacy_args_after_migration() + self.ple
self.assertEqual(self.run_compare(legacy=legacy, candidate=candidate)['mismatches'], [])
def test_partial_duplicate_changed_or_reordered_ple_fails(self):
cases = [
self.ple[:-2],
self.ple + self.ple,
['--ple-kar', str(self.archive), '--ple-kar-level', '3', '--ple-kar-gpu-cache-mib', '64'],
['--ple-kar-level', '2', '--ple-kar', str(self.archive), '--ple-kar-gpu-cache-mib', '64'],
]
for flags in cases:
with self.subTest(flags=flags):
legacy = json.loads(json.dumps(self.legacy))
legacy['args'] += flags
result = self.run_compare(legacy=legacy)
self.assertIn('ple_arguments', result['mismatches'])
def test_malformed_candidate_ple_tuple_is_rejected(self):
cases = [
self.ple[:-2],
self.ple + self.ple,
['--ple-kar', str(self.archive), '--ple-kar-level', '1',
'--ple-kar-gpu-cache-mib', '64'],
['--ple-kar-level', '2', '--ple-kar', str(self.archive),
'--ple-kar-gpu-cache-mib', '64'],
]
for flags in cases:
with self.subTest(flags=flags):
candidate = json.loads(json.dumps(self.candidate))
candidate['engine']['args'] = self.legacy_args_after_migration() + flags
result = self.run_compare(candidate=candidate)
self.assertIn('ple_arguments', result['mismatches'])
def test_changes_to_non_ple_model_mtp_and_profile_settings_fail(self):
cases = []
altered = json.loads(json.dumps(self.candidate))
altered['engine']['args'][1] = '262143'
cases.append((altered, 'profile_settings'))
altered = json.loads(json.dumps(self.legacy))
altered['args'][3] = '/models/Other-IQ3_S.gguf'
cases.append((altered, 'model_selection'))
altered = json.loads(json.dumps(self.candidate))
altered['mtp_pack'] = '/models/mtp-other'
altered['assets'][0]['directory'] = '/models/mtp-other'
cases.append((altered, 'mtp_asset_mapping'))
altered = json.loads(json.dumps(self.candidate))
altered['engine']['args'].insert(0, '--force')
altered['engine']['args'].insert(1, 'other')
cases.append((altered, 'engine_arguments'))
for value, expected in cases:
with self.subTest(expected=expected):
if expected in ('model_selection',):
result = self.run_compare(legacy=value)
else:
result = self.run_compare(candidate=value)
self.assertIn(expected, result['mismatches'])
def test_every_retained_profile_setting_must_match_on_both_sides(self):
for flag, wanted in parity.REQUIRED_SETTINGS.items():
with self.subTest(flag=flag, side='legacy'):
legacy = json.loads(json.dumps(self.legacy))
index = legacy['args'].index(flag)
legacy['args'][index + 1] = f'{wanted}-changed'
self.assertIn('profile_settings',
self.run_compare(legacy=legacy)['mismatches'])
with self.subTest(flag=flag, side='candidate'):
candidate = json.loads(json.dumps(self.candidate))
index = candidate['engine']['args'].index(flag)
candidate['engine']['args'][index + 1] = f'{wanted}-changed'
self.assertIn('profile_settings',
self.run_compare(candidate=candidate)['mismatches'])
def test_service_context_requires_bind_workdir_log_and_one_slot(self):
for key, value in [('cwd', '/srv/other'), ('bind', '0.0.0.0:18081'),
('log', '/tmp/other.log'), ('effective_slots', 2)]:
context = json.loads(json.dumps(self.context))
context['candidate'][key] = value
result = self.run_compare(context=context)
expected = {'cwd': 'working_directory', 'bind': 'bind_selection',
'log': 'log_selection', 'effective_slots': 'slot_count'}[key]
self.assertIn(expected, result['mismatches'])
context = json.loads(json.dumps(self.context))
context['environment_complete'] = False
self.assertIn('effective_environment', self.run_compare(context=context)['unverified'])
for side in ('legacy', 'candidate'):
context = json.loads(json.dumps(self.context))
context[side].pop('effective_slots')
result = self.run_compare(context=context)
self.assertNotIn('slot_count', result['mismatches'])
self.assertIn('worker_slot_count', result['unverified'])
def test_only_declared_bind_and_executable_environment_deltas_are_allowed(self):
context = json.loads(json.dumps(self.context))
context['candidate']['environment'] = {
'STRATA_BIND': '127.0.0.1:18081',
'STRATA_ENGINE_EXE': self.candidate_executable,
}
self.assertEqual(self.run_compare(context=context)['mismatches'], [])
context['candidate']['environment']['CUDA_VISIBLE_DEVICES'] = '1'
self.assertIn('environment_delta', self.run_compare(context=context)['mismatches'])
def test_http_request_capacity_is_not_confused_with_worker_slot_count(self):
candidate = json.loads(json.dumps(self.candidate))
candidate.pop('max_in_flight_requests')
result = self.run_compare(candidate=candidate)
self.assertNotIn('slot_count', result['mismatches'])
self.assertIn('http_capacity_policy', result['unverified'])
def test_archive_bytes_are_stream_checked_against_pin(self):
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha):
parity.check_archive(self.archive, self.archive_sha)
self.archive.write_bytes(b'corrupted fixture')
with self.assertRaisesRegex(parity.InvalidInput, 'archive_digest'):
parity.check_archive(self.archive, self.archive_sha)
with self.assertRaisesRegex(parity.InvalidInput, 'archive_pin'):
parity.check_archive(self.archive, '0' * 64)
def test_strict_json_rejects_duplicates_constants_invalid_utf8_and_nonobject(self):
path = self.root / 'config.json'
for raw in (b'{"x":1,"x":2}', b'{"x":NaN}', b'\xff', b'[]'):
with self.subTest(raw=raw):
path.write_bytes(raw)
with self.assertRaises(parity.InvalidInput):
value = parity.read_json(path)
parity.validate_legacy(value)
def test_json_parser_recursion_and_overflow_errors_are_bounded(self):
path = self.root / 'nested.json'
path.write_text('{}')
for error in (RecursionError, OverflowError):
with self.subTest(error=error.__name__):
with patch.object(parity.json, 'loads', side_effect=error):
with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'):
parity.read_json(path)
def test_safe_file_open_accepts_regular_files_and_rejects_symlinks(self):
config = self.root / 'regular.json'
config.write_text('{}')
self.assertEqual(parity.read_json(config), {})
config_link = self.root / 'config-link.json'
config_link.symlink_to(config)
with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'):
parity.read_json(config_link)
archive_link = self.root / 'archive-link.kar'
archive_link.symlink_to(self.archive)
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha):
with self.assertRaisesRegex(parity.InvalidInput, 'archive_file'):
parity.check_archive(archive_link, self.archive_sha)
@unittest.skipUnless(hasattr(os, 'mkfifo'), 'named FIFO unavailable')
def test_named_fifo_is_rejected_quickly_for_json_and_archive(self):
fifo = self.root / 'input.fifo'
os.mkfifo(fifo)
module_path = Path(__file__).with_name('check-ple-config-parity.py')
code = (
"import importlib.util,sys; "
"s=importlib.util.spec_from_file_location('p',sys.argv[1]); "
"m=importlib.util.module_from_spec(s); s.loader.exec_module(m); "
"\ntry:\n"
" if sys.argv[3]=='json': m.read_json(sys.argv[2])\n"
" else: m.check_archive(sys.argv[2],m.PINNED_ARCHIVE_SHA256)\n"
"except m.InvalidInput: pass\nelse: raise SystemExit(9)"
)
for kind in ('json', 'archive'):
with self.subTest(kind=kind):
result = subprocess.run(
[sys.executable, '-c', code, str(module_path), str(fifo), kind],
capture_output=True, text=True, timeout=2)
self.assertEqual(result.returncode, 0, result.stderr)
def test_nonregular_open_failure_closes_the_descriptor(self):
opened = []
real_open = os.open
def capture(path, flags):
fd = real_open(path, flags)
opened.append(fd)
return fd
with patch.object(parity.os, 'open', capture):
with self.assertRaisesRegex(parity.InvalidInput, 'invalid_json'):
parity.open_regular(self.root, 'invalid_json')
self.assertEqual(len(opened), 1)
with self.assertRaises(OSError):
os.fstat(opened[0])
def test_candidate_resource_limits_match_runtime_bounds(self):
cases = []
candidate = json.loads(json.dumps(self.candidate))
candidate['max_in_flight_requests'] = 257
cases.append(candidate)
candidate = json.loads(json.dumps(self.candidate))
candidate['assets'] = [{'manifest': f'/m/{i}', 'directory': f'/a/{i}'}
for i in range(parity.MAX_ASSET_BUNDLES + 1)]
cases.append(candidate)
for memory in ({'required_mib': parity.U64_MAX + 1, 'reserve_mib': 0},
{'required_mib': parity.U64_MAX, 'reserve_mib': 1},
{'required_mib': 1, 'reserve_mib': -1}):
candidate = json.loads(json.dumps(self.candidate))
candidate['cuda_memory'] = memory
cases.append(candidate)
for candidate in cases:
with self.subTest(candidate=candidate):
with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'):
parity.validate_candidate(candidate)
def test_unknown_legacy_and_native_keys_are_rejected(self):
legacy = dict(self.legacy, future_secret_setting='opaque')
with self.assertRaisesRegex(parity.InvalidInput, 'legacy_schema'):
parity.validate_legacy(legacy)
with self.assertRaisesRegex(parity.InvalidInput, 'legacy_credential_present'):
parity.validate_legacy(dict(self.legacy, api_key='must-not-be-read'))
candidate = json.loads(json.dumps(self.candidate))
candidate['future_runtime_setting'] = True
with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'):
parity.validate_candidate(candidate)
candidate = json.loads(json.dumps(self.candidate))
candidate['engine']['future_runtime_setting'] = True
with self.assertRaisesRegex(parity.InvalidInput, 'candidate_schema'):
parity.validate_candidate(candidate)
def test_candidate_secret_file_is_not_opened_and_output_never_contains_secret(self):
secret_path = Path(self.candidate['api_key_file'])
secret_path.write_text('synthetic-secret-do-not-print')
original_open = Path.open
def guarded_open(path, *args, **kwargs):
if path == secret_path:
raise AssertionError('secret file must not be opened')
return original_open(path, *args, **kwargs)
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha), \
patch.object(Path, 'open', guarded_open):
output = parity.compare(self.legacy, self.candidate, self.context, self.archive,
self.archive_sha, self.candidate_executable,
'127.0.0.1:18081', 'systemd-journal')
encoded = json.dumps(output)
self.assertNotIn('synthetic-secret', encoded)
self.assertEqual(output['status'], 'incomplete')
def test_cli_prints_safe_json_and_returns_two_for_positive_incomplete_fixture(self):
legacy_path = self.root / 'legacy.json'
candidate_path = self.root / 'candidate.json'
context_path = self.root / 'context.json'
for path, value in ((legacy_path, self.legacy), (candidate_path, self.candidate),
(context_path, self.context)):
path.write_text(json.dumps(value))
stdout = io.StringIO()
argv = ['--legacy-config', str(legacy_path), '--candidate-config', str(candidate_path),
'--service-context', str(context_path), '--archive', str(self.archive),
'--archive-sha256', self.archive_sha, '--expected-executable', self.candidate_executable,
'--expected-bind', '127.0.0.1:18081', '--expected-log', 'systemd-journal']
with patch.object(parity, 'PINNED_ARCHIVE_SHA256', self.archive_sha), redirect_stdout(stdout):
result = parity.main(argv)
self.assertEqual(result, 2)
self.assertNotIn('synthetic-secret', stdout.getvalue())
self.assertNotIn(str(self.root), stdout.getvalue())
self.assertEqual(json.loads(stdout.getvalue())['status'], 'incomplete')
if __name__ == '__main__':
unittest.main()
+139
View File
@@ -3,6 +3,7 @@
import importlib.util
import hashlib
import json
import subprocess
from pathlib import Path
import shutil
import tempfile
@@ -156,5 +157,143 @@ class PackageTests(unittest.TestCase):
b.frozen_file(self.pkg/b.NAME, Path(stage)/'out', 1)
class IsolatedProbeTests(unittest.TestCase):
def setUp(self):
reporter = patch.object(b, '_report_best_effort')
reporter.start()
self.addCleanup(reporter.stop)
def fake_docker(self, calls, *, wait_stdout='0\n', wait_stderr='', wait_rc=0,
logs_stdout='probe output\n', logs_stderr='', logs_rc=0,
start_error=None, wait_error=None, cleanup_error=None, logs_size=None):
container = None
def invoke(*args, timeout=30, check=True):
nonlocal container
calls.append((args, timeout, check))
if args[0] == 'create':
container = args[args.index('--name') + 1]
return SimpleNamespace(stdout='a' * 64 + '\n', stderr='', returncode=0)
if args[0] == 'start':
self.assertEqual(args[1], container)
if start_error is not None:
raise start_error
return SimpleNamespace(stdout=container + '\n', stderr='', returncode=0)
if args[0] == 'wait':
self.assertEqual(args[1], container)
if wait_error is not None:
raise wait_error
return SimpleNamespace(stdout=wait_stdout, stderr=wait_stderr, returncode=wait_rc)
if args[0] == 'logs':
self.assertEqual(args[-1], container)
stdout = logs_stdout if logs_size is None else 'x' * logs_size
return SimpleNamespace(stdout=stdout, stderr=logs_stderr, returncode=logs_rc)
if args[:2] == ('inspect', '--format'):
self.assertEqual(args[-1], container)
raise OSError('synthetic inspect unavailable')
if args[0] == 'inspect':
self.assertEqual(args[-1], container)
raise OSError('synthetic inspect unavailable')
if args[:2] == ('rm', '-f'):
self.assertEqual(args[-1], container)
if cleanup_error is not None:
raise cleanup_error
return SimpleNamespace(stdout='', stderr='', returncode=0)
raise AssertionError(f'unexpected Docker call: {args!r}')
return invoke
def test_probe_uses_long_infrastructure_deadline_and_original_cli_deadline(self):
calls = []
with patch.object(b, 'docker', side_effect=self.fake_docker(calls)):
output = b.isolated_run('sha256:' + 'a' * 64, ['engine-info'], entrypoint='strata-next')
self.assertEqual(output, 'probe output\n')
operations = [call[0][0] for call in calls]
self.assertEqual(operations, ['create', 'start', 'wait', 'logs', 'rm'])
create, start, wait, logs, remove = calls
self.assertEqual(create[1], 120)
self.assertEqual(start[1], 120)
self.assertEqual(wait[1], 30)
self.assertEqual(logs[1], 30)
self.assertEqual(remove[1], 10)
self.assertNotIn('--rm', create[0])
self.assertEqual(create[0][create[0].index('--network') + 1], 'none')
self.assertIn('--read-only', create[0])
self.assertIn('--cap-drop', create[0])
self.assertIn('65532:65532', create[0])
self.assertIn('strata-next', create[0])
self.assertEqual(start[0][1], create[0][create[0].index('--name') + 1])
self.assertEqual(wait[0][1], start[0][1])
self.assertEqual(logs[0][-1], start[0][1])
self.assertEqual(remove[0][-1], start[0][1])
def test_probe_rejects_malformed_wait_status_and_bounds_both_streams(self):
for status in ('', '0\n1\n', '-1\n', '256\n'):
with self.subTest(status=status):
calls = []
with patch.object(b, 'docker', side_effect=self.fake_docker(calls, wait_stdout=status)):
with self.assertRaisesRegex(ValueError, 'malformed CLI exit status|outside 0..255'):
b.isolated_run('image', ['engine-help'])
self.assertEqual([x[0][0] for x in calls[:3]], ['create', 'start', 'wait'])
self.assertEqual(calls[-1][0][0:2], ('rm', '-f'))
for stream in ('stdout', 'stderr'):
with self.subTest(stream=stream):
calls = []
kwargs = {'logs_size': b.PROBE_OUTPUT_LIMIT + 1} if stream == 'stdout' else {
'logs_stderr': 'x' * (b.PROBE_OUTPUT_LIMIT + 1)}
with patch.object(b, 'docker', side_effect=self.fake_docker(calls, **kwargs)):
with self.assertRaisesRegex(ValueError, f'CLI {stream} exceeds'):
b.isolated_run('image', ['engine-help'])
self.assertEqual(calls[-1][0][0:2], ('rm', '-f'))
def test_nonzero_cli_exit_preserves_both_streams(self):
calls = []
with patch.object(b, 'docker', side_effect=self.fake_docker(
calls, wait_stdout='17\n', logs_stdout='help stdout', logs_stderr='help stderr')):
with self.assertRaises(subprocess.CalledProcessError) as raised:
b.isolated_run('image', ['engine-help'])
self.assertEqual(raised.exception.returncode, 17)
self.assertEqual(raised.exception.output, 'help stdout')
self.assertEqual(raised.exception.stderr, 'help stderr')
self.assertEqual([x[0][0] for x in calls[:4]], ['create', 'start', 'wait', 'logs'])
self.assertEqual(calls[-1][0][0:2], ('rm', '-f'))
def test_infrastructure_timeout_keeps_original_across_broken_reporting_and_cleanup(self):
calls = []
timeout = subprocess.TimeoutExpired(['docker', 'start'], 120)
with patch.object(b, 'docker', side_effect=self.fake_docker(
calls, start_error=timeout,
cleanup_error=subprocess.TimeoutExpired(['docker', 'rm'], 10))), \
patch.object(b, '_report_best_effort', side_effect=BrokenPipeError('closed stderr')):
with self.assertRaises(subprocess.TimeoutExpired) as raised:
b.isolated_run('image', ['engine-info'])
self.assertIs(raised.exception, timeout)
operations = [x[0][0] for x in calls]
self.assertEqual(operations, ['create', 'start', 'inspect', 'logs', 'rm'])
container = calls[0][0][calls[0][0].index('--name') + 1]
self.assertTrue(all(call[0][-1] == container for call in calls[2:]))
self.assertTrue(all(call[1] <= 10 for call in calls[2:]))
def test_application_timeout_is_not_extended_by_infrastructure_deadlines(self):
calls = []
timeout = subprocess.TimeoutExpired(['docker', 'wait'], 30)
with patch.object(b, 'docker', side_effect=self.fake_docker(calls, wait_error=timeout)):
with self.assertRaises(subprocess.TimeoutExpired) as raised:
b.isolated_run('image', ['engine-help'])
self.assertIs(raised.exception, timeout)
self.assertEqual([x[1] for x in calls[:3]], [120, 120, 30])
self.assertEqual(calls[-1][0][:2], ('rm', '-f'))
def test_cleanup_failure_after_success_is_not_silently_ignored(self):
calls = []
with patch.object(b, 'docker', side_effect=self.fake_docker(
calls, cleanup_error=OSError('synthetic cleanup failure'))):
with self.assertRaisesRegex(OSError, 'synthetic cleanup failure'):
b.isolated_run('image', ['engine-info'])
self.assertEqual(calls[-1][0][0:2], ('rm', '-f'))
self.assertEqual(calls[-1][1], 10)
if __name__ == '__main__':
unittest.main()