Author SHA1 Message Date
Pavlo Ratushnyi 3a478b603c feat(cuda): add fixed typed vector launch and isolated PTX gate
Linux / verify (pull_request) Successful in 6m15s
Linux / keyless-cuda-gate (pull_request) Skipped
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) Failing after 4m2s
Linux / linux-static-cli (pull_request) Successful in 9m31s
Linux / release-cli (pull_request) Skipped
Desktop foundation / core (ubuntu-latest) (push) Failing after 13s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
2026-10-07 23:43:54 +02:00
9 changed files with 1096 additions and 32 deletions
+2
View File
@@ -38,6 +38,8 @@ jobs:
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
- name: Local checks
run: scripts/check-local.sh
- name: GPU-hidden fixed PTX assembly
run: scripts/test-cuda-fixed-ptx.sh
keyless-cuda-gate:
if: gitea.event_name == 'workflow_dispatch'
+165 -12
View File
@@ -11,20 +11,59 @@ use crate::{Error, Result};
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct ContextHandle(usize);
#[derive(Clone, Copy)]
#[cfg_attr(
not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)),
expect(
dead_code,
reason = "No device handle is constructed on unavailable configurations"
)
)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct BufferHandle(u64);
#[derive(Clone, Copy)]
pub(crate) struct ModuleHandle(usize);
#[derive(Clone, Copy)]
pub(crate) struct FunctionHandle(usize);
struct ArgumentStorage {
addresses: [u64; 3],
count: u32,
parameters: [*mut std::ffi::c_void; 4],
}
// Convert the allocation to raw ownership BEFORE forming field pointers.
// A later move or mutable borrow of a Box must not retag/invalidate pointers
// derived from it (std::boxed unsafe-code considerations). This owner moves
// only a NonNull value; it never creates a reference to the pointed-to storage.
// Drop reconstructs the Box once, after completion or before any launch attempt.
pub(crate) struct LaunchArguments {
storage: std::ptr::NonNull<ArgumentStorage>,
}
impl LaunchArguments {
pub(crate) fn new(a: BufferHandle, b: BufferHandle, output: BufferHandle, count: u32) -> Self {
let storage = Box::into_raw(Box::new(ArgumentStorage {
addresses: [a.0, b.0, output.0],
count,
parameters: [std::ptr::null_mut(); 4],
}));
// SAFETY: the non-null allocation is now uniquely raw-owned and stable.
// Initialize all self-referential pointers without borrowing/moving a
// Box or creating new references to the entire allocation.
unsafe {
for i in 0..3 {
(*storage).parameters[i] = (&raw mut (*storage).addresses[i]).cast();
}
(*storage).parameters[3] = (&raw mut (*storage).count).cast();
}
Self {
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
}
}
}
impl Drop for LaunchArguments {
fn drop(&mut self) {
// SAFETY: exactly one owner reconstructs this Box. The caller only
// permits Drop before a launch or after successful synchronization;
// ambiguous completion forgets this owner and retains the allocation.
unsafe {
drop(Box::from_raw(self.storage.as_ptr()));
}
}
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
@@ -49,6 +88,24 @@ mod enabled {
type MemAllocV2 = unsafe extern "C" fn(*mut CuDevicePtr, usize) -> CuResult;
type MemFreeV2 = unsafe extern "C" fn(CuDevicePtr) -> CuResult;
type MemcpyHtoDV2 = unsafe extern "C" fn(CuDevicePtr, *const c_void, usize) -> CuResult;
type ModuleLoadData = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> CuResult;
type ModuleGetFunction =
unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> CuResult;
type ModuleUnload = unsafe extern "C" fn(*mut c_void) -> CuResult;
type LaunchKernel = unsafe extern "C" fn(
*mut c_void,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
c_uint,
*mut c_void,
*mut *mut c_void,
*mut *mut c_void,
) -> CuResult;
static FIXED_PTX: &[u8] = concat!(include_str!("vector_add.ptx"), "\0").as_bytes();
type MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult;
struct Library(*mut c_void);
@@ -77,6 +134,10 @@ mod enabled {
free: MemFreeV2,
copy_from: MemcpyHtoDV2,
copy_to: MemcpyDtoHV2,
load_module: ModuleLoadData,
get_function: ModuleGetFunction,
unload_module: ModuleUnload,
launch_kernel: LaunchKernel,
}
fn check(operation: &'static str, code: CuResult) -> Result<()> {
if code == 0 {
@@ -123,6 +184,10 @@ mod enabled {
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);
Ok(Self {
_library: library,
init,
@@ -137,6 +202,74 @@ mod enabled {
free,
copy_from,
copy_to,
load_module,
get_function,
unload_module,
launch_kernel,
})
}
pub(crate) fn load_fixed_module(&self) -> 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())
})?;
if module.is_null() {
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
}
Ok(ModuleHandle(module as usize))
}
pub(crate) fn fixed_function(&self, module: ModuleHandle) -> 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.
check("cuModuleGetFunction", unsafe {
(self.get_function)(
&mut function,
module.0 as *mut c_void,
c"leleka_vector_add_f32".as_ptr(),
)
})?;
if function.is_null() {
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
}
Ok(FunctionHandle(function as usize))
}
pub(crate) fn unload(&self, module: ModuleHandle) -> Result<()> {
// SAFETY: usable handle was consumed before this single attempt,
// current context owns it, and all prior work completed. It is
// never retried or reused even when unload reports failure.
check("cuModuleUnload", unsafe {
(self.unload_module)(module.0 as *mut c_void)
})
}
pub(crate) fn launch(
&self,
function: FunctionHandle,
grid: u32,
arguments: &mut LaunchArguments,
) -> Result<()> {
// SAFETY: fixed live function/owner context; checked exact shapes,
// nonaliasing output and grid; six fixed dimensions + sharedBytes;
// null stream/extra. Four pointer entries address initialized typed
// boxed values, NOT device addresses interpreted as host pointers.
// Caller keeps the entire box/table alive through mandatory sync,
// and retains it permanently on ambiguous completion.
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<()> {
@@ -252,6 +385,26 @@ impl Api {
Err(Error::Disabled)
}
}
pub(crate) fn load_fixed_module(&self) -> Result<ModuleHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn fixed_function(&self, module: ModuleHandle) -> Result<FunctionHandle> {
let _ = module.0;
Err(Error::UnsupportedPlatform)
}
pub(crate) fn unload(&self, module: ModuleHandle) -> Result<()> {
let _ = module.0;
Err(Error::UnsupportedPlatform)
}
pub(crate) fn launch(
&self,
function: FunctionHandle,
_: u32,
arguments: &mut LaunchArguments,
) -> 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)
+146 -2
View File
@@ -26,6 +26,9 @@ pub enum Error {
operation: &'static str,
code: i32,
},
ContextMismatch,
InvalidVectorShape,
OutputAliasesInput,
InvalidOrdinal,
InvalidSize,
BudgetExceeded,
@@ -57,6 +60,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"),
@@ -153,6 +163,7 @@ impl<'driver> Device<'driver> {
budget: byte_budget,
allocated: Cell::new(0),
poisoned: Cell::new(false),
kernel: Cell::new(None),
})
}
}
@@ -164,6 +175,31 @@ pub struct Context<'driver> {
budget: usize,
allocated: Cell<usize>,
poisoned: Cell<bool>,
kernel: Cell<Option<FixedKernel>>,
}
#[derive(Clone, Copy)]
struct FixedKernel {
module: ffi::ModuleHandle,
function: ffi::FunctionHandle,
}
// 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) {
return Err(Error::InvalidVectorShape);
}
let count = u32::try_from(bytes / 4).map_err(|_| Error::InvalidVectorShape)?;
let grid = u64::from(count)
.checked_add(127)
.ok_or(Error::InvalidVectorShape)?
/ 128;
if grid == 0 || grid > i32::MAX as u64 {
return Err(Error::InvalidVectorShape);
}
Ok((
count,
u32::try_from(grid).map_err(|_| Error::InvalidVectorShape)?,
))
}
impl Context<'_> {
pub fn budget_bytes(&self) -> usize {
@@ -217,12 +253,106 @@ impl Context<'_> {
}
combine(sync, guard.finish())
}
/// Add two exact f32 byte vectors with the fixed trusted kernel. The
/// output is usable as a computed vector only after a successful return.
pub fn vector_add_f32(
&self,
a: &DeviceBuffer<'_>,
b: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
if self.poisoned.get() {
return Err(Error::ContextPoisoned);
}
if !std::ptr::eq(self, a.context)
|| !std::ptr::eq(self, b.context)
|| !std::ptr::eq(self, output.context)
{
return Err(Error::ContextMismatch);
}
let (count, grid) = vector_shape(a.bytes)?;
if a.bytes != b.bytes || a.bytes != output.bytes {
return Err(Error::InvalidVectorShape);
}
let a_handle = a.handle.ok_or(Error::ContextPoisoned)?;
let b_handle = b.handle.ok_or(Error::ContextPoisoned)?;
let out_handle = output.handle.ok_or(Error::ContextPoisoned)?;
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);
let guard = self.enter()?;
let kernel = match self.fixed_kernel() {
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())
}
fn fixed_kernel(&self) -> Result<FixedKernel> {
if let Some(kernel) = self.kernel.get() {
return Ok(kernel);
}
let module = self.driver.api.load_fixed_module()?;
match self.driver.api.fixed_function(module) {
Ok(function) => {
let kernel = FixedKernel { module, function };
self.kernel.set(Some(kernel));
Ok(kernel)
}
Err(error) => {
// Local usable handle consumed by this single unload attempt;
// no cache publishes a partial module or retries failed unload.
let cleanup = self.driver.api.unload(module);
if cleanup.is_err() {
self.poisoned.set(true);
}
combine(Err(error), cleanup)
}
}
}
fn unload_kernel(&self) -> Result<()> {
// Consume BEFORE attempting unload; even an error can invalidate it.
let Some(kernel) = self.kernel.take() else {
return Ok(());
};
if self.poisoned.get() {
return Ok(());
}
let guard = match self.enter() {
Ok(guard) => guard,
Err(error) => {
self.poisoned.set(true);
return Err(error);
}
};
let unload = self.driver.api.unload(kernel.module);
if unload.is_err() {
self.poisoned.set(true);
}
combine(unload, guard.finish())
}
/// Consume the context and report destruction failure. Borrows prevent
/// closing a context while a device buffer can still be used.
pub fn close(mut self) -> Result<()> {
self.destroy()
}
fn destroy(&mut self) -> Result<()> {
let unload = self.unload_kernel();
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.
@@ -233,9 +363,9 @@ impl Context<'_> {
if result.is_ok() {
self.allocated.set(0);
}
result
combine(unload, result)
} else {
Ok(())
unload
}
}
}
@@ -381,6 +511,20 @@ mod tests {
})
);
}
#[test]
fn vector_count_geometry_boundaries() {
for bytes in [0, 1, 3, 5, usize::MAX] {
assert!(vector_shape(bytes).is_err());
}
for n in [1u32, 127, 128, 129, 1025, u32::MAX] {
let bytes = usize::try_from(u64::from(n) * 4).unwrap();
assert_eq!(
vector_shape(bytes),
Ok((n, u32::try_from(u64::from(n).div_ceil(128)).unwrap()))
);
}
assert!(vector_shape((u32::MAX as usize + 1) * 4).is_err());
}
#[cfg(not(feature = "cuda-driver"))]
#[test]
fn default_load_rejects_before_driver_use() {
+41
View File
@@ -0,0 +1,41 @@
// Trusted fixed operation; byte image is embedded with a final NUL by ffi.rs.
.version 7.0
.target sm_75
.address_size 64
.visible .entry leleka_vector_add_f32(
.param .u64 input_a,
.param .u64 input_b,
.param .u64 output,
.param .u32 count
)
{
.reg .pred %p;
.reg .b32 %r<3>;
.reg .b64 %rd<8>;
.reg .f32 %f<3>;
ld.param.u64 %rd0, [input_a];
ld.param.u64 %rd1, [input_b];
ld.param.u64 %rd2, [output];
ld.param.u32 %r2, [count];
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 %p, %rd3, %rd4;
@%p bra DONE;
shl.b64 %rd4, %rd3, 2;
add.u64 %rd5, %rd0, %rd4;
add.u64 %rd6, %rd1, %rd4;
add.u64 %rd7, %rd2, %rd4;
ld.global.f32 %f0, [%rd5];
ld.global.f32 %f1, [%rd6];
add.rn.f32 %f2, %f0, %f1;
st.global.f32 [%rd7], %f2;
DONE:
ret;
}
+84 -15
View File
@@ -11,16 +11,24 @@ typedef int CUresult;
static CUcontext current=(void *)(uintptr_t)0x11;
static CUcontext stack[64];
static size_t depth;
static const CUcontext owned=(void *)(uintptr_t)0x22;
static CUcontext contexts[16];
static size_t next_context;
static int context_live(CUcontext ctx){for(size_t i=0;i<16;i++)if(contexts[i]==ctx&&ctx)return 1;return 0;}
static int live_context;
static unsigned failed_mask;
static struct {void *ptr;size_t size;} buffers[16];
static struct {void *raw,*ptr;size_t size;CUcontext owner;} buffers[16];
static struct {void *handle,*function;CUcontext owner;} modules[16];
static size_t next_module;
static void **pending_args;
static uint64_t pending_values[3];
static uint32_t pending_n;
static CUcontext pending_owner;
static const void *pending_host;
static void *pending_device;
static size_t pending_bytes;
static void *pending_destination;
static unsigned calls[16];
static const char *names[]={"init","version","device","create","destroy","push","pop","sync","alloc","free","htod","dtoh"};
static const char *names[]={"init","version","device","create","destroy","push","pop","sync","alloc","free","htod","dtoh","load","lookup","unload","launch"};
static size_t charged(void) {size_t result=0;for(size_t i=0;i<16;i++)result+=buffers[i].size;return result;}
static void trace(const char *stage,int code,size_t bytes) {
const char *path=getenv("MOCK_CUDA_TRACE");if(!path)abort();
@@ -41,19 +49,33 @@ static int fault(int op) {
}
return 0;
}
static void check_canary(size_t i) {
unsigned char *raw=buffers[i].raw;
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 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];
trace("pending_launch",0,pending_n);
pending_args=NULL;pending_n=0;
}
for(size_t i=0;i<16;i++)check_canary(i);
if(pending_host&&pending_device){
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?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);}
pending_host=NULL;pending_device=NULL;pending_destination=NULL;pending_bytes=0;
}
static int require_context(void) {return current==owned&&live_context?0:201;}
static int require_context(void) {return context_live(current)?0:201;}
static void *lookup(CUdeviceptr ptr,size_t count) {
for(size_t i=0;i<16;i++)if((CUdeviceptr)(uintptr_t)buffers[i].ptr==ptr&&count==buffers[i].size)return buffers[i].ptr;
for(size_t i=0;i<16;i++)if((CUdeviceptr)(uintptr_t)buffers[i].ptr==ptr&&count==buffers[i].size&&buffers[i].owner==current)return buffers[i].ptr;
return NULL;
}
CUresult cuInit(unsigned flags) {if(flags)return 1;if(fault(0))return 700;trace("init",0,0);return 0;}
@@ -61,18 +83,22 @@ CUresult cuDriverGetVersion(int *version) {if(fault(1))return 700;*version=13000
CUresult cuDeviceGet(int *device,int ordinal) {if(fault(2))return 700;if(ordinal!=0)return 101;*device=0;trace("device",0,0);return 0;}
CUresult cuCtxCreate_v2(CUcontext *result,unsigned flags,int device) {
if(flags||device)return 1;if(fault(3))return 700;
stack[depth++]=current;current=owned;live_context=1;*result=owned;trace("create",0,0);return 0;
if(next_context>=16)return 2;
CUcontext owned=(void *)(uintptr_t)(0x22+next_context);contexts[next_context++]=owned;
stack[depth++]=current;current=owned;live_context++;*result=owned;trace("create",0,0);return 0;
}
CUresult cuCtxDestroy_v2(CUcontext ctx) {
if(fault(4))return 700;if(ctx!=owned||!live_context)return 201;
if(fault(4))return 700;if(!context_live(ctx))return 201;
/* Read retained pending source before disposing it: a delayed HtoD host borrow. */
complete_pending();
for(size_t i=0;i<16;i++){free(buffers[i].ptr);buffers[i].ptr=NULL;buffers[i].size=0;}
live_context=0;if(current==owned)current=(void *)(uintptr_t)0x11;
if(pending_args&&pending_owner!=ctx)abort();complete_pending();
for(size_t i=0;i<16;i++)if(buffers[i].owner==ctx){free(buffers[i].raw);memset(&buffers[i],0,sizeof(buffers[i]));}
for(size_t i=0;i<16;i++)if(modules[i].owner==ctx)memset(&modules[i],0,sizeof(modules[i]));
for(size_t i=0;i<16;i++)if(contexts[i]==ctx)contexts[i]=NULL;
live_context--;if(current==ctx)current=depth?stack[--depth]:(void *)(uintptr_t)0x11;
trace("destroy",0,0);return 0;
}
CUresult cuCtxPushCurrent_v2(CUcontext ctx) {
if(fault(5))return 700;if(ctx!=owned||!live_context||depth>=64)return 201;
if(fault(5))return 700;if(!context_live(ctx)||depth>=64)return 201;
stack[depth++]=current;current=ctx;trace("push",0,0);return 0;
}
CUresult cuCtxPopCurrent_v2(CUcontext *result) {
@@ -87,13 +113,13 @@ CUresult cuCtxSynchronize(void) {
complete_pending();trace("sync",0,0);return 0;
}
CUresult cuMemAlloc_v2(CUdeviceptr *ptr,size_t bytes) {
if(fault(8))return 700;if(require_context()||!bytes||bytes>1024)return 201;
for(size_t i=0;i<16;i++)if(!buffers[i].ptr){buffers[i].ptr=calloc(1,bytes);buffers[i].size=bytes;*ptr=(CUdeviceptr)(uintptr_t)buffers[i].ptr;trace("alloc",0,bytes);return 0;}
if(fault(8))return 700;if(require_context()||!bytes||bytes>16384)return 201;
for(size_t i=0;i<16;i++)if(!buffers[i].ptr){buffers[i].raw=calloc(1,bytes+16);if(!buffers[i].raw)return 2;memset(buffers[i].raw,0xa5,8);memset((unsigned char*)buffers[i].raw+8+bytes,0xa5,8);buffers[i].ptr=(unsigned char*)buffers[i].raw+8;buffers[i].size=bytes;buffers[i].owner=current;*ptr=(CUdeviceptr)(uintptr_t)buffers[i].ptr;trace("alloc",0,bytes);return 0;}
return 2;
}
CUresult cuMemFree_v2(CUdeviceptr ptr) {
if(fault(9))return 700;if(require_context())return 201;
for(size_t i=0;i<16;i++)if((CUdeviceptr)(uintptr_t)buffers[i].ptr==ptr){if(pending_device==buffers[i].ptr){trace("unsafe_pending_free",0,0);pending_device=NULL;pending_host=NULL;pending_destination=NULL;pending_bytes=0;}free(buffers[i].ptr);buffers[i].ptr=NULL;buffers[i].size=0;trace("free",0,0);return 0;}
for(size_t i=0;i<16;i++)if((CUdeviceptr)(uintptr_t)buffers[i].ptr==ptr){if(pending_args){trace("unsafe_pending_free",0,0);abort();}check_canary(i);if(pending_device==buffers[i].ptr){trace("unsafe_pending_free",0,0);pending_device=NULL;pending_host=NULL;pending_destination=NULL;pending_bytes=0;}free(buffers[i].raw);memset(&buffers[i],0,sizeof(buffers[i]));trace("free",0,0);return 0;}
return 1;
}
CUresult cuMemcpyHtoD_v2(CUdeviceptr ptr,const void *host,size_t bytes) {
@@ -107,3 +133,46 @@ CUresult cuMemcpyDtoH_v2(void *host,CUdeviceptr ptr,size_t bytes) {
pending_destination=host;pending_device=lookup(ptr,bytes);pending_bytes=bytes;trace("dtoh",0,bytes);return 0;
}
#endif
/* Independent fixed vector ABI fixture. Arithmetic here is a CPU reference;
it neither interprets nor executes PTX. */
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(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;
}
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(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;}
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;}
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) {
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;
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);
if(fault(15))return 700;trace("launch",0,n);return 0;
}
+337 -1
View File
@@ -103,6 +103,34 @@ fn isolated_cpu_elf_matrix() {
"dtoh_sync",
"free",
"destroy",
"missing_cuModuleLoadData",
"missing_cuModuleGetFunction",
"missing_cuModuleUnload",
"missing_cuLaunchKernel",
"vector_1",
"vector_127",
"vector_128",
"vector_129",
"vector_1025",
"vector_cache",
"vector_contexts",
"vector_bounds",
"vector_same_input",
"vector_load",
"vector_lookup",
"vector_null_load",
"vector_null_function",
"vector_launch",
"vector_sync",
"vector_launch_sync",
"vector_launch_sync_pop",
"vector_pop",
"vector_wrong_pop",
"vector_unload",
"vector_lookup_unload",
"vector_close_pop",
"vector_close_destroy",
"vector_push",
];
for scenario in scenarios {
let path = root.join(format!("trace-{scenario}"));
@@ -112,7 +140,13 @@ fn isolated_cpu_elf_matrix() {
.env("LELEKA_CUDA_CASE", scenario)
.env("MOCK_CUDA_TRACE", &path)
.env_remove("MOCK_CUDA_FAIL")
.env_remove("MOCK_CUDA_WRONG_POP");
.env_remove("MOCK_CUDA_WRONG_POP")
.env_remove("MOCK_CUDA_NULL_LOAD")
.env_remove("MOCK_CUDA_NULL_FUNCTION")
.env_remove("MOCK_CUDA_VECTOR");
if scenario.starts_with("vector_") {
command.env("MOCK_CUDA_VECTOR", "1");
}
command.env(
"LD_LIBRARY_PATH",
root.join(if scenario.starts_with("missing") {
@@ -122,6 +156,19 @@ fn isolated_cpu_elf_matrix() {
}),
);
let failure = match scenario {
"vector_load" => Some("load"),
"vector_lookup" => Some("lookup"),
"vector_launch" => Some("launch"),
"vector_sync" => Some("sync:3"),
"vector_launch_sync" => Some("launch,sync:3"),
"vector_launch_sync_pop" => Some("launch,sync:3,pop:7"),
"vector_pop" => Some("pop:7"),
"vector_unload" => Some("unload"),
"vector_lookup_unload" => Some("lookup,unload"),
"vector_close_pop" => Some("pop:14"),
"vector_close_destroy" => Some("destroy"),
"vector_push" => Some("push:6"),
other if other.starts_with("vector_") => None,
"create_pop" => Some("pop"),
"pop" => Some("pop:2"),
"sync_htod" => Some("sync"),
@@ -141,6 +188,15 @@ fn isolated_cpu_elf_matrix() {
if scenario == "wrong_pop" { "1" } else { "2" },
);
}
if scenario == "vector_wrong_pop" {
command.env("MOCK_CUDA_WRONG_POP", "7");
}
if scenario == "vector_null_load" {
command.env("MOCK_CUDA_NULL_LOAD", "1");
}
if scenario == "vector_null_function" {
command.env("MOCK_CUDA_NULL_FUNCTION", "1");
}
let output = command.output().unwrap();
assert!(
output.status.success(),
@@ -157,6 +213,10 @@ fn isolated_cpu_elf_matrix() {
fn fixture_child() {
assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").unwrap(), "1");
let case = std::env::var("LELEKA_CUDA_CASE").unwrap();
if case.starts_with("vector_") {
vector_child(&case);
return;
}
if case.starts_with("missing") || ["init", "version"].contains(&case.as_str()) {
let error = Driver::load()
.err()
@@ -379,3 +439,279 @@ fn fixture_child() {
assert_eq!(destroyed.current, 0x11);
}
}
// Expected values and geometry are derived from FR-VADD-1..5 and the NVIDIA
// launch ABI, independent of the wrapper/PTX implementation. CPU mock results
// are host dataflow/ownership evidence only.
fn vector_child(case: &str) {
use leleka_cuda_driver::Error;
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let count = case
.strip_prefix("vector_")
.unwrap()
.parse::<usize>()
.unwrap_or(129);
let bytes = count * 4;
let context = device.create_context(bytes * 4 + 16).unwrap();
let mut a = context.allocate(bytes).unwrap();
let mut b = context.allocate(bytes).unwrap();
let mut out = context.allocate(bytes).unwrap();
let av: Vec<f32> = (0..count)
.map(|i| (i as i32 % 31 - 15) as f32 * 0.5)
.collect();
let bv: Vec<f32> = (0..count)
.map(|i| (i as i32 % 23 - 11) as f32 * 0.25)
.collect();
let encode = |v: &[f32]| {
v.iter()
.flat_map(|value| value.to_ne_bytes())
.collect::<Vec<u8>>()
};
a.copy_from(&encode(&av)).unwrap();
b.copy_from(&encode(&bv)).unwrap();
if case == "vector_bounds" {
let foreign = device.create_context(bytes * 3).unwrap();
let foreign_input = foreign.allocate(bytes).unwrap();
let short = context.allocate(4).unwrap();
let odd = context.allocate(3).unwrap();
let mut odd_out = context.allocate(3).unwrap();
let before = trace().len();
assert!(matches!(
context.vector_add_f32(&foreign_input, &b, &mut out),
Err(Error::ContextMismatch)
));
assert!(context.vector_add_f32(&a, &short, &mut out).is_err());
assert!(context.vector_add_f32(&odd, &odd, &mut odd_out).is_err());
assert_eq!(trace().len(), before, "validation before ABI mutation");
drop((foreign_input, short, odd, odd_out));
foreign.close().unwrap();
}
let result = if case == "vector_same_input" {
context.vector_add_f32(&a, &a, &mut out)
} else {
context.vector_add_f32(&a, &b, &mut out)
};
let execution_failure = [
"vector_load",
"vector_lookup",
"vector_null_load",
"vector_null_function",
"vector_launch",
"vector_sync",
"vector_launch_sync",
"vector_launch_sync_pop",
"vector_pop",
"vector_wrong_pop",
"vector_lookup_unload",
"vector_push",
]
.contains(&case);
if execution_failure {
let error = result.unwrap_err();
let expected = match case {
"vector_load" => vec![("cuModuleLoadData", 700)],
"vector_lookup" => vec![("cuModuleGetFunction", 700)],
"vector_lookup_unload" => vec![("cuModuleGetFunction", 700), ("cuModuleUnload", 700)],
"vector_launch" => vec![("cuLaunchKernel", 700)],
"vector_sync" => vec![("cuCtxSynchronize", 700)],
"vector_launch_sync" => vec![("cuLaunchKernel", 700), ("cuCtxSynchronize", 700)],
"vector_launch_sync_pop" => vec![
("cuLaunchKernel", 700),
("cuCtxSynchronize", 700),
("cuCtxPopCurrent_v2", 700),
],
"vector_pop" => vec![("cuCtxPopCurrent_v2", 700)],
"vector_push" => vec![("cuCtxPushCurrent_v2", 700)],
_ => vec![],
};
assert_eq!(cuda_errors(&error), expected);
if case == "vector_null_load" {
assert!(matches!(
error,
Error::InvalidDriverValue("cuModuleLoadData")
));
}
if case == "vector_null_function" {
assert!(matches!(
error,
Error::InvalidDriverValue("cuModuleGetFunction")
));
}
if case == "vector_wrong_pop" {
assert_eq!(error, Error::UnexpectedContext);
}
if [
"vector_sync",
"vector_launch_sync",
"vector_launch_sync_pop",
"vector_pop",
"vector_wrong_pop",
"vector_lookup_unload",
]
.contains(&case)
{
let before = trace().len();
assert!(context.vector_add_f32(&a, &b, &mut out).is_err());
assert!(context.allocate(4).is_err());
assert!(a.copy_from(&encode(&av)).is_err());
assert!(context.synchronize().is_err());
assert_eq!(trace().len(), before, "poison admits zero native work");
// Encourage allocator reuse before containment reads pending args.
let churn: Vec<_> = (0..1024).map(|_| Box::new([0xdeadbeefu64; 8])).collect();
std::hint::black_box(churn);
}
} else {
result.unwrap();
if case == "vector_cache" {
context.vector_add_f32(&a, &b, &mut out).unwrap();
}
let mut output = vec![0; bytes];
out.copy_to(&mut output).unwrap();
let expected: Vec<_> = av
.iter()
.zip(if case == "vector_same_input" {
&av
} else {
&bv
})
.map(|(a, b)| (a + b).to_bits())
.collect();
let actual: Vec<_> = output
.as_chunks::<4>()
.0
.iter()
.map(|v| u32::from_ne_bytes(*v))
.collect();
assert_eq!(actual, expected, "independent exact finite f32 reference");
let mut unchanged = vec![0; bytes];
a.copy_to(&mut unchanged).unwrap();
assert_eq!(unchanged, encode(&av));
b.copy_to(&mut unchanged).unwrap();
assert_eq!(unchanged, encode(&bv));
if case == "vector_contexts" {
let second = device.create_context(bytes * 3).unwrap();
let mut x = second.allocate(bytes).unwrap();
let mut y = second.allocate(bytes).unwrap();
let mut z = second.allocate(bytes).unwrap();
x.copy_from(&encode(&av)).unwrap();
y.copy_from(&encode(&bv)).unwrap();
second.vector_add_f32(&x, &y, &mut z).unwrap();
z.copy_to(&mut output).unwrap();
assert_eq!(
output,
encode(&av.iter().zip(&bv).map(|(a, b)| a + b).collect::<Vec<_>>())
);
drop((x, y, z));
second.close().unwrap();
}
}
drop((a, b, out));
let closed = context.close();
match case {
"vector_unload" => assert_eq!(
cuda_errors(&closed.unwrap_err()),
vec![("cuModuleUnload", 700)]
),
"vector_close_pop" => assert_eq!(
cuda_errors(&closed.unwrap_err()),
vec![("cuCtxPopCurrent_v2", 700)]
),
"vector_close_destroy" => assert_eq!(
cuda_errors(&closed.unwrap_err()),
vec![("cuCtxDestroy_v2", 700)]
),
_ => closed.unwrap(),
}
let rows = trace();
assert!(!rows.iter().any(|r| {
[
"unsafe_pending_free",
"unsafe_pending_unload",
"stack_arguments",
]
.contains(&r.stage.as_str())
}));
let expected_modules = if case == "vector_contexts" { 2 } else { 1 };
if !["vector_load", "vector_null_load", "vector_push"].contains(&case) {
assert_eq!(
rows.iter()
.filter(|r| r.stage == "load" && r.code == 0)
.count(),
expected_modules
);
}
if !execution_failure {
assert_eq!(
rows.iter()
.filter(|r| r.stage == "lookup" && r.code == 0)
.count(),
expected_modules
);
let launches = if ["vector_cache", "vector_contexts"].contains(&case) {
2
} else {
1
};
assert_eq!(
rows.iter().filter(|r| r.stage == "launch").count(),
launches
);
assert!(
rows.iter()
.filter(|r| r.stage == "geometry")
.all(|r| r.bytes == count.div_ceil(128))
);
assert!(
rows.iter()
.filter(|r| r.stage == "arguments")
.all(|r| r.bytes == count)
);
}
for (i, row) in rows.iter().enumerate().filter(|(_, r)| r.stage == "launch") {
assert!(
rows[i + 1..]
.iter()
.take_while(|r| r.stage != "pop")
.any(|r| r.stage == "sync"),
"mandatory sync after any launch attempt"
);
assert!([0, 700].contains(&row.code));
}
if [
"vector_sync",
"vector_launch_sync",
"vector_launch_sync_pop",
]
.contains(&case)
{
assert_eq!(rows.iter().filter(|r| r.stage == "unload").count(), 0);
assert!(
rows.iter()
.any(|r| r.stage == "pending_launch" && r.bytes == count)
);
}
if ["vector_unload", "vector_lookup_unload"].contains(&case) {
assert_eq!(
rows.iter().filter(|r| r.stage == "unload").count(),
1,
"failed handle consumed once"
);
}
for stage in ["load", "lookup", "unload", "launch"] {
for row in rows.iter().filter(|r| r.stage == stage && r.code == 0) {
assert!([0x22, 0x23].contains(&row.current));
assert_eq!(row.depth, 1);
}
}
if case != "vector_close_destroy" {
let last = rows
.iter()
.rev()
.find(|r| r.stage == "destroy" && r.code == 0)
.unwrap();
assert_eq!(last.current, 0x11);
assert_eq!(last.live, 0);
assert_eq!(last.charged, 0);
}
}
+238
View File
@@ -0,0 +1,238 @@
# Fixed CUDA f32 vector-add requirements
Bounded STRA-102 requirements for plan
`05e21fde-510e-4d63-8aa1-442e67339961`, written before implementation on
base `0383253c6011ec795aa395b613405263f63378ee`.
This unit supplies one opt-in, typed operation over owned CUDA buffers:
`out[i] = add.rn.f32(a[i], b[i])`. A successful return must mean the attempted
launch completed and the caller's previous context was restored. Validation
errs toward refusal before native mutation; uncertain completion or restoration
errs toward poisoning and retaining resources. These properties can support
bounded wrapper/ABI claims after their respective gates; they cannot establish
model support or numerical execution merely from a mock or compilation.
The historical [bootstrap contract](cuda-driver-bootstrap.md) and its actual
12-symbol qualification receipts remain unchanged. This document owns only the
extension below. The charter remains the project goal and quality authority;
this unit advances the independent Rust NVIDIA execution foundation without
changing production serving or the imported Strata engine.
## Scope and caller outcome
An internal engine developer can explicitly enable the `cuda-driver` feature,
load the driver, create a private context, allocate/upload two input buffers and
an output buffer, invoke the fixed add operation and read the completed output.
The safe interface accepts owned buffer references and returns structured errors;
it accepts no PTX, module image, entry name, stream, launch geometry, raw pointer,
foreign context or callback from a caller.
The existing default feature remains off. No new HTTP endpoint, worker switch,
backend/model admission, scheduler, tensor loader, inference implementation or
production deployment integration is included. Deployment of this foundation
must continue to require only the installed NVIDIA driver rather than Strata,
Python, a C compiler or CUDA Toolkit; offline verification tools are separate.
## Requirements and acceptance conditions
### FR-VADD-1 — validate owned shapes before mutation
- Accept two immutable input buffers and one mutable output buffer belonging to
the exact same owned `Context` instance. Equal device ordinals or separate
contexts on the same GPU do not establish ownership equality.
- All three byte lengths must be equal, nonzero and divisible by four; interpret
them as f32 elements. The element count must fit `u32`, byte bounds must retain
the bootstrap's checked budget/`isize` constraints, and grid arithmetic must be
checked without truncation or overflow.
- Preserve safe aliasing: inputs may refer to the same immutable allocation;
output must not alias an input. The public borrow contract must enforce this,
with defensive identity refusal wherever implementation structure permits
otherwise. No unsafe bypass is exposed publicly.
- Reject invalid ownership, shape/count/geometry, unavailable capability and
poisoned contexts before push, module load, lookup or launch. Do not mutate
output or allocation accounting on validation refusal. Do not allocate new
device buffers implicitly for this operation.
### FR-VADD-2 — one trusted module and function
- Embed a bounded, NUL-terminated PTX byte sequence in the crate. It contains
exactly the fixed entry `leleka_vector_add_f32` with parameters in this order:
input A u64 device address, input B u64 device address, output u64 device
address, element count u32. Treat pointers as private ABI values, never public
Rust handles. Record the exact embedded bytes' SHA256 for verification.
- The entry checks `i < n` before any element access; address arithmetic must
not wrap. Every in-range thread reads the corresponding A/B elements and
writes exactly one output element. No input writes, external symbols,
indirect calls, atomics, shared-memory state or out-of-range writes.
- Use explicit `add.rn.f32` without `.ftz`, saturation, approximate arithmetic
or floating-point contraction. No `fma`/`mad` substitutes for the add. The
selected fixed image uses PTX 7.0, `sm_75`, and `.address_size 64`; unsupported
driver/target combinations fail explicitly, not by selecting another kernel.
- Cache at most one successfully loaded module/function per context, lazily
after validation. Repeated successful calls reuse it. Publish a cache entry
only after both load and function lookup succeeded with valid non-null
handles. Failed initialization must not create a usable partial cache.
The arithmetic spelling is grounded in NVIDIA's archived
[PTX floating-point add specification](https://docs.nvidia.com/cuda/archive/13.0.1/parallel-thread-execution/index.html#floating-point-instructions-add).
This is the required arithmetic, not evidence that real hardware has executed
it. Signed zeros, subnormal handling, overflow, infinities, NaNs and NaN payload
behavior still require explicit installed-driver numerical qualification.
### FR-VADD-3 — fixed 16-symbol loader and launch ABI
Extend the bootstrap's fixed twelve symbols by precisely these four:
| Symbol | Private C ABI parameters | Return |
| --- | --- | --- |
| `cuModuleLoadData` | `CUmodule*`, `const void*` | `CUresult` |
| `cuModuleGetFunction` | `CUfunction*`, `CUmodule`, `const char*` | `CUresult` |
| `cuModuleUnload` | `CUmodule` | `CUresult` |
| `cuLaunchKernel` | `CUfunction`, six `unsigned int` grid/block dimensions, `unsigned int` shared bytes, `CUstream`, `void** kernelParams`, `void** extra` | `CUresult` |
All sixteen resolve before `cuInit`; each missing extension symbol must fail
before initialization. Keep the legacy bootstrap `_v2` signatures, soname,
library lifetime and platform guards. Opaque module/function/stream pointers
remain inside audited private FFI. The ABI references are NVIDIA's archived
[module management](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/group__CUDA__MODULE.html)
and [execution control](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/group__CUDA__EXEC.html)
documentation. Independent advisory verification checked the official pinned
cudart 13.0.88 archive (1,491,604 bytes, SHA256
`bc44226f069402ab327bcf9e754660621aa6bc61fb7fc6afe03b794dfaaab658`)
and `cuda.h` SHA256
`64025f81a9d6d2b10e9e11654f3523e5b046d01b883f0b9ca474e463274b80d4`.
Header lines 7365/7476/7532 identify load/unload/function lookup; lines
17537–17547 identify launch with seven unsigned-int arguments including shared
bytes. This is header evidence, not an execution result.
Launch one dimension with fixed block size 128, `grid.x = ceil(n / 128)`;
grid/block y and z are one, shared memory is zero, stream is null, `extra` is
null. `kernelParams` is a private four-entry array of pointers to the typed
argument values above. Own the scalar/device-address parameter storage and
pointer table, keeping their addresses stable through launch and synchronization.
If the table references fields of its own storage object, establish those pointers
only after stable heap placement; moving an inline self-referential object must
not invalidate them. NVIDIA's documentation describes copying parameter values
from the supplied regions, but this contract does not infer a stronger
before-return timing guarantee from that wording;
if completion is uncertain, retain any storage the driver could still reference
and poison future work. No caller host pointer or arbitrary argument escapes
into this interface. Compute the grid in a wider
integer and require `grid.x <= i32::MAX`. Kernel index/address arithmetic must
cover the final partial block without u32 overflow or reading beyond `n`.
No caller can alter this launch shape. The driver may still reject this fixed
shape on unsupported hardware; that is a reported operation failure.
### FR-VADD-4 — completion and context restoration
- Push the owned context for module/launch operations and pop it on all paths
after a successful push, checking that the popped handle is the owned one.
Successful operations and handled failures restore the prior caller context;
a failed or mismatched pop reports the failure and poisons this context.
- After **every attempted `cuLaunchKernel`**, synchronize even when launch
returns an error. Retain the launch error and subsequent synchronization/pop
errors in their operation order; cleanup must not replace the original error.
A lookup/load failure before launch is not a launch attempt.
- Return success only after launch, synchronization and restoration all succeed.
Inputs stay immutable; output contents after a native execution failure are
unspecified and must not be reported as a successfully computed vector.
- Synchronization failure means completion is uncertain: poison the context,
reject future allocation/copy/sync/kernel work without further native work,
and keep possibly referenced buffers/module alive until safe context teardown.
Do not free or unload them merely because a failed launch was observed.
- Continue the bootstrap's staged-copy rule, including keeping ambiguous host
DMA staging alive. A fixed kernel must not weaken existing copy/borrow safety.
### FR-VADD-5 — module ownership and failure cleanup
- Module/function cache lifetime is inside its owner context and dynamic-library
lifetime. No public module or function can outlive that context or cross a
thread; retain the existing `!Send`/`!Sync` resource guarantees.
- On function lookup failure after module load, attempt unload in the owned
current context. Consume the module's usable-handle slot before calling unload,
regardless of its return value; unload at most once per handle. A failed
unload poisons the context. Retain only context-owned residual/accounting for
final destruction: never retry unload, reuse the handle or reinitialize a
healthy cache after that failure. If restoration is uncertain, likewise
report all relevant errors and forbid treating the module as a valid kernel.
- Healthy teardown unloads the cached module after completed work, in the owned
context, before destroying the context. Pending/uncertain work must not be
followed by explicit module unload or buffer free. Context destruction is the
final containment attempt; permanent driver failures cannot be called cleaned.
- Explicit fallible close reports unload/restoration/destruction failures;
destruction should still be attempted when safe. Drop remains best effort
and nonpanicking. Failed destroy retains the library as required by the
bootstrap rather than permitting calls through an unloaded library.
- No automatic retries of a failed launch. Repeated poisoned contexts can
retain resources; this unit supplies no process-wide recovery or cumulative
resource bound and must not advertise a leak-free serving guarantee.
## Security and non-functional contract
| Dimension | Metric / threshold | Planned verification |
| --- | --- | --- |
| Critical usability | One typed add action; structured errors, no raw pointer/module interface | Public API review and synthetic caller |
| Reliability | Success requires launch + completion + restoration; zero silent launch retries | Fault matrix and trace order |
| Performance | No speed/SLO assertion; one launch and one mandatory completion sync per valid call | ABI trace, separate future paired benchmark |
| Capacity | One cached module/context; fixed block128; checked count/grid and existing byte budget | Boundary/refusal and repeated-call tests |
| Security / isolation | Exact context ownership, private fixed PTX/entry, no safe arbitrary execution surface | Cross-context/alias/ABI review and compile refusals |
| Audit / retention | Only owned synthetic traces; no model/request/credentials in Git; private evidence outside source | Harness output and cleanup review |
| Observability | Fixed operation names, driver codes, ordered primary/cleanup errors; no pointers or PTX dumps in error text | Fault assertions and error-text inspection |
| Accessibility / i18n | No UI is introduced; existing user interfaces/locales remain unchanged | Changed-surface review |
| Rate / admission | One synchronous call on the creating thread; existing per-context memory budget; no new network/tenant admission | Thread/lifetime gates and budget refusals |
| Deploy / rollback | Default feature off, no serving consumer, no deployment-tool dependency added; disable opt-in to return to existing path | Feature/default/dependency/consumer review |
| Support | Load/lookup/launch/completion/cleanup failures remain diagnosable; no production support SLA is claimed | Error matrix and documented residuals |
| AI dependence | This fixed arithmetic operation performs no model call; no AI output or quality gate substituted by it | Consumer/source review |
| Integrity | Inputs unchanged; output published as success only for completed add; no hidden persistent state except bounded cache | Synthetic data/canaries and cache traces |
| Backup / recovery | No durable data introduced; failed driver teardown is reported/retained, not treated as recovery | Fault/ownership review |
| Privacy | Only sanitized synthetic vectors permitted in this unit's verification | Fixture and artifact review |
| Maintainability | Four additional exact symbols, one embedded module/entry, no new normal dependency | Source/ABI/dependency review |
| Compatibility | Linux 64-bit opt-in only; legacy12 bindings and existing33 mock/10 compile guards preserved | Default/platform and regression gates |
| Cost / efficiency | CPU mock/tooling work only for this delivery; no GPU/probe/model access, no duplicated CI | Recorded commands and container guards |
## Verification plan — outcomes not yet measured
The planned instruments derive from the requirements and official ABI, rather
than obtaining expected outputs from the wrapper implementation. A synthetic
mock can witness argument/context/cleanup behavior and expected fixture data;
it does not execute or establish correctness of the embedded PTX instructions.
| Gate | Required checks / predicted refusal | Claim licensed by a pass |
| --- | --- | --- |
| Existing regression | Retain all 33 bootstrap mock cases and 10 compile refusals, default-denial units, enabled FFI format/Clippy | Existing contract still holds against changed source |
| Missing extension symbols | Independently omit each of four new symbols; zero `cuInit` and resource mutation | Fixed16 pre-initialization admission |
| Typed validation | Different contexts on same device; unequal/nonmultiple4/empty shapes; count/grid overflow; invalid output alias; poisoned context. All refuse before push/load/launch | Bounded safe wrapper admission |
| ABI and synthetic data | Verify exact trusted PTX/entry identity, parameter order/width/value and live owned device allocations, fixed dimensions/null stream/null extra, context sentinel, input immutability/output/canaries | Mocked host ABI/dataflow only |
| Launch bounds | Counts 1,127,128,129 and a bounded larger nonmultiple128 vector; checked maximum/count-overflow tests without giant allocations | Shape/tail guard contract, not real GPU memory safety |
| Cache/lifetime | First valid call loads/looks up once; next call reuses; independent contexts own separate caches; zero unload with pending work; healthy unload before destroy | Bounded cache and resource ordering |
| Faults | Load/lookup/null-success handles/push/launch/sync/pop/wrong-pop/unload/destroy, plus launch+sync and lookup+unload errors; failed unload consumed once, no retry/reuse/cache reinitialization | Original errors retained, cleanup attempts, poison/refusal behavior |
| Delayed completion | Mock defers add completion to sync, including dereferencing retained parameter storage; failed sync leaves work pending until containment; no early argument release/buffer free/module unload; caller output never presented as successful after failure | Declared containment behavior alongside source review |
| Ownership compile gates | Existing driver/context/buffer borrow and thread refusals remain; no safe arbitrary module/function/pointer escape | Rust safe API lifetime/thread surface |
| Offline PTX assembly | GPU-hidden Linux CPU Docker with pinned `ptxas`; exact PTX SHA, tool/version/container target and flags; no devices, installed driver calls or user data | PTX assembler acceptance for the recorded target only |
| Installed-driver numerical execution | Separate authorized real-GPU gate: independent f32 reference; declare finite tolerance before execution (target exact finite bits), signed zeros/subnormal/overflow/Inf/NaN cases with NaN classification/payload limits | Only the executed hardware/driver numerical scope |
| Model / protocol / throughput | Separate Qwen and two named MoE integration, real quality/protocol gates, same-workload paired distributions/provenance | Whole-engine claims only after their own evidence |
Record actual argv, source/commit and embedded PTX hashes, toolchain, architecture,
image/ELF identity, environment/guards, exact test counts, failures and exit codes.
Keep generated evidence private outside Git, remove owned disposable resources,
and report cleanup failures. No number in the planned matrix is a measured pass.
## Remaining platform and qualification boundaries
GNU/Linux 64-bit CPU mock/assembly results do not qualify the existing static
musl executable for `dlopen(libcuda.so.1)`. Its loader integration remains open,
as described in the historical bootstrap contract. PTX loading may require the
installed driver to JIT the fixed image; driver/JIT compatibility is unqualified
until a separate real-driver gate. No Toolkit becomes a deployment prerequisite
merely because offline assembly is used for validation.
No real GPU allocation, kernel execution, model support, quality, protocol
completion, rollback or performance is established by this requirements unit.
The autonomous engine parent and its dependent intake/delivery items remain
open under root coordination. No admission/closure flags are changed here.
No active host-local `.leasevibe.yaml` pointer was supplied; it was absent in
the worktree and canonical repository. Task-relevant host settings are therefore
unavailable, not inferred. The explicit session restrictions remain binding:
Gitea only for future publication/CI, no merge, no active Qwen/runtime changes,
no GPU/model/user-data probes. This BA unit changes only this requirements file.
+11 -2
View File
@@ -25,7 +25,7 @@ if [[ "${1:-}" == --inside ]]; then
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -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; do
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 \
"-D${symbol}=mock_replaced_${symbol}" "${repo_root}/crates/cuda-driver/tests/mock_cuda.c" \
@@ -35,6 +35,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/tests/mock_cuda.c" "${repo_root}/crates/cuda-driver/tests/mock_driver.rs"
rustup component list --installed
rustc --version
@@ -77,6 +78,14 @@ RS
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'context lifetime escaped' >&2; exit 1; fi
grep -q 'cannot move out of.*context.*because it is borrowed' "$work/reject.log"
echo 'two lifetime compile refusals: 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.vector_add_f32(&buffer,&buffer,&mut buffer).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 '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'
cargo tree --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --edges normal
exit 0
fi
@@ -148,7 +157,7 @@ docker start -a "$setup_container"
fixture_image="$(docker commit "$setup_container")"
docker rm "$setup_container" >/dev/null
setup_container=''
docker image inspect "$fixture_image" --format 'Actual CPU fixture image {{.Id}} architecture={{.Architecture}}'
docker image inspect "$fixture_image" --format 'Actual CPU fixture image {{.Id}} architecture={{.Architecture}}'
container="$(docker create --runtime runc --user 65532:65532 --cap-drop ALL \
--security-opt no-new-privileges --network none --memory 1536m --cpus 2 --pids-limit 128 \
--tmpfs /tmp:rw,nosuid,exec,size=768m "$fixture_image" sleep 900)"
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env bash
# Offline assembly acceptance only; no installed driver, GPU, or PTX execution.
set -euo pipefail
[[ $# == 0 ]] || { echo 'Usage: scripts/test-cuda-fixed-ptx.sh' >&2; exit 2; }
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
image='ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b'
work="$(mktemp -d "${TMPDIR:-/tmp}/leleka-fixed-ptx.XXXXXX")"
container=''
cleanup() {
local result=$? failed=0
set +e
if [[ -n "$container" ]]; then docker rm -f "$container" >/dev/null || failed=1; fi
rm -rf "$work" || failed=1
if [[ "$failed" == 1 ]]; then echo 'PTX owned cleanup failed' >&2; result=1; else echo 'PTX owned container/files removed; shared base retained'; fi
exit "$result"
}
trap cleanup EXIT
python3 - "$repo_root" "$work" <<'PY'
import hashlib, json, pathlib, 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')
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())
PY
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 \
--cap-drop ALL --security-opt no-new-privileges --network none --read-only \
--memory 768m --cpus 2 --pids-limit 64 --tmpfs /tmp:rw,nosuid,exec,size=128m \
"$image" sleep 900)"
configuration="$(docker inspect "$container" --format '{{.HostConfig.NetworkMode}}|{{.HostConfig.Runtime}}|{{.HostConfig.Privileged}}|{{.Config.User}}|{{len .HostConfig.Devices}}|{{len .HostConfig.DeviceRequests}}|{{len .HostConfig.Binds}}|{{.HostConfig.CapDrop}}|{{.HostConfig.SecurityOpt}}')"
[[ "$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"
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)"
'