WIP: STRA-102 independent CUDA Driver context and buffers #13

Closed
admin wants to merge 2 commits from codex/stra102-cuda-driver-bootstrap into codex/stra102-rust-iq2s-iq3xxs
11 changed files with 1543 additions and 2 deletions
+1 -1
View File
@@ -33,7 +33,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Install build tools
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake ninja-build g++ python3-numpy
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake ninja-build g++ python3-numpy docker.io
- name: Install pinned Rust
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
- name: Local checks
Generated
+7
View File
@@ -1007,6 +1007,13 @@ dependencies = [
name = "leleka-backend-api"
version = "0.1.0"
[[package]]
name = "leleka-cuda-driver"
version = "0.1.0"
dependencies = [
"libc",
]
[[package]]
name = "leleka-model-format"
version = "0.1.0"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
resolver = "3"
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "control-plane", "desktop-core"]
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/cuda-driver", "control-plane", "desktop-core"]
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "control-plane", "desktop-core"]
[workspace.package]
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "leleka-cuda-driver"
version = "0.1.0"
description = "Opt-in bounded CUDA Driver context and byte-buffer foundation"
edition.workspace = true
license.workspace = true
rust-version.workspace = true
[features]
default = []
cuda-driver = []
[target.'cfg(all(target_os = "linux", target_pointer_width = "64"))'.dependencies]
libc = "=0.2.190"
# The workspace unsafe forbid remains unchanged. Only private ffi.rs may allow
# unsafe code; all other modules deny it, and unsafe operations require blocks.
[lints.rust]
unsafe_code = "deny"
unsafe_op_in_unsafe_fn = "deny"
[lints.clippy]
all = "warn"
+292
View File
@@ -0,0 +1,292 @@
//! Private audited C ABI boundary. No host or device pointers are exported.
//! Behavior references: CUDA Driver API archive 13.0.1 context management,
//! memory management, and api-sync-behavior.html. Exact create/pointer ABI was
//! checked against the official pinned CUDA 13.0.88 cuda.h (line 25633 declares
//! cuCtxCreate_v2 with THREE arguments; line 90 maps today's cuCtxCreate alias
//! to cuCtxCreate_v4; line 274 defines the 64-bit CUdeviceptr). This header is
//! verification evidence only and is not a production dependency. Do not infer
//! a fixed export ABI from the newer alias.
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"
)
)]
pub(crate) struct BufferHandle(u64);
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
mod enabled {
use super::*;
use libc::{c_int, c_uint, c_void};
type CuResult = c_int;
type CuDevice = c_int;
type CuContext = *mut c_void;
type CuDevicePtr = u64;
type Init = unsafe extern "C" fn(c_uint) -> CuResult;
type DriverGetVersion = unsafe extern "C" fn(*mut c_int) -> CuResult;
type DeviceGet = unsafe extern "C" fn(*mut CuDevice, c_int) -> CuResult;
type ContextCreateV2 = unsafe extern "C" fn(*mut CuContext, c_uint, CuDevice) -> CuResult;
type ContextDestroyV2 = unsafe extern "C" fn(CuContext) -> CuResult;
type ContextPushCurrentV2 = unsafe extern "C" fn(CuContext) -> CuResult;
type ContextPopCurrentV2 = unsafe extern "C" fn(*mut CuContext) -> CuResult;
type ContextSynchronize = unsafe extern "C" fn() -> CuResult;
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 MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult;
struct Library(*mut c_void);
impl Drop for Library {
fn drop(&mut self) {
// SAFETY: this is the successful dlopen handle, owned exactly once.
// All loaded functions live in Api alongside this Library. Driver
// owner borrows retain Api through all resource operations/cleanup.
unsafe {
libc::dlclose(self.0);
}
}
}
pub(crate) struct Api {
_library: Library,
init: Init,
version: DriverGetVersion,
device: DeviceGet,
create: ContextCreateV2,
destroy: ContextDestroyV2,
push: ContextPushCurrentV2,
pop: ContextPopCurrentV2,
synchronize: ContextSynchronize,
allocate: MemAllocV2,
free: MemFreeV2,
copy_from: MemcpyHtoDV2,
copy_to: MemcpyDtoHV2,
}
fn check(operation: &'static str, code: CuResult) -> Result<()> {
if code == 0 {
Ok(())
} else {
Err(Error::Driver { operation, code })
}
}
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.
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);
Ok(Self {
_library: library,
init,
version,
device,
create,
destroy,
push,
pop,
synchronize,
allocate,
free,
copy_from,
copy_to,
})
}
pub(crate) fn init(&self) -> Result<()> {
// SAFETY: resolved exact ABI, mandated zero flags, live library.
check("cuInit", unsafe { (self.init)(0) })
}
pub(crate) fn version(&self) -> Result<i32> {
let mut value = 0;
// SAFETY: resolved ABI and valid initialized writable C int.
check("cuDriverGetVersion", unsafe { (self.version)(&mut value) })?;
Ok(value)
}
pub(crate) fn device(&self, ordinal: i32) -> Result<i32> {
let mut value = 0;
// SAFETY: resolved ABI, valid out pointer, ordinal prevalidated.
check("cuDeviceGet", unsafe { (self.device)(&mut value, ordinal) })?;
Ok(value)
}
pub(crate) fn create(&self, device: i32) -> Result<ContextHandle> {
let mut context = std::ptr::null_mut();
// SAFETY: exact legacy v2 THREE-argument ABI, zero flags, a device
// returned by cuDeviceGet, and a valid writable context pointer.
check("cuCtxCreate_v2", unsafe {
(self.create)(&mut context, 0, device)
})?;
if context.is_null() {
return Err(Error::InvalidDriverValue("cuCtxCreate_v2"));
}
Ok(ContextHandle(context as usize))
}
pub(crate) fn destroy(&self, context: ContextHandle) -> Result<()> {
// SAFETY: this handle was created by this Api and remains owned by
// the caller context. No buffer can outlive the borrow owner. This
// API explicitly supports destroying a non-current owned context.
check("cuCtxDestroy_v2", unsafe {
(self.destroy)(context.0 as CuContext)
})
}
pub(crate) fn push(&self, context: ContextHandle) -> Result<()> {
// SAFETY: live private context, same creating thread (Rc owners).
check("cuCtxPushCurrent_v2", unsafe {
(self.push)(context.0 as CuContext)
})
}
pub(crate) fn pop(&self) -> Result<ContextHandle> {
let mut context = std::ptr::null_mut();
// SAFETY: called after successful create/push on the same thread,
// valid out pointer. Callers verify identity and poison on failure.
check("cuCtxPopCurrent_v2", unsafe { (self.pop)(&mut context) })?;
Ok(ContextHandle(context as usize))
}
pub(crate) fn synchronize(&self) -> Result<()> {
// SAFETY: caller guard makes its live owned context current.
check("cuCtxSynchronize", unsafe { (self.synchronize)() })
}
pub(crate) fn allocate(&self, bytes: usize) -> Result<BufferHandle> {
let mut ptr = 0;
// SAFETY: current-context guard; nonzero, bounded size validated
// before mutation; valid u64 CUdeviceptr output on Linux64.
check("cuMemAlloc_v2", unsafe { (self.allocate)(&mut ptr, bytes) })?;
if ptr == 0 {
return Err(Error::InvalidDriverValue("cuMemAlloc_v2"));
}
Ok(BufferHandle(ptr))
}
pub(crate) fn free(&self, buffer: BufferHandle) -> Result<()> {
// SAFETY: uniquely owned allocation, owner context is current.
// Poisoned/uncertain contexts never enter this operation.
check("cuMemFree_v2", unsafe { (self.free)(buffer.0) })
}
pub(crate) fn copy_from(&self, buffer: BufferHandle, owned: &[u8]) -> Result<()> {
// SAFETY: buffer owner is current, exact allocation size checked,
// and the caller owns this staging allocation. It synchronizes on
// both success/error and leaks staging on ambiguous completion, so
// the pointer stays valid even if the call retains it after return.
check("cuMemcpyHtoD_v2", unsafe {
(self.copy_from)(buffer.0, owned.as_ptr().cast(), owned.len())
})
}
pub(crate) fn copy_to(&self, buffer: BufferHandle, owned: &mut [u8]) -> Result<()> {
// SAFETY: valid owned writable staging of exactly the allocation
// size; current owner context; caller synchronizes or leaks as
// above. No borrowed output is passed directly to the driver.
check("cuMemcpyDtoH_v2", unsafe {
(self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len())
})
}
}
}
#[cfg(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
))]
pub(crate) use enabled::Api;
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
pub(crate) struct Api;
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
impl Api {
pub(crate) fn load() -> Result<Self> {
if cfg!(feature = "cuda-driver") {
Err(Error::UnsupportedPlatform)
} else {
Err(Error::Disabled)
}
}
// These methods cannot be reached through the safe API: load always fails.
pub(crate) fn init(&self) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn version(&self) -> Result<i32> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn device(&self, _: i32) -> Result<i32> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn create(&self, _: i32) -> Result<ContextHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn destroy(&self, _: ContextHandle) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn push(&self, _: ContextHandle) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn pop(&self) -> Result<ContextHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn synchronize(&self) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn allocate(&self, _: usize) -> Result<BufferHandle> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn free(&self, _: BufferHandle) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy_from(&self, _: BufferHandle, _: &[u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn copy_to(&self, _: BufferHandle, _: &mut [u8]) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
}
+397
View File
@@ -0,0 +1,397 @@
//! Opt-in CUDA Driver context and bounded byte buffers, without inference.
//!
//! Enable `cuda-driver` and explicitly call [`Driver::load`] on Linux 64-bit.
//! Resources are confined to their creating thread and borrow their owners.
//! Copies stage owned bytes and synchronize before publishing host output.
//! A failed synchronization poisons the context and intentionally leaks the
//! bounded staging allocation: completion cannot safely be inferred from an
//! error, including a subsequent context-destruction result.
#![deny(unsafe_code)]
#![deny(unsafe_op_in_unsafe_fn)]
use std::{cell::Cell, fmt, marker::PhantomData, rc::Rc};
#[allow(unsafe_code)]
mod ffi;
/// Errors retain CUDA operation names/codes and any subsequent cleanup errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
Disabled,
UnsupportedPlatform,
LibraryUnavailable,
MissingSymbol(&'static str),
InvalidDriverValue(&'static str),
Driver {
operation: &'static str,
code: i32,
},
InvalidOrdinal,
InvalidSize,
BudgetExceeded,
ShapeMismatch {
expected: usize,
actual: usize,
},
HostAllocation,
ContextPoisoned,
UnexpectedContext,
Multiple {
primary: Box<Error>,
secondary: Box<Error>,
},
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
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")
}
Self::Driver { operation, code } => {
write!(f, "{operation} failed with CUDA code {code}")
}
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}")
}
}
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;
fn combine<T>(primary: Result<T>, secondary: Result<()>) -> Result<T> {
match (primary, secondary) {
(Ok(value), Ok(())) => Ok(value),
(Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error),
(Err(primary), Err(secondary)) => Err(Error::Multiple {
primary: Box::new(primary),
secondary: Box::new(secondary),
}),
}
}
fn valid_size(bytes: usize) -> Result<()> {
if bytes == 0 || bytes > isize::MAX as usize {
Err(Error::InvalidSize)
} else {
Ok(())
}
}
/// A loaded fixed ABI. No resources can be sent or shared between threads.
pub struct Driver {
api: Rc<ffi::Api>,
version: i32,
}
impl Driver {
/// Resolve the entire fixed ABI before initializing CUDA.
pub fn load() -> Result<Self> {
let api = Rc::new(ffi::Api::load()?);
api.init()?;
let version = api.version()?;
Ok(Self { api, version })
}
pub fn version(&self) -> i32 {
self.version
}
pub fn device(&self, ordinal: i32) -> Result<Device<'_>> {
if ordinal < 0 {
return Err(Error::InvalidOrdinal);
}
Ok(Device {
driver: self,
handle: self.api.device(ordinal)?,
})
}
}
/// A device selected through its owner driver, without a public raw handle.
pub struct Device<'driver> {
driver: &'driver Driver,
handle: i32,
}
impl<'driver> Device<'driver> {
pub fn create_context(&self, byte_budget: usize) -> Result<Context<'driver>> {
valid_size(byte_budget)?;
let api = &self.driver.api;
let handle = api.create(self.handle)?;
let restore = api.pop().and_then(|popped| {
if popped == handle {
Ok(())
} else {
Err(Error::UnexpectedContext)
}
});
if let Err(error) = restore {
let cleanup = api.destroy(handle);
if cleanup.is_err() {
// The driver may still own a live context; keep its ABI loaded.
std::mem::forget(Rc::clone(api));
}
return combine(Err(error), cleanup);
}
Ok(Context {
driver: self.driver,
handle: Some(handle),
budget: byte_budget,
allocated: Cell::new(0),
poisoned: Cell::new(false),
})
}
}
/// A private context with a budget for actual live allocations.
pub struct Context<'driver> {
driver: &'driver Driver,
handle: Option<ffi::ContextHandle>,
budget: usize,
allocated: Cell<usize>,
poisoned: Cell<bool>,
}
impl Context<'_> {
pub fn budget_bytes(&self) -> usize {
self.budget
}
/// Failed frees remain charged until context destruction.
pub fn allocated_bytes(&self) -> usize {
self.allocated.get()
}
fn enter(&self) -> Result<CurrentGuard<'_, '_>> {
if self.poisoned.get() {
return Err(Error::ContextPoisoned);
}
let handle = self.handle.ok_or(Error::ContextPoisoned)?;
self.driver.api.push(handle)?;
Ok(CurrentGuard {
context: self,
active: true,
})
}
pub fn allocate(&self, bytes: usize) -> Result<DeviceBuffer<'_>> {
valid_size(bytes)?;
let total = self
.allocated
.get()
.checked_add(bytes)
.ok_or(Error::BudgetExceeded)?;
if total > self.budget {
return Err(Error::BudgetExceeded);
}
let guard = self.enter()?;
let allocation = self.driver.api.allocate(bytes);
if allocation.is_ok() {
self.allocated.set(total);
}
// A successful allocation whose pop fails stays charged. The poisoned
// context owns that allocation until destruction, so no unguarded free.
let handle = combine(allocation, guard.finish())?;
Ok(DeviceBuffer {
context: self,
handle: Some(handle),
bytes,
_thread: PhantomData,
})
}
pub fn synchronize(&self) -> Result<()> {
let guard = self.enter()?;
let sync = self.driver.api.synchronize();
if sync.is_err() {
self.poisoned.set(true);
}
combine(sync, 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<()> {
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.
let result = self.driver.api.destroy(handle);
if result.is_err() {
std::mem::forget(Rc::clone(&self.driver.api));
}
if result.is_ok() {
self.allocated.set(0);
}
result
} else {
Ok(())
}
}
}
impl Drop for Context<'_> {
fn drop(&mut self) {
let _ = self.destroy();
}
}
/// Push/pop balance with fallible explicit finish and nonpanicking fallback.
struct CurrentGuard<'context, 'driver> {
context: &'context Context<'driver>,
active: bool,
}
impl CurrentGuard<'_, '_> {
fn finish(mut self) -> Result<()> {
self.restore()
}
fn restore(&mut self) -> Result<()> {
if !self.active {
return Ok(());
}
self.active = false;
let result = self.context.driver.api.pop().and_then(|popped| {
if Some(popped) == self.context.handle {
Ok(())
} else {
Err(Error::UnexpectedContext)
}
});
if result.is_err() {
self.context.poisoned.set(true);
}
result
}
}
impl Drop for CurrentGuard<'_, '_> {
fn drop(&mut self) {
let _ = self.restore();
}
}
/// An exact nonempty byte allocation borrowing its owning context.
pub struct DeviceBuffer<'context> {
context: &'context Context<'context>,
handle: Option<ffi::BufferHandle>,
bytes: usize,
_thread: PhantomData<Rc<()>>,
}
impl DeviceBuffer<'_> {
pub fn len(&self) -> usize {
self.bytes
}
pub fn is_empty(&self) -> bool {
false
}
fn staging(&self, actual: usize) -> Result<Vec<u8>> {
if actual != self.bytes {
return Err(Error::ShapeMismatch {
expected: self.bytes,
actual,
});
}
if self.context.poisoned.get() {
return Err(Error::ContextPoisoned);
}
let mut staging = Vec::new();
staging
.try_reserve_exact(self.bytes)
.map_err(|_| Error::HostAllocation)?;
staging.resize(self.bytes, 0);
Ok(staging)
}
pub fn copy_from(&mut self, input: &[u8]) -> Result<()> {
let mut staging = self.staging(input.len())?;
staging.copy_from_slice(input);
self.copy_staged(staging, false).map(|_| ())
}
pub fn copy_to(&self, output: &mut [u8]) -> Result<()> {
let staging = self.staging(output.len())?;
let staging = self.copy_staged(staging, true)?;
output.copy_from_slice(&staging);
Ok(())
}
fn copy_staged(&self, mut staging: Vec<u8>, to_host: bool) -> Result<Vec<u8>> {
let handle = self.handle.ok_or(Error::ContextPoisoned)?;
let guard = self.context.enter()?;
let copy = if to_host {
self.context.driver.api.copy_to(handle, &mut staging)
} else {
self.context.driver.api.copy_from(handle, &staging)
};
// Even copy errors can report earlier asynchronous work. Synchronize
// on every attempted copy before considering the staging reclaimable.
let sync = self.context.driver.api.synchronize();
if sync.is_err() {
self.context.poisoned.set(true);
// CUDA may still reference these owned host bytes. A poisoned
// context admits no further copy, limiting this leak to one buffer
// (at most its context budget), regardless of caller lifetimes.
std::mem::forget(staging);
return combine(combine(copy, sync), guard.finish()).map(|()| Vec::new());
}
combine(copy, guard.finish())?;
Ok(staging)
}
pub fn release(mut self) -> Result<()> {
self.free()
}
fn free(&mut self) -> Result<()> {
let Some(handle) = self.handle.take() else {
return Ok(());
};
let guard = self.context.enter()?;
let free = self.context.driver.api.free(handle);
if free.is_ok() {
self.context
.allocated
.set(self.context.allocated.get() - self.bytes);
}
combine(free, guard.finish())
}
}
impl Drop for DeviceBuffer<'_> {
fn drop(&mut self) {
let _ = self.free();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sizes_and_error_composition() {
assert_eq!(valid_size(0), Err(Error::InvalidSize));
assert_eq!(valid_size(usize::MAX), Err(Error::InvalidSize));
assert_eq!(valid_size(1), Ok(()));
assert_eq!(
combine::<()>(Err(Error::InvalidSize), Err(Error::UnexpectedContext)),
Err(Error::Multiple {
primary: Box::new(Error::InvalidSize),
secondary: Box::new(Error::UnexpectedContext)
})
);
}
#[cfg(not(feature = "cuda-driver"))]
#[test]
fn default_load_rejects_before_driver_use() {
assert!(matches!(Driver::load(), Err(Error::Disabled)));
}
#[cfg(all(
feature = "cuda-driver",
not(all(target_os = "linux", target_pointer_width = "64"))
))]
#[test]
fn unsupported_load_rejects_before_driver_use() {
assert!(matches!(Driver::load(), Err(Error::UnsupportedPlatform)));
}
}
+109
View File
@@ -0,0 +1,109 @@
/* Synthetic CPU-only CUDA Driver ABI fixture. No NVIDIA headers/devices/library. */
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef void *CUcontext;
typedef uint64_t CUdeviceptr;
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 int live_context;
static unsigned failed_mask;
static struct {void *ptr;size_t size;} buffers[16];
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 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();
FILE *f=fopen(path,"a");if(!f)abort();
fprintf(f,"%s %d %lu %zu %d %zu %zu\n",stage,code,(unsigned long)(uintptr_t)current,depth,live_context,charged(),bytes);
fclose(f);
}
static int fault(int op) {
calls[op]++;
const char *value=getenv("MOCK_CUDA_FAIL");
if(!value||(failed_mask&(1u<<op)))return 0;
char requested[128],expected[64];snprintf(requested,sizeof(requested),"%s",value);
snprintf(expected,sizeof(expected),"%s:%u",names[op],calls[op]);
for(char *token=strtok(requested,",");token;token=strtok(NULL,",")) {
if(strcmp(token,names[op])==0||strcmp(token,expected)==0) {
failed_mask|=1u<<op;trace(names[op],700,0);return 700;
}
}
return 0;
}
static void complete_pending(void) {
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);
}
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 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;
return NULL;
}
CUresult cuInit(unsigned flags) {if(flags)return 1;if(fault(0))return 700;trace("init",0,0);return 0;}
CUresult cuDriverGetVersion(int *version) {if(fault(1))return 700;*version=13000;trace("version",0,0);return 0;}
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;
}
CUresult cuCtxDestroy_v2(CUcontext ctx) {
if(fault(4))return 700;if(ctx!=owned||!live_context)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;
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;
stack[depth++]=current;current=ctx;trace("push",0,0);return 0;
}
CUresult cuCtxPopCurrent_v2(CUcontext *result) {
if(fault(6))return 700;if(!depth)return 201;
*result=current;current=stack[--depth];
const char *wrong=getenv("MOCK_CUDA_WRONG_POP");
if(wrong&&calls[6]==(unsigned)strtoul(wrong,NULL,10))*result=(void *)(uintptr_t)0x99;
trace("pop",0,0);return 0;
}
CUresult cuCtxSynchronize(void) {
if(fault(7))return 700;if(require_context())return 201;
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;}
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;}
return 1;
}
CUresult cuMemcpyHtoD_v2(CUdeviceptr ptr,const void *host,size_t bytes) {
if(fault(10))return 700;if(require_context()||!lookup(ptr,bytes))return 201;
/* Copy is deliberately delayed to explicit synchronization. */
pending_host=host;pending_device=lookup(ptr,bytes);pending_bytes=bytes;trace("htod",0,bytes);return 0;
}
#ifndef MOCK_MISSING_DTOH
CUresult cuMemcpyDtoH_v2(void *host,CUdeviceptr ptr,size_t bytes) {
if(fault(11))return 700;if(require_context()||!lookup(ptr,bytes))return 201;
pending_destination=host;pending_device=lookup(ptr,bytes);pending_bytes=bytes;trace("dtoh",0,bytes);return 0;
}
#endif
+381
View File
@@ -0,0 +1,381 @@
#![cfg(all(target_os = "linux", target_pointer_width = "64"))]
use leleka_cuda_driver::Driver;
use std::{fs, path::PathBuf, process::Command};
#[derive(Debug)]
struct Row {
stage: String,
code: i32,
current: usize,
depth: usize,
live: usize,
charged: usize,
bytes: usize,
}
fn trace() -> Vec<Row> {
let path = std::env::var("MOCK_CUDA_TRACE").unwrap();
fs::read_to_string(path)
.unwrap_or_default()
.lines()
.map(|line| {
let v: Vec<_> = line.split_whitespace().collect();
assert_eq!(v.len(), 7);
Row {
stage: v[0].into(),
code: v[1].parse().unwrap(),
current: v[2].parse().unwrap(),
depth: v[3].parse().unwrap(),
live: v[4].parse().unwrap(),
charged: v[5].parse().unwrap(),
bytes: v[6].parse().unwrap(),
}
})
.collect()
}
fn valid_context_trace(rows: &[Row]) {
for row in rows.iter().filter(|row| row.code == 0) {
if ["alloc", "htod", "dtoh", "sync", "free"].contains(&row.stage.as_str()) {
assert_eq!(row.current, 0x22, "{row:?}");
assert_eq!(row.depth, 1, "{row:?}");
assert_eq!(row.live, 1);
}
if row.stage == "pop" {
assert_eq!(row.current, 0x11, "{row:?}");
assert_eq!(row.depth, 0);
}
}
}
fn cuda_errors(error: &leleka_cuda_driver::Error) -> Vec<(&'static str, i32)> {
match error {
leleka_cuda_driver::Error::Driver { operation, code } => vec![(*operation, *code)],
leleka_cuda_driver::Error::Multiple { primary, secondary } => {
let mut errors = cuda_errors(primary);
errors.extend(cuda_errors(secondary));
errors
}
_ => Vec::new(),
}
}
#[test]
#[ignore = "requires isolated CPU-only fake libcuda harness"]
fn isolated_cpu_elf_matrix() {
assert_eq!(
std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(),
Ok("1"),
"run only the isolated synthetic ELF harness"
);
let root = PathBuf::from(std::env::var("LELEKA_CUDA_MOCK_ROOT").unwrap());
assert!(root.is_absolute());
let scenarios = [
"success",
"bounds",
"missing",
"missing_cuInit",
"missing_cuDriverGetVersion",
"missing_cuDeviceGet",
"missing_cuCtxCreate_v2",
"missing_cuCtxDestroy_v2",
"missing_cuCtxPushCurrent_v2",
"missing_cuCtxPopCurrent_v2",
"missing_cuCtxSynchronize",
"missing_cuMemAlloc_v2",
"missing_cuMemFree_v2",
"missing_cuMemcpyHtoD_v2",
"init",
"version",
"device",
"create",
"create_pop",
"push",
"pop",
"wrong_pop",
"operation_wrong_pop",
"context_sync",
"alloc",
"htod",
"dtoh",
"sync_htod",
"sync_dtoh",
"htod_sync",
"dtoh_sync",
"free",
"destroy",
];
for scenario in scenarios {
let path = root.join(format!("trace-{scenario}"));
let mut command = Command::new(std::env::current_exe().unwrap());
command
.args(["--exact", "fixture_child", "--ignored", "--nocapture"])
.env("LELEKA_CUDA_CASE", scenario)
.env("MOCK_CUDA_TRACE", &path)
.env_remove("MOCK_CUDA_FAIL")
.env_remove("MOCK_CUDA_WRONG_POP");
command.env(
"LD_LIBRARY_PATH",
root.join(if scenario.starts_with("missing") {
scenario
} else {
"complete"
}),
);
let failure = match scenario {
"create_pop" => Some("pop"),
"pop" => Some("pop:2"),
"sync_htod" => Some("sync"),
"sync_dtoh" => Some("sync:2"),
"htod_sync" => Some("htod,sync"),
"dtoh_sync" => Some("dtoh,sync:2"),
"success" | "bounds" | "missing" | "wrong_pop" | "operation_wrong_pop" => None,
"context_sync" => Some("sync"),
other => Some(other),
};
if let Some(failure) = failure {
command.env("MOCK_CUDA_FAIL", failure);
}
if ["wrong_pop", "operation_wrong_pop"].contains(&scenario) {
command.env(
"MOCK_CUDA_WRONG_POP",
if scenario == "wrong_pop" { "1" } else { "2" },
);
}
let output = command.output().unwrap();
assert!(
output.status.success(),
"scenario {scenario}\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
println!("synthetic CPU ELF scenario {scenario}: PASS");
}
}
#[test]
#[ignore = "invoked only by isolated_cpu_elf_matrix with synthetic library"]
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("missing") || ["init", "version"].contains(&case.as_str()) {
let error = Driver::load()
.err()
.expect("missing ABI/init/version must fail");
if case.starts_with("missing") {
let symbol = case.strip_prefix("missing_").unwrap_or("cuMemcpyDtoH_v2");
assert!(
matches!(error,leleka_cuda_driver::Error::MissingSymbol(actual) if actual==symbol)
);
}
let rows = trace();
if case.starts_with("missing") {
assert!(rows.is_empty(), "symbol resolution must precede init");
} else {
assert!(rows.iter().any(|row| row.stage == case && row.code == 700));
}
return;
}
let driver = Driver::load().unwrap();
assert_eq!(driver.version(), 13000);
if case == "device" {
assert!(driver.device(0).is_err());
return;
}
assert!(driver.device(-1).is_err());
let device = driver.device(0).unwrap();
if case == "bounds" {
let before = trace().len();
assert!(device.create_context(0).is_err());
assert!(device.create_context(usize::MAX).is_err());
assert_eq!(trace().len(), before);
}
if ["create", "create_pop", "wrong_pop"].contains(&case.as_str()) {
assert!(device.create_context(16).is_err());
let rows = trace();
if case == "create" {
assert!(!rows.iter().any(|row| row.stage == "destroy"));
} else {
assert!(
rows.iter()
.any(|row| row.stage == "destroy" && row.code == 0)
);
}
return;
}
let context = device.create_context(16).unwrap();
assert_eq!(context.budget_bytes(), 16);
assert_eq!(context.allocated_bytes(), 0);
assert_eq!(trace().last().unwrap().current, 0x11);
if ["alloc", "push", "pop", "operation_wrong_pop"].contains(&case.as_str()) {
assert!(context.allocate(8).is_err());
if ["pop", "operation_wrong_pop"].contains(&case.as_str()) {
let before = trace().len();
assert!(context.allocate(8).is_err());
assert!(context.synchronize().is_err());
assert_eq!(trace().len(), before, "poison must reject native work");
} else {
assert_eq!(context.allocated_bytes(), 0);
}
drop(context);
valid_context_trace(&trace());
return;
}
if case == "context_sync" {
assert!(context.synchronize().is_err());
drop(context);
valid_context_trace(&trace());
return;
}
if case == "bounds" {
let before = trace().len();
assert!(context.allocate(0).is_err());
assert!(context.allocate(17).is_err());
assert!(context.allocate(usize::MAX).is_err());
assert_eq!(trace().len(), before);
}
let mut buffer = context.allocate(8).unwrap();
assert_eq!(buffer.len(), 8);
assert_eq!(context.allocated_bytes(), 8);
if case == "bounds" {
let before = trace().len();
assert!(context.allocate(9).is_err());
assert!(buffer.copy_from(&[1; 7]).is_err());
assert!(buffer.copy_from(&[1; 9]).is_err());
let mut short = [0x99; 7];
assert!(buffer.copy_to(&mut short).is_err());
assert_eq!(short, [0x99; 7]);
assert_eq!(
trace().len(),
before,
"bounds reject before driver mutation"
);
}
let mut input = [0, 1, 2, 3, 0xff, 0x80, 0x55, 0xaa];
let mut output = [0x99; 8];
if ["htod", "sync_htod", "htod_sync"].contains(&case.as_str()) {
let error = buffer.copy_from(&input).unwrap_err();
let expected = match case.as_str() {
"htod" => vec![("cuMemcpyHtoD_v2", 700)],
"sync_htod" => vec![("cuCtxSynchronize", 700)],
_ => vec![("cuMemcpyHtoD_v2", 700), ("cuCtxSynchronize", 700)],
};
assert_eq!(
cuda_errors(&error),
expected,
"copy/completion errors retained in order"
);
input.fill(0);
std::hint::black_box(input);
if ["sync_htod", "htod_sync"].contains(&case.as_str()) {
let before = trace().len();
assert!(context.allocate(1).is_err());
assert_eq!(trace().len(), before);
}
} else {
buffer.copy_from(&input).unwrap();
if ["dtoh", "sync_dtoh", "dtoh_sync"].contains(&case.as_str()) {
let error = buffer.copy_to(&mut output).unwrap_err();
let expected = match case.as_str() {
"dtoh" => vec![("cuMemcpyDtoH_v2", 700)],
"sync_dtoh" => vec![("cuCtxSynchronize", 700)],
_ => vec![("cuMemcpyDtoH_v2", 700), ("cuCtxSynchronize", 700)],
};
assert_eq!(
cuda_errors(&error),
expected,
"copy/completion errors retained in order"
);
assert_eq!(output, [0x99; 8], "failed copy must not publish staging");
if ["sync_dtoh", "dtoh_sync"].contains(&case.as_str()) {
let before = trace().len();
assert!(context.synchronize().is_err());
assert_eq!(trace().len(), before);
}
} else {
buffer.copy_to(&mut output).unwrap();
assert_eq!(output, input);
}
}
if case == "free" {
let error = buffer.release().unwrap_err();
assert_eq!(cuda_errors(&error), vec![("cuMemFree_v2", 700)]);
assert_eq!(context.allocated_bytes(), 8);
} else if ["sync_htod", "sync_dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) {
drop(buffer);
} else {
buffer.release().unwrap();
assert_eq!(context.allocated_bytes(), 0);
}
if case == "destroy" {
let error = context.close().unwrap_err();
assert_eq!(cuda_errors(&error), vec![("cuCtxDestroy_v2", 700)]);
} else if ["sync_htod", "sync_dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) {
drop(context);
} else {
context.close().unwrap();
}
let rows = trace();
if case == "sync_htod" {
assert!(
rows.iter()
.any(|row| row.stage == "pending_htod" && row.code == 0 && row.bytes == 644),
"delayed source retained original owned bytes after caller input changed"
);
}
if case == "sync_dtoh" {
assert!(
rows.iter()
.any(|row| row.stage == "pending_dtoh" && row.bytes == 8)
);
assert_eq!(
output, [0x99; 8],
"completion after failed sync must target retained staging, never caller output"
);
}
if ["htod", "dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) {
let copy = if case.starts_with("htod") {
"htod"
} else {
"dtoh"
};
let index = rows
.iter()
.position(|row| row.stage == copy && row.code == 700)
.unwrap();
assert_eq!(
rows[index + 1].stage,
"sync",
"sync must be attempted after copy failure"
);
assert_eq!(
rows[index + 1].code,
if case.ends_with("_sync") { 700 } else { 0 }
);
}
valid_context_trace(&rows);
assert!(
rows.iter().any(|row| row.stage == "destroy"),
"owned context cleanup attempted"
);
assert!(
!rows.iter().any(|row| row.stage == "unsafe_pending_free"),
"pending copy device freed early"
);
for row in rows
.iter()
.filter(|row| row.stage == "alloc" && row.code == 0)
{
assert_eq!(row.bytes, 8);
assert_eq!(row.charged, 8);
}
if !["destroy"].contains(&case.as_str()) {
let destroyed = rows
.iter()
.rev()
.find(|row| row.stage == "destroy" && row.code == 0)
.unwrap();
assert_eq!(destroyed.live, 0);
assert_eq!(destroyed.charged, 0);
assert_eq!(destroyed.current, 0x11);
}
}
+168
View File
@@ -0,0 +1,168 @@
# Independent CUDA driver bootstrap contract
Requirements of record for bounded STRA-102 plan
`d20f1568-5b7b-477d-8eab-a32219af7fd7`, before implementation.
This foundation does not implement inference, model loading or GPU kernels and
must not change production serving or advertise any supported model.
## Platform and ABI
- Explicit `cuda-driver` Cargo feature, disabled by default, plus an explicit
`Driver::load()` call; Linux with 64-bit pointers. Unsupported platforms or
disabled capability must return a clear error without touching a CUDA driver.
- Load only the installed NVIDIA Driver ABI soname `libcuda.so.1` at runtime.
No CUDA Toolkit, Strata, Python, C compiler or native build script is a
production build/runtime dependency of this Rust crate.
- Resolve the fixed documented legacy ABI symbols, with `_v2` context, device
allocation/free and synchronous copy symbols where required. Missing symbols
fail before CUDA initialization or resource mutation. No symbol-version
fallback or API reinterpretation.
- Isolate all unsafe FFI and dynamic loader code in the driver crate. Public
callers get owned typed resources and errors, never raw host/device pointers
or mutable CUDA context handles.
## Fixed ABI and source evidence
The exact symbol set is `cuInit`, `cuDriverGetVersion`, `cuDeviceGet`,
`cuCtxCreate_v2`, `cuCtxDestroy_v2`, `cuCtxPushCurrent_v2`,
`cuCtxPopCurrent_v2`, `cuCtxSynchronize`, `cuMemAlloc_v2`, `cuMemFree_v2`,
`cuMemcpyHtoD_v2`, `cuMemcpyDtoH_v2`. The legacy create binding has three
arguments: `CUcontext*`, `unsigned int`, `CUdevice`; the current unversioned
CUDA 13 header macro points to the four-argument v4 entry instead and must
not be rebound to this function type. Device pointers are 64-bit for this
64-bit-only surface; byte counts use `size_t`.
Independent TL verification read the official
[NVIDIA cudart 13.0.88 archive](https://developer.download.nvidia.com/compute/cuda/redist/cuda_cudart/linux-x86_64/cuda_cudart-linux-x86_64-13.0.88-archive.tar.xz)
in memory, without installing headers or a toolkit. Archive size 1,491,604 bytes,
SHA256 `bc44226f069402ab327bcf9e754660621aa6bc61fb7fc6afe03b794dfaaab658`;
`cuda.h` SHA256 `64025f81a9d6d2b10e9e11654f3523e5b046d01b883f0b9ca474e463274b80d4`.
Header lines 25633/90 prove the legacy declaration/current alias respectively;
line 274 defines the 64-bit device pointer. Runtime behavior still requires
separate installed-driver qualification. See NVIDIA's
[synchronization behavior](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/api-sync-behavior.html)
for why calling a synchronous-named copy alone does not prove completion of
all host memory references.
## Ownership and context discipline
- Driver, context and device-buffer lifetimes keep the dynamic library alive
until every dependent operation and cleanup finishes. Resources cannot be
sent or shared between threads (`!Send`, `!Sync`).
- Create a private context and pop it immediately, restoring the caller's
previous context. Do not use or mutate an external primary context.
- Push the owned context for every operation that needs it, and restore the
previous context on both success and failure. Pop failures must surface as
errors; never claim restoration after the driver rejects restoration.
- Buffers cannot outlive their owner context; allocation/copy operations are
bounded, checked before driver mutation and reject empty/oversized shapes.
- Copies use exact-sized byte slices with bounded owned staging memory and the
synchronous Driver API. DtoH publishes staging only after completion; ambiguous
completion errors retain staging and poison the context to prevent dangling
host DMA pointers. Synchronize
before returning host borrows. Failed copy/synchronization paths must preserve
context cleanup, while reporting the original driver failure accurately.
- Cleanup is best-effort on drop, does not panic and must not free resources in
an unrelated context. Explicit fallible cleanup should expose failure when
the API supports it; permanently failed driver cleanup cannot be guaranteed.
## Independent CPU qualification
Only synthetic owned fixtures may be used. The test library is compiled to an
ELF named `libcuda.so.1`, injected through a private subprocess loader environment
inside a disposable Linux CPU Docker container. No installed driver is called,
no NVIDIA device is exposed, and no GPU/model/request probe is performed.
The fake library records synthetic ABI operations, context stack, allocated bytes,
copy/sync actions and cleanup. Independent assertions cover missing symbols,
init/device/create/push/pop/alloc/copy/sync/free/destroy errors, bounds before
mutation, byte-copy round trips and prior-context restoration. Lifetime and
thread-safety compile-fail gates are required as well as runtime tests.
All existing local gates remain; focused checks add crate format/Clippy/unit and
the Linux ELF mock gate. Results below must report the actual environment,
counts and cleanup, never infer GPU success from a mock or compile pass.
## Qualification state
Actual local CPU result on 2026-10-07:
- Linux **aarch64**, native CPU Docker Desktop execution; Rust 1.99.0
(`b940084d7 2026-09-28`), GNU C compiler Debian 12.2.0-14+deb12u1.
- Pinned Rust base OCI index:
`sha256:114c7a4425406451c2866b6aafe69fe29b1b298832db1277d411ac73c82d04d6`.
Independently inspected index contains Linux amd64 manifest
`sha256:b36c246742b4d323472588f789601be34eb4af053255e2af53969078ee8dcec7`
and arm64 manifest
`sha256:e393e07b3c3c39f238de676b0eb60c03dc7aefe5d6e37be6d29c686bf4d7e256`.
The final owned fixture image after installing matching rustfmt/Clippy was
`sha256:a7fd4951f84b368826117e60c93f1e067ade2e39b2b69329108e70b052dd136d`.
- Actual test container: nonroot UID/GID 65532, default runc, network `none`,
all effective/permitted/bounding capabilities zero, no privileges, no host
binds or device requests/devices; raw NVIDIA/DRI device guard passed.
Build tools were provisioned in an earlier disposable setup container;
all tests and compilation then ran offline with network disabled.
- Minimal synthetic workspace contained only exact driver crate source/tests,
matching workspace package/lint declarations, and approved pinned libc
0.2.190. Engine, control-plane, CUDA Toolkit/headers/nvcc and installed
`libcuda` were physically absent. The existing registry archive SHA256
`ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78`
was checked before extraction, then Cargo verified every vendored source
checksum. Normal dependency tree was driver crate → libc only.
- Default denial/unit tests: **2 passed**. Actual enabled-FFI all-target,
all-feature Clippy with warnings denied and formatting passed.
- **33 isolated subprocess scenarios passed**: round trip, pre-mutation
shape/budget refusal, each of the twelve missing symbols, init/version/device,
create/pop cleanup, push/pop errors, mismatched popped context and poisoned
future work, allocation, both copy directions, explicit synchronization,
copy-plus-sync dual errors in original/cleanup order, free and destroy faults.
The fixture matrix is explicitly ignored by ordinary `cargo test`; the harness
selects it with `--ignored` and requires its marker, so an absent harness
cannot appear as a vacuous integration pass.
- Delayed synthetic HtoD at destruction read the exact original eight owned
staging bytes after the caller source was changed to zeros. Delayed DtoH at
destruction wrote retained staging while the still-live caller destination
remained unchanged after failed synchronization. These independently
witness the declared staging/completion behavior, alongside source review;
they are not a proof of all possible memory safety or vendor behavior.
- **10 independent compile refusals passed**: Send and Sync for Driver, Device,
Context and DeviceBuffer; context outliving Driver; buffer outliving Context.
Assertions checked the expected auto-trait/borrow compiler diagnostics.
- Final fake full/missing-DtoH ELF SHA256 values:
`551878f9b518b200f8ac3dbf3570ec7494f1a2226917530c84ea30b418c1d41f` /
`a95af6e51e678a5e3fc5f937b4232393493497161195391e256138a5d2009991`.
Source hashes inside the container matched the working-tree bytes.
- All owned setup/test containers, derived fixture images, private source
staging, synthetic libraries, trace files and target directories were
removed. The shared pinned base image and existing registry cache were retained.
Cleanup attempts each resource independently, preserves test failure, and
fails a successful test run if any cleanup fails.
Two initial fixture provisioning failures occurred before Rust integration:
missing optional rustfmt/Clippy, then Docker tmpfs execution denial for libc's
Rust build script. The final fixture installs verified toolchain components and
uses an explicitly executable owned `/tmp`; product behavior and assertions
were not weakened.
Production source receipts: `src/lib.rs`
`7ce58fcf033b5e9704b2d134fc4c16cd2d5c57c5c45a867d2399c310dec3c4d4`;
`src/ffi.rs` `5f00400fab73d98578ca53bfedcb86b4163133d2956a88ac3d2cd156455800c8`.
## Remaining integration limits
These outcomes qualify a GNU/Linux CPU mock contract. They do not execute an
installed NVIDIA driver, GPU allocation/copy or a kernel, and they do not prove
vendor cleanup succeeds after a driver failure. A sync fault deliberately
retains bounded staging and poisons that context; failed destruction can retain
the library/context instead of pretending release occurred. Repeated poisoned
contexts can accumulate retained resources; there is no process-wide recovery
or memory-bounded serving guarantee in this bootstrap.
The existing statically linked musl executable is also **unqualified** for this
loader. [musl's static dlopen stub](https://git.musl-libc.org/cgit/musl/plain/src/ldso/dlopen.c)
refuses dynamic loading; the GNU/Linux ELF mock pass does not make static musl
capable of loading `libcuda.so.1`. A separate executable/loader integration gate
is required. The OCI index admits amd64 builds, but this actual local mock run
was arm64; hosted amd64/compiler qualification is separately pending.
Installed-driver GPU allocation/copy, kernel execution, model inference,
model quality and paired performance remain separate unqualified gates.
+4
View File
@@ -24,6 +24,10 @@ cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-backend-
cargo fmt --manifest-path "${repo_root}/crates/quant-core/Cargo.toml" --check
cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-quant-core --all-targets -- -D warnings
cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-quant-core
cargo fmt --manifest-path "${repo_root}/crates/cuda-driver/Cargo.toml" --check
cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-cuda-driver --all-targets --all-features -- -D warnings
cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-cuda-driver
"${repo_root}/scripts/test-cuda-driver-bootstrap.sh"
cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check
cargo clippy --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --all-targets -- -D warnings
cargo test --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env bash
# Usage: scripts/test-cuda-driver-bootstrap.sh [--inside]
# Default: isolated Linux CPU Docker mock ELF gate; --inside is container-only.
# Synthetic crate-only workspace; no installed CUDA driver or model data accessed.
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
image='rust@sha256:114c7a4425406451c2866b6aafe69fe29b1b298832db1277d411ac73c82d04d6'
if [[ "${1:-}" == --inside ]]; then
[[ $# == 1 && -f /.dockerenv && "$(uname -s)" == Linux ]]
[[ "$(id -u)" == 65532 ]]
[[ "$(awk '/^Cap(Eff|Prm|Bnd):/{print $2}' /proc/self/status)" == $'0000000000000000\n0000000000000000\n0000000000000000' ]]
for device in /dev/nvidia* /dev/dri/*; do
[[ ! -e "$device" ]] || { echo 'raw GPU device present; refusing mock gate' >&2; exit 1; }
done
[[ ! -e "${repo_root}/engine" && ! -e "${repo_root}/control-plane" ]]
command -v nvcc >/dev/null && { echo 'unexpected CUDA Toolkit' >&2; exit 1; }
if ldconfig -p 2>/dev/null | grep -q 'libcuda\.so'; then
echo 'installed CUDA driver present; refusing mock gate' >&2; exit 1
fi
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 \
"${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 \
"${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
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" \
-o "$work/missing_$symbol/libcuda.so.1"
done
readelf -h "$work/complete/libcuda.so.1" | grep 'Class:.*ELF64'
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/tests/mock_cuda.c" "${repo_root}/crates/cuda-driver/tests/mock_driver.rs"
rustup component list --installed
rustc --version
cc --version | head -1
export CARGO_TARGET_DIR="$work/target"
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 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" \
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)"
[[ -n "$rlib" ]]
# Independent negative compile gates: lifetimes/auto-traits cannot escape FFI ownership.
for typename in Driver 'Device<'"'static"'>' 'Context<'"'static"'>' 'DeviceBuffer<'"'static"'>';
do
for trait in Send Sync; do
printf 'use leleka_cuda_driver::*;fn require<T:%s>(){}fn main(){require::<%s>();}\n' "$trait" "$typename" > "$work/reject.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 "unsafe trait escape: $typename $trait" >&2; exit 1
fi
grep -Eq 'cannot be (sent|shared).*safely' "$work/reject.log"
echo "compile refusal $typename $trait: PASS"
done
done
cat > "$work/reject.rs" <<'RS'
use leleka_cuda_driver::Driver;
fn main(){let driver=Driver::load().unwrap();let device=driver.device(0).unwrap();let context=device.create_context(16).unwrap();drop(driver);context.synchronize().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 'driver lifetime escaped' >&2; exit 1; fi
grep -q 'cannot move out of.*driver.*because it is borrowed' "$work/reject.log"
cat > "$work/reject.rs" <<'RS'
use leleka_cuda_driver::Driver;
fn main(){let driver=Driver::load().unwrap();let device=driver.device(0).unwrap();let context=device.create_context(16).unwrap();let buffer=context.allocate(8).unwrap();context.close().unwrap();buffer.copy_to(&mut [0;8]).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 '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'
cargo tree --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --edges normal
exit 0
fi
[[ $# == 0 ]] || { echo 'Usage: scripts/test-cuda-driver-bootstrap.sh [--inside]' >&2; exit 2; }
staging="$(mktemp -d "${TMPDIR:-/tmp}/leleka-cuda-bootstrap.XXXXXX")"
container=''
setup_container=''
fixture_image=''
cleanup() {
local result=$? failed=0
set +e
if [[ -n "$container" ]]; then docker rm -f "$container" >/dev/null || failed=1; fi
if [[ -n "$setup_container" ]]; then docker rm -f "$setup_container" >/dev/null || failed=1; fi
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
exit "$result"
}
trap cleanup EXIT
mkdir -p "$staging/src/crates" "$staging/src/scripts"
cp -R "${repo_root}/crates/cuda-driver" "$staging/src/crates/"
cp "${BASH_SOURCE[0]}" "$staging/src/scripts/test-cuda-driver-bootstrap.sh"
{ printf '[workspace]\nresolver = "3"\nmembers = ["crates/cuda-driver"]\n\n';
sed -n '/^\[workspace.package\]/,$p' "${repo_root}/Cargo.toml"; } > "$staging/src/Cargo.toml"
# Only the already-approved pinned libc registry archive is admitted as a dependency.
libc_archive=''
for candidate in "${CARGO_HOME:-${HOME}/.cargo}"/registry/cache/*/libc-0.2.190.crate; do
if [[ -f "$candidate" ]]; then libc_archive="$candidate"; break; fi
done
[[ -n "$libc_archive" ]]
python3 - "$libc_archive" "$staging/src" "${repo_root}/Cargo.lock" <<'PYVENDOR'
import hashlib,json,pathlib,sys,tarfile
archive,root,lock=map(pathlib.Path,sys.argv[1:])
expected='ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78'
assert hashlib.sha256(archive.read_bytes()).hexdigest()==expected
rows=lock.read_text().split('[[package]]')
packages=[row for row in rows[1:] if '\nname = "leleka-cuda-driver"\n' in row or '\nname = "libc"\n' in row]
assert len(packages)==2
assert 'checksum = "'+expected+'"' in ''.join(packages)
(root/'Cargo.lock').write_text('version = 4\n'+''.join('[[package]]'+row for row in packages))
vendor=root/'vendor'/'libc-0.2.190'
checksums={}
with tarfile.open(archive) as source:
for member in source:
path=pathlib.PurePosixPath(member.name)
assert path.parts[0]=='libc-0.2.190' and '..' not in path.parts and not path.is_absolute()
if member.isdir():continue
assert member.isfile()
relative=pathlib.Path(*path.parts[1:]);destination=vendor/relative
destination.parent.mkdir(parents=True,exist_ok=True)
data=source.extractfile(member).read();destination.write_bytes(data)
checksums[relative.as_posix()]=hashlib.sha256(data).hexdigest()
(vendor/'.cargo-checksum.json').write_text(json.dumps({'files':checksums,'package':expected}))
(root/'.cargo').mkdir()
(root/'.cargo'/'config.toml').write_text('[source.crates-io]\nreplace-with = "vendored-sources"\n[source.vendored-sources]\ndirectory = "vendor"\n')
print('Approved libc registry archive SHA256 '+expected+'; exact files vendor-verified by Cargo')
PYVENDOR
chmod -R a+rX "$staging/src"
docker pull "$image" >/dev/null
docker image inspect "$image" --format 'Pinned CPU base {{.Id}} architecture={{.Architecture}}'
# Rust official image lacks optional lint/format components. Provision only these
# verified pinned-toolchain components in a disposable setup container; runtime
# tests run later with network disabled and zero capabilities/non-root.
setup_container="$(docker create --runtime runc --cap-drop ALL --security-opt no-new-privileges \
--network bridge --memory 1536m --cpus 2 --pids-limit 128 "$image" \
bash -c 'for d in /dev/nvidia* /dev/dri/*; do [[ ! -e "$d" ]] || exit 1; done; rustup component add rustfmt clippy')"
docker start -a "$setup_container"
[[ "$(docker inspect "$setup_container" --format '{{.State.ExitCode}}')" == 0 ]]
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}}'
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)"
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 "CPU mock container: $configuration"
docker cp "$staging/src/." "$container:/src"
docker start "$container" >/dev/null
docker exec "$container" bash /src/scripts/test-cuda-driver-bootstrap.sh --inside