feat: gate explicit CUDA profiles before model provisioning

This commit is contained in:
Pavlo Ratushnyi
2026-10-04 19:17:25 +02:00
parent 606ce2b759
commit 710d3347c7
7 changed files with 277 additions and 32 deletions
+2
View File
@@ -99,6 +99,8 @@ jobs:
sha256sum strata-next-linux-x86_64-musl BUILD-PROVENANCE.txt ELF-AUDIT.txt > SHA256SUMS
- name: Static CLI model smoke
run: python3 scripts/smoke-static-cli.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Explicit GPU profile driver policy without GPU
run: python3 scripts/smoke-gpu-requirement.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Atomic pinned assets before native serving
run: python3 scripts/smoke-asset-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/strata-next
- name: Native GGUF pack preparation against upstream oracle
+20
View File
@@ -14,6 +14,8 @@ use crate::worker::WorkerConfig;
pub struct Config {
pub assets: Vec<crate::asset_bundle::AssetBundle>,
pub native_model: Option<crate::native_model::NativeModel>,
pub gpu_requirement: Option<crate::doctor::GpuRequirement>,
host_checked: bool,
pub shutdown_grace: Duration,
pub max_in_flight_requests: usize,
pub api_key: Option<std::sync::Arc<crate::auth::ApiKey>>,
@@ -29,6 +31,7 @@ struct FileConfig {
#[serde(default)]
assets: Vec<crate::asset_bundle::AssetBundle>,
native_model: Option<crate::native_model::NativeModel>,
gpu_requirement: Option<crate::doctor::GpuRequirement>,
shutdown_grace_s: Option<u64>,
max_in_flight_requests: Option<usize>,
api_key_file: Option<PathBuf>,
@@ -172,6 +175,9 @@ impl Config {
if worker.is_none() && tokenizer_dir.is_some() {
return Err("tokenizer_dir requires an engine executable".into());
}
if worker.is_none() && file.gpu_requirement.is_some() {
return Err("gpu_requirement requires an engine executable".into());
}
let model = optional_env("STRATA_MODEL_ID")?.or(file.model);
if model.as_ref().is_some_and(|id| {
id.is_empty()
@@ -193,6 +199,8 @@ impl Config {
Ok(Self {
assets: file.assets,
native_model: file.native_model,
gpu_requirement: file.gpu_requirement,
host_checked: false,
shutdown_grace: Duration::from_secs(shutdown_grace_s),
max_in_flight_requests,
api_key,
@@ -205,6 +213,7 @@ impl Config {
/// Complete acquisition/preparation before the listener or worker starts.
pub async fn provision(&mut self) -> Result<(), Box<dyn std::error::Error>> {
self.check_host().await?;
// Parse all manifests before any acquisition, including the source model.
if let Some(native) = &self.native_model {
crate::model::Manifest::load(&native.manifest).await?;
@@ -227,6 +236,17 @@ impl Config {
}
Ok(())
}
/// Point-in-time driver policy check; never creates a CUDA context.
pub async fn check_host(&mut self) -> Result<(), Box<dyn std::error::Error>> {
if let Some(requirement) = self.gpu_requirement
&& !self.host_checked
{
crate::doctor::check(requirement).await?;
self.host_checked = true;
}
Ok(())
}
}
fn optional_env(name: &str) -> Result<Option<String>, env::VarError> {
+105 -31
View File
@@ -1,50 +1,108 @@
//! Read-only Linux host checks for the CUDA 13.0 engine profile.
use std::{error::Error, fs, process::Command};
//! Read-only Linux driver-version checks for the explicit CUDA 13.0 GA profile.
use serde::{Deserialize, Serialize};
use std::{error::Error, fs, process::Stdio, time::Duration};
use tokio::{io::AsyncReadExt, process::Command, time::timeout};
const MIN_DRIVER: DriverVersion = DriverVersion(580, 65, 6);
const PROBE_LIMIT: u64 = 8192;
#[derive(Clone, Copy, Deserialize, Serialize)]
pub enum GpuRequirement {
#[serde(rename = "cuda-13.0-linux")]
Cuda13Linux,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct DriverVersion(u32, u32, u32);
pub fn report() -> Result<(), Box<dyn Error>> {
pub async fn report() -> Result<(), Box<dyn Error>> {
println!(
"platform: {} {}",
std::env::consts::OS,
std::env::consts::ARCH
);
if !cfg!(target_os = "linux") {
return Err("GPU deployment requires a Linux host".into());
}
let version = detect_driver()
.ok_or("NVIDIA driver was not found; install a compatible driver before GPU serving")?;
println!("NVIDIA driver: {}.{}.{}", version.0, version.1, version.2);
if version < MIN_DRIVER {
return Err(format!(
"NVIDIA driver {}.{}.{} is below the CUDA 13.0 GA minimum 580.65.06",
version.0, version.1, version.2
)
.into());
}
println!("CUDA 13.0 GA driver requirement: met (>=580.65.06)");
let version = check(GpuRequirement::Cuda13Linux).await?;
println!("NVIDIA driver: {version}");
println!(
"CUDA 13.0 GA profile driver floor: met (>=580.65.06); GPU/model readiness not checked"
);
Ok(())
}
fn detect_driver() -> Option<DriverVersion> {
if let Ok(version_file) = fs::read_to_string("/proc/driver/nvidia/version")
&& let Some(version) = parse_driver_version(&version_file)
{
return Some(version);
pub async fn check(_requirement: GpuRequirement) -> Result<String, Box<dyn Error>> {
if !cfg!(target_os = "linux") {
return Err("cuda-13.0-linux requires Linux; select a compatible host/profile".into());
}
let output = Command::new("nvidia-smi")
let version = match fs::read_to_string("/proc/driver/nvidia/version")
.ok()
.and_then(|s| parse_driver_version(&s))
{
Some(version) => version,
None => probe().await?,
};
if version < MIN_DRIVER {
return Err(format!("NVIDIA driver {}.{}.{} is below the cuda-13.0-linux profile floor 580.65.06; upgrade the host driver", version.0, version.1, version.2).into());
}
Ok(format!("{}.{}.{}", version.0, version.1, version.2))
}
async fn probe() -> Result<DriverVersion, Box<dyn Error>> {
let mut child = Command::new("nvidia-smi")
.args(["--query-gpu=driver_version", "--format=csv,noheader"])
.output()
.ok()?;
output
.status
.success()
.then(|| parse_driver_version(&String::from_utf8_lossy(&output.stdout)))
.flatten()
.stdin(Stdio::null())
.stderr(Stdio::null())
.stdout(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(
|_| "NVIDIA driver unavailable; install the host driver and make nvidia-smi accessible",
)?;
let result = timeout(Duration::from_secs(5), async {
let mut bytes = Vec::new();
child
.stdout
.take()
.ok_or("driver probe stdout unavailable")?
.take(PROBE_LIMIT + 1)
.read_to_end(&mut bytes)
.await
.map_err(|_| "driver probe output read failed")?;
if bytes.len() as u64 > PROBE_LIMIT {
return Err("driver probe output exceeded 8 KiB; check nvidia-smi");
}
let status = child.wait().await.map_err(|_| "driver probe wait failed")?;
if !status.success() {
return Err("NVIDIA driver query failed; check driver installation and nvidia-smi");
}
let text = std::str::from_utf8(&bytes).map_err(|_| "driver probe output was not UTF-8")?;
parse_csv(text).ok_or("NVIDIA driver version was missing or malformed; check nvidia-smi")
})
.await;
match result {
Ok(Ok(version)) => Ok(version),
error => {
let _ = child.kill().await;
let message = match error {
Ok(Err(message)) => message,
_ => "NVIDIA driver query timed out after 5 seconds; check host driver health",
};
Err(message.into())
}
}
}
fn parse_csv(text: &str) -> Option<DriverVersion> {
let versions = text
.lines()
.map(|line| {
let line = line.trim();
if !line.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
return None;
}
parse_driver_version(line)
})
.collect::<Option<Vec<_>>>()?;
versions.into_iter().min()
}
fn parse_driver_version(text: &str) -> Option<DriverVersion> {
@@ -62,6 +120,22 @@ fn parse_driver_version(text: &str) -> Option<DriverVersion> {
mod tests {
use super::*;
#[test]
fn csv_requires_only_versions_and_checks_the_oldest() {
assert_eq!(parse_csv("580.65.06\n600.1.0\n"), Some(MIN_DRIVER));
for invalid in [
"",
"580.65.06\n\n",
"580.65.06\nheader",
"580.65",
"580.65.06.1",
"x580.65.06",
"580.65.06 secret",
] {
assert_eq!(parse_csv(invalid), None, "{invalid:?}");
}
}
#[test]
fn driver_version_is_compared_numerically() {
assert_eq!(
+2 -1
View File
@@ -70,7 +70,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
[doctor] if doctor == "doctor" => {
doctor::report()?;
doctor::report().await?;
Ok(())
}
[model, action, flag, output]
@@ -777,6 +777,7 @@ fn print_tensor_index(path: &Path, hash: bool) -> Result<(), Box<dyn std::error:
async fn serve(config_path: Option<&Path>) -> Result<(), Box<dyn std::error::Error>> {
let mut config = Config::load_with_path(config_path)?;
config.check_host().await?;
let _embedded = match config.worker.as_mut() {
Some(worker) => {
let embedded = strata_control::embedded_engine::resolve(&worker.executable)?;
+2
View File
@@ -53,6 +53,8 @@ pub fn check(path: Option<&Path>) -> Result<serde_json::Value, &'static str> {
"readiness_checked": false,
"asset_bundles_configured": config.assets.len(),
"assets_verified": false,
"gpu_requirement": config.gpu_requirement,
"gpu_requirement_checked": false,
}))
}
+25
View File
@@ -524,6 +524,7 @@ preparation to `provision --config` and `serve --config`:
{
"bind": "127.0.0.1:8081",
"model": "qwen-flash-native",
"gpu_requirement": "cuda-13.0-linux",
"native_model": {
"manifest": "/srv/strata/manifests/source-v1.json",
"source_dir": "/srv/strata/models/source-v1",
@@ -570,3 +571,27 @@ without optional MTP. Full-model and clean-node GPU qualification remain open.
preparation and offline reuse with a synthetic worker, including corruption,
locking, conflicting config and previous-version preservation. It is a CPU
startup-order test, not an inference or model-quality result.
### Explicit GPU profile requirement
Set top-level `"gpu_requirement": "cuda-13.0-linux"` on CUDA 13.0 Linux
profiles. `provision` and `serve` check the host before fetching assets,
preparing a model, materializing an embedded engine, starting a worker, or
opening the HTTP listener. Unsupported OS, missing/unreadable driver, and a
version below this profile's conservative **580.65.06** floor fail with an
actionable error. The floor follows the Linux CUDA 13.0 GA toolkit driver in
[NVIDIA's release table](https://docs.nvidia.com/cuda/archive/13.0.0/cuda-toolkit-release-notes/index.html).
This is an explicit deployment policy, not a universal CUDA compatibility limit.
The check reads the kernel driver version, falling back to `nvidia-smi` when
unavailable. That subprocess has a five-second timeout and 8 KiB output limit;
it is killed and reaped on failure. Versions are compared numerically. No CUDA
context or inference request is created. `check-config` only reports the
requirement with `gpu_requirement_checked: false`; it never runs this probe.
Omitting the requirement preserves CPU/manual worker behavior. A requirement
without a worker, or an unknown requirement, is rejected.
A successful check does **not** qualify GPU architecture, free VRAM, model
quality, engine shared-library dependencies, MTP support, or a clean-node
real-model launch. Those remain separate release gates. Keep model/auxiliary
bundles pinned and use distinct versioned output directories as described above.
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""CPU fixtures for explicit CUDA driver policy. Never runs inference or CUDA."""
import json
import os
from pathlib import Path
import socket
import subprocess
import sys
import tempfile
import time
def main():
binary = str(Path(sys.argv[1]).resolve())
if sys.platform == 'linux' and Path('/proc/driver/nvidia/version').exists():
raise SystemExit('Requires an isolated CPU runner without an installed NVIDIA kernel driver')
with tempfile.TemporaryDirectory(prefix='strata-driver-gate-') as tmp:
root = Path(tmp).resolve()
probe = root / 'nvidia-smi'
marker = root / 'probe-called'
worker_marker = root / 'worker-called'
worker = root / 'worker'
worker.write_text(f'#!/bin/sh\n: > "{worker_marker}"\nexit 1\n')
worker.chmod(0o700)
path = root / 'config.json'
env = {'PATH': str(root)}
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
config = {'bind': f'127.0.0.1:{port}', 'engine': {'executable': str(worker)}}
count = 0
def run(command='provision', ok=False, contains=None, timeout=10):
nonlocal count
path.write_text(json.dumps(config))
started = time.monotonic()
result = subprocess.run([binary, command, '--config', str(path)], env=env,
capture_output=True, text=True, timeout=timeout)
assert (result.returncode == 0) == ok, (result.stdout, result.stderr)
if contains:
assert contains in result.stderr, result.stderr
assert not worker_marker.exists(), 'worker started before policy/asset checks'
assert not (root / 'output').exists()
assert not (root / '.output.strata-stage').exists()
with socket.socket() as sock:
assert sock.connect_ex(('127.0.0.1', port)) != 0, 'listener opened'
count += 1
return result, time.monotonic() - started
def fake(body):
marker.unlink(missing_ok=True)
probe.write_text(f'#!/bin/sh\nprintf called > "{marker}"\n{body}\n')
probe.chmod(0o700)
# CPU profiles do not query the driver. check-config stays read-only.
fake('exit 1')
run(ok=True)
assert not marker.exists()
config['gpu_requirement'] = 'cuda-13.0-linux'
result, _ = run('check-config', ok=True)
report = json.loads(result.stdout)
assert report['gpu_requirement'] == 'cuda-13.0-linux'
assert report['gpu_requirement_checked'] is False
assert not marker.exists()
config['gpu_requirement'] = 'unknown'
run()
config['gpu_requirement'] = 'cuda-13.0-linux'
engine = config.pop('engine')
run(contains='requires an engine executable')
config['engine'] = engine
# An absent manifest proves failure happens before asset acquisition.
config['assets'] = [{'manifest': str(root / 'absent.json'), 'directory': str(root / 'output')}]
if sys.platform != 'linux':
run(contains='requires Linux')
run('serve', contains='requires Linux')
assert not marker.exists()
print(f'{count} driver policy scenarios passed; Linux probe cases require hosted CPU runner')
return
probe.unlink()
run(contains='driver unavailable')
cases = [
("printf '579.99.99\\n'", 'below'),
("printf '580.65.05\\n'", 'below'),
("printf '580.65.06\\n580.1.0\\n'", 'below'),
("printf 'secret malformed output\\n'", 'malformed'),
("printf '580.65.06\\n'; exit 1", 'query failed'),
("printf ''", 'malformed'),
("printf '580.65.06\\nBAD\\n'", 'malformed'),
("i=0; while [ $i -lt 9000 ]; do printf x; i=$((i+1)); done", 'exceeded 8 KiB'),
]
for body, error in cases:
fake(body)
run(contains=error)
run('serve', contains=error)
assert marker.exists()
# Bounded probe is killed/reaped. exec keeps the PID unambiguous.
pid_path = root / 'probe.pid'
fake(f'printf "%s" "$$" > "{pid_path}"\nexec /bin/sleep 60')
_, elapsed = run(contains='timed out after 5 seconds')
assert 4.5 <= elapsed < 9, elapsed
pid = int(pid_path.read_text())
try:
os.kill(pid, 0)
except ProcessLookupError:
pass
else:
raise AssertionError('timed-out probe still alive or unreaped')
# Accepted versions proceed to manifest lookup, and no farther.
for version in ['580.65.06', '580.100.0', '600.1.0']:
fake(f"printf '{version}\\n'")
result, _ = run()
assert 'NVIDIA' not in result.stderr, result.stderr
assert marker.exists()
config.pop('assets')
run(ok=True)
config['assets'] = [{'manifest': str(root / 'absent.json'), 'directory': str(root / 'output')}]
print(f'{count} driver policy scenarios passed; CPU fixtures only, no GPU readiness claim')
if __name__ == '__main__':
main()