Skip to content
22 changes: 20 additions & 2 deletions crates/mesh-llm-commands/src/runtime_native/formatters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,8 +357,26 @@ fn format_rejection(reason: &CandidateRejection) -> String {
CandidateRejection::CudaProfileMissing => {
"CUDA runtime requires CUDA, but no CUDA profile was detected".to_string()
}
CandidateRejection::CudaToolkitMajorMismatch { required } => {
format!("CUDA toolkit mismatch: runtime requires CUDA {required}")
CandidateRejection::CudaToolkitMajorMismatch {
required,
installed,
} => {
let installed = installed
.iter()
.map(|major| major.to_string())
.collect::<Vec<_>>()
.join(", ");
format!(
"CUDA toolkit mismatch: runtime requires CUDA {required}, host has CUDA {installed} installed"
)
}
CandidateRejection::CudaToolkitMajorAboveDriver {
required,
driver_max,
} => {
format!(
"CUDA driver too old: runtime requires CUDA {required}, driver supports up to CUDA {driver_max}"
)
}
CandidateRejection::CudaGpuArchUnsupported { supported } => {
format!(
Expand Down
53 changes: 51 additions & 2 deletions crates/mesh-llm-hardware-profile/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,24 +304,73 @@ fn detect_cuda_profile(gpus: &[HostGpuProfile]) -> Option<HostCudaProfile> {
toolkit_majors.insert(major);
}
if toolkit_majors.is_empty() {
toolkit_majors.extend(cuda_majors_from_nvidia_smi());
toolkit_majors.extend(installed_cuda_toolkit_majors());
}
// `nvidia-smi` reports the newest CUDA the driver supports, which is often
// ahead of the installed toolkit. Keep it separate so it is only used as an
// upper bound during runtime selection.
let driver_max_major = env_u32("MESH_LLM_CUDA_DRIVER_MAX_MAJOR")
.or_else(|| cuda_majors_from_nvidia_smi().into_iter().next_back());
let mut gpu_arches = env_string_set("MESH_LLM_CUDA_GPU_ARCHES");
gpu_arches.extend(gpus.iter().filter_map(|gpu| gpu.cuda_sm.clone()));
let has_cuda_label = gpus.iter().any(|gpu| {
let label = gpu.display_name.to_ascii_lowercase();
label.contains("nvidia") || label.contains("cuda")
});
if toolkit_majors.is_empty() && gpu_arches.is_empty() && !has_cuda_label {
if toolkit_majors.is_empty()
&& driver_max_major.is_none()
&& gpu_arches.is_empty()
&& !has_cuda_label
{
return None;
}
Some(HostCudaProfile {
toolkit_majors,
driver_max_major,
driver_version: std::env::var("MESH_LLM_CUDA_DRIVER_VERSION").ok(),
gpu_arches,
})
}

/// CUDA toolkit majors with runtime libraries actually present on this host.
///
/// Linux native runtimes link against `libcudart.so.<major>` without bundling
/// it, so this is the set that can really be loaded. Windows runtimes ship
/// their own copies and do not depend on this.
fn installed_cuda_toolkit_majors() -> BTreeSet<u32> {
let mut majors = BTreeSet::new();
if let Some(output) = command_output("ldconfig", &["-p"]) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Probe configured CUDA library roots too. ldconfig -p plus /usr/local/cuda-* misses toolkits installed under a custom prefix or exposed only through LD_LIBRARY_PATH/CUDA_HOME (for example Conda or /opt/cuda-12). On a host with libcudart.so.12 in one of those paths and a driver advertising CUDA 13, toolkit_majors stays empty and the resolver falls back to selecting cuda13—the load failure this PR is intended to prevent. Please include the loader/environment search paths (with the same complete-library validation) or explicitly handle this installation shape.

majors.extend(cuda_majors_from_soname_listing(&output));
}
for base in ["/usr/local/cuda", "/usr/local"] {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verify runtime libraries, not just the toolkit directory name. A /usr/local/cuda-* directory can exist without usable libcudart/libcublas/libcublasLt files (for example, a partial or stale installation). This code would then add the major even though ldconfig found no runtime library, and the resolver can select an unbundled Linux artifact that still fails at load time. The repository’s scripts/lib/cuda-toolkit.sh::cuda_toolkit_library_dir already requires all three libraries; please use equivalent file checks here before treating the major as installed.

let Ok(entries) = std::fs::read_dir(base) else {
continue;
};
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if let Some(rest) = name.strip_prefix("cuda-")
&& let Some(major) = leading_major_version(rest)
{
majors.insert(major);
}
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
majors
}

/// Extract CUDA majors from `libcudart.so.<major>` sonames in a listing.
fn cuda_majors_from_soname_listing(output: &str) -> BTreeSet<u32> {
let mut majors = BTreeSet::new();
for token in output.split_whitespace() {
if let Some(rest) = token.strip_prefix("libcudart.so.")
&& let Some(major) = leading_major_version(rest)
{
majors.insert(major);
}
}
majors
}

fn detect_rocm_profile(gpus: &[HostGpuProfile]) -> Option<HostRocmProfile> {
let mut gpu_arches = env_string_set("MESH_LLM_ROCM_GPU_ARCHES");
gpu_arches.extend(rocm::gpu_arches());
Expand Down
22 changes: 20 additions & 2 deletions crates/mesh-llm-native-runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,26 @@ let profile = HostRuntimeProfile {
`mesh-llm-hardware-profile` builds this profile for real hosts. It supports
explicit environment overrides for CI/release testing, including
`MESH_LLM_CUDA_TOOLKIT_MAJOR`, `MESH_LLM_CUDA_TOOLKIT_MAJORS`,
`MESH_LLM_CUDA_GPU_ARCHES`, `MESH_LLM_ROCM_GPU_ARCHES`, and
`MESH_LLM_VULKAN_AVAILABLE`.
`MESH_LLM_CUDA_DRIVER_MAX_MAJOR`, `MESH_LLM_CUDA_GPU_ARCHES`,
`MESH_LLM_ROCM_GPU_ARCHES`, and `MESH_LLM_VULKAN_AVAILABLE`.

### CUDA toolkit vs driver

`toolkit_majors` and `driver_max_major` are deliberately separate:

- `toolkit_majors` — CUDA majors whose runtime libraries are actually installed
(probed from `libcudart.so.<major>` sonames and `/usr/local/cuda-<version>`).
- `driver_max_major` — the newest CUDA the installed driver supports, from
`nvidia-smi`. This is an upper bound only.

Linux native runtimes link `libcudart`/`libcublas` without bundling them, so
they can only load when a matching toolkit major is installed. Windows runtimes
ship their own copies and are self contained, so they are accepted on any driver
new enough to run them.

Conflating the two selects a runtime the host cannot load. A CUDA 13 driver with
a CUDA 12 toolkit must still choose the cuda12 runtime, otherwise startup fails
with `libcudart.so.13: cannot open shared object file`.

## Resolution

Expand Down
8 changes: 8 additions & 0 deletions crates/mesh-llm-native-runtime/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,16 @@ pub struct HostGpuProfile {

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct HostCudaProfile {
/// CUDA toolkit majors whose runtime libraries are actually installed on
/// this host (for example `libcudart.so.12`). A runtime that does not ship
/// its own CUDA libraries can only load if its major appears here.
#[serde(default)]
pub toolkit_majors: BTreeSet<u32>,
/// Highest CUDA major the installed driver supports, as reported by
/// `nvidia-smi`. This is an upper bound, not evidence that a matching
/// toolkit is installed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub driver_max_major: Option<u32>,
Comment on lines +38 to +42

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Update the HostCudaProfile Rust example.

Line 42 adds a required struct field. The example in crates/mesh-llm-native-runtime/README.md lines 127-131 omits it and cannot compile. Add driver_max_major: None to that literal.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/mesh-llm-native-runtime/src/host.rs` around lines 38 - 42, Add
driver_max_major: None to the HostCudaProfile struct literal in the README
example so it matches the required field and compiles.

#[serde(default, skip_serializing_if = "Option::is_none")]
pub driver_version: Option<String>,
#[serde(default)]
Expand Down
147 changes: 139 additions & 8 deletions crates/mesh-llm-native-runtime/src/resolver.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{
HostRuntimeProfile, NativeRuntimeArtifact, NativeRuntimeBackendKind, NativeRuntimeCache,
NativeRuntimeReleaseManifest,
HostCudaProfile, HostRuntimeProfile, NativeRuntimeArtifact, NativeRuntimeBackendKind,
NativeRuntimeCache, NativeRuntimeReleaseManifest,
};
use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
Expand All @@ -27,7 +27,8 @@ pub enum CandidateRejection {
TargetTripleMismatch { expected: String, actual: String },
BackendNotSupported { backend: NativeRuntimeBackendKind },
CudaProfileMissing,
CudaToolkitMajorMismatch { required: u32 },
CudaToolkitMajorMismatch { required: u32, installed: Vec<u32> },
CudaToolkitMajorAboveDriver { required: u32, driver_max: u32 },
CudaGpuArchUnsupported { supported: Vec<String> },
RocmProfileMissing,
RocmGpuArchUnsupported { supported: Vec<String> },
Expand Down Expand Up @@ -403,11 +404,7 @@ fn evaluate_cuda_requirements(
reasons.push(CandidateRejection::CudaProfileMissing);
return;
};
if !cuda.toolkit_majors.contains(&requirements.toolkit_major) {
reasons.push(CandidateRejection::CudaToolkitMajorMismatch {
required: requirements.toolkit_major,
});
}
evaluate_cuda_toolkit_major(artifact, requirements.toolkit_major, cuda, reasons);
if !requirements.gpu_arches.is_empty()
&& requirements
.gpu_arches
Expand All @@ -420,6 +417,57 @@ fn evaluate_cuda_requirements(
}
}

/// A CUDA runtime can only load if the CUDA runtime libraries it links against
/// are present. Runtimes that ship their own copies (Windows) are self
/// contained; runtimes that do not (Linux) need a matching toolkit major
/// installed on the host.
///
/// `nvidia-smi` reports the highest CUDA major the *driver* supports, which is
/// routinely newer than the installed toolkit. Treat it as an upper bound only,
/// so a CUDA 13 driver with a CUDA 12 toolkit still selects the cuda12 runtime.
fn evaluate_cuda_toolkit_major(
artifact: &NativeRuntimeArtifact,
required: u32,
cuda: &HostCudaProfile,
reasons: &mut Vec<CandidateRejection>,
) {
if let Some(driver_max) = cuda.driver_max_major
&& required > driver_max
{
reasons.push(CandidateRejection::CudaToolkitMajorAboveDriver {
required,
driver_max,
});
return;
}

if artifact_bundles_cuda_runtime(artifact) {
return;
}

// No installed-toolkit evidence at all: fall back to the driver bound
// rather than rejecting every CUDA runtime on the host.
if cuda.toolkit_majors.is_empty() {
return;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

if !cuda.toolkit_majors.contains(&required) {
reasons.push(CandidateRejection::CudaToolkitMajorMismatch {
required,
installed: cuda.toolkit_majors.iter().copied().collect(),
});
}
}

/// True when the artifact ships its own CUDA runtime libraries and therefore
/// does not depend on a host toolkit.
fn artifact_bundles_cuda_runtime(artifact: &NativeRuntimeArtifact) -> bool {
artifact.libraries.iter().any(|library| {
let name = library.rsplit('/').next().unwrap_or(library).to_lowercase();
name.starts_with("cudart") || name.starts_with("libcudart")
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

fn evaluate_rocm_requirements(
artifact: &NativeRuntimeArtifact,
profile: &HostRuntimeProfile,
Expand Down Expand Up @@ -542,6 +590,7 @@ mod tests {
gpus: Vec::new(),
cuda: Some(HostCudaProfile {
toolkit_majors: BTreeSet::from([12]),
driver_max_major: Some(12),
driver_version: None,
gpu_arches: BTreeSet::from(["sm_90".to_string()]),
}),
Expand Down Expand Up @@ -635,6 +684,88 @@ mod tests {
);
}

/// A CUDA 13 driver with only a CUDA 12 toolkit installed must still select
/// the cuda12 runtime. Linux runtimes do not bundle `libcudart`, so
/// selecting cuda13 here fails at load with
/// `libcudart.so.13: cannot open shared object file`.
#[test]
fn newer_driver_with_older_toolkit_selects_installed_toolkit_runtime() {
let mut host = profile();
let cuda = host.cuda.as_mut().unwrap();
cuda.toolkit_majors = BTreeSet::from([12]);
cuda.driver_max_major = Some(13);

let manifest = NativeRuntimeReleaseManifest {
mesh_version: "0.68.0".to_string(),
skippy_abi: "0.1.25".to_string(),
artifacts: vec![
cuda_runtime("meshllm-runtime-linux-x86_64-cuda12", 12, &["sm_90"]),
cuda_runtime("meshllm-runtime-linux-x86_64-cuda13", 13, &["sm_90"]),
],
};

let selected =
select_native_runtime(&manifest, &host, "0.68.0", &RuntimeSelection::Recommended)
.unwrap();

assert_eq!(selected.artifact.id, "meshllm-runtime-linux-x86_64-cuda12");
}

/// Runtimes that ship their own CUDA libraries (Windows) do not depend on a
/// host toolkit, so a newer driver must not reject them. Regression test for
/// the silent Vulkan fallback in #1127.
#[test]
fn self_contained_cuda_runtime_is_accepted_on_newer_driver() {
let mut host = profile();
let cuda = host.cuda.as_mut().unwrap();
cuda.toolkit_majors = BTreeSet::new();
cuda.driver_max_major = Some(13);

let mut bundled = cuda_runtime("meshllm-runtime-windows-x86_64-cuda12", 12, &["sm_90"]);
bundled.libraries.push("lib/cudart64_12.dll".to_string());

let manifest = NativeRuntimeReleaseManifest {
mesh_version: "0.68.0".to_string(),
skippy_abi: "0.1.25".to_string(),
artifacts: vec![bundled],
};

let selected =
select_native_runtime(&manifest, &host, "0.68.0", &RuntimeSelection::Recommended)
.unwrap();

assert_eq!(
selected.artifact.id,
"meshllm-runtime-windows-x86_64-cuda12"
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// With no installed-toolkit evidence at all, fall back to the driver bound
/// rather than rejecting every CUDA runtime.
#[test]
fn missing_toolkit_evidence_falls_back_to_driver_bound() {
let mut host = profile();
let cuda = host.cuda.as_mut().unwrap();
cuda.toolkit_majors = BTreeSet::new();
cuda.driver_max_major = Some(12);

let manifest = NativeRuntimeReleaseManifest {
mesh_version: "0.68.0".to_string(),
skippy_abi: "0.1.25".to_string(),
artifacts: vec![cuda_runtime(
"meshllm-runtime-linux-x86_64-cuda12",
12,
&["sm_90"],
)],
};

let selected =
select_native_runtime(&manifest, &host, "0.68.0", &RuntimeSelection::Recommended)
.unwrap();

assert_eq!(selected.artifact.id, "meshllm-runtime-linux-x86_64-cuda12");
}

#[test]
fn unsupported_cuda_gpu_arch_is_rejected() {
let manifest = NativeRuntimeReleaseManifest {
Expand Down
Loading