rigspark-runtime 3.0.7

Hardware detection, backend adapters, lifecycle, memory and harness runtime for rigspark.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use rigspark_core::{
    catalog::require,
    sizing::{CpuArch, Gpu, GpuVendor, Hardware, Platform, ValidationError},
};
use serde::Deserialize;
use serde_json::{Value, json};
use std::{process::Stdio, time::Duration};
use tokio::{io::AsyncReadExt, process::Command};

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Controller {
    vendor: String,
    vram: Option<f64>,
    vram_dynamic: Option<bool>,
    #[serde(default)]
    shared_memory: Option<bool>,
}
#[derive(Debug, Deserialize)]
struct Disk {
    mount: String,
    available: f64,
}
#[derive(Debug, Deserialize)]
struct Snapshot {
    arch: String,
    platform: String,
    total: f64,
    available: Option<f64>,
    free: f64,
    #[serde(default)]
    controllers: Vec<Controller>,
    #[serde(default)]
    disks: Vec<Disk>,
    #[serde(default, rename = "unifiedMemory")]
    unified_memory: Option<bool>,
}

fn vendor(value: &str) -> GpuVendor {
    let value = value.to_lowercase();
    let words: Vec<&str> = value.split(|ch: char| !ch.is_alphanumeric()).collect();
    if value.contains("nvidia") {
        GpuVendor::Nvidia
    } else if value.contains("apple") {
        GpuVendor::Apple
    } else if value.contains("amd")
        || value.contains("advanced micro")
        || value.contains("radeon")
        || words.contains(&"ati")
    {
        GpuVendor::Amd
    } else if value.contains("intel") || words.contains(&"arc") {
        GpuVendor::Intel
    } else {
        GpuVendor::None
    }
}
pub fn validate_hardware(hardware: &Hardware) -> Result<(), ValidationError> {
    let safe = |value: f64, min: f64| {
        value.is_finite() && value >= min && value <= 9007199254740991.0 && value.fract() == 0.0
    };
    require(
        safe(hardware.total_ram_bytes, 1.0)
            && safe(hardware.free_ram_bytes, 1.0)
            && safe(hardware.free_disk_bytes, 0.0)
            && hardware.gpu.iter().all(|gpu| safe(gpu.vram_bytes, 0.0)),
        "invalid hardware measurements",
    )
}
pub fn map_snapshot(value: &Value) -> Result<Hardware, ValidationError> {
    let raw: Snapshot = serde_json::from_value(value.clone())
        .map_err(|error| ValidationError(error.to_string()))?;
    let arch = match raw.arch.to_lowercase().as_str() {
        "x64" | "x86_64" | "amd64" => CpuArch::X64,
        "arm64" | "aarch64" => CpuArch::Arm64,
        _ => return Err(ValidationError("unsupported CPU architecture".into())),
    };
    let platform = match raw.platform.as_str() {
        "darwin" => Platform::Darwin,
        "linux" => Platform::Linux,
        "win32" => Platform::Win32,
        _ => return Err(ValidationError("unsupported platform".into())),
    };
    let disks: Vec<_> = raw
        .disks
        .iter()
        .filter(|disk| disk.available.is_finite() && disk.available >= 0.0)
        .collect();
    let root = disks.iter().find(|disk| {
        disk.mount == "/"
            || (disk.mount.len() >= 2
                && disk.mount.len() <= 3
                && disk.mount.as_bytes()[0].is_ascii_alphabetic()
                && disk.mount.as_bytes()[1] == b':'
                && (disk.mount.len() == 2 || disk.mount.ends_with('\\')))
    });
    let free_disk = root.map_or_else(
        || {
            disks
                .iter()
                .map(|disk| disk.available.round())
                .fold(0.0_f64, f64::max)
        },
        |disk| disk.available.round(),
    );
    let gpu = raw
        .controllers
        .iter()
        .map(|controller| {
            let vendor = vendor(&controller.vendor);
            let mib = controller
                .vram
                .filter(|value| value.is_finite() && *value > 0.0)
                .unwrap_or(0.0);
            let bytes = if vendor == GpuVendor::None
                || (vendor == GpuVendor::Intel && controller.vram_dynamic != Some(false))
            {
                0.0
            } else {
                (mib * 1048576.0).round()
            };
            Gpu {
                vendor,
                vram_bytes: bytes,
            }
        })
        .collect();
    // NVIDIA Grace/Jetson SoCs report no dedicated framebuffer; their GPU shares system memory.
    let shared_soc = arch == CpuArch::Arm64
        && raw.controllers.iter().any(|controller| {
            controller.shared_memory == Some(true)
                && vendor(&controller.vendor) == GpuVendor::Nvidia
        });
    let hardware = Hardware {
        arch,
        platform,
        total_ram_bytes: raw.total.round(),
        free_ram_bytes: raw
            .available
            .filter(|value| value.is_finite() && *value > 0.0)
            .unwrap_or(raw.free)
            .round(),
        gpu,
        free_disk_bytes: free_disk,
        unified_memory: (raw.unified_memory == Some(true) || shared_soc).then_some(true),
    };
    validate_hardware(&hardware)?;
    Ok(hardware)
}

pub fn detect_with(
    probe: impl FnOnce() -> Result<Value, String>,
    fallback: &Hardware,
) -> Result<(Hardware, Vec<String>), ValidationError> {
    match probe()
        .map_err(ValidationError)
        .and_then(|value| map_snapshot(&value))
    {
        Ok(hardware) => Ok((hardware, vec![])),
        Err(error) => {
            let mut hardware = fallback.clone();
            hardware.gpu.clear();
            hardware.free_disk_bytes = 1099511627776.0;
            validate_hardware(&hardware)?;
            Ok((
                hardware,
                vec![format!(
                    "hardware detection fallback: {error}; disk availability uses the legacy sentinel, not a measurement"
                )],
            ))
        }
    }
}

pub fn parse_gpu_output(platform: &str, raw: &str) -> Result<Vec<Value>, ValidationError> {
    if platform == "linux" {
        return raw
            .lines()
            .filter(|line| !line.trim().is_empty())
            .map(|line| {
                let (name, memory) = line
                    .rsplit_once(',')
                    .ok_or_else(|| ValidationError("invalid NVIDIA memory reading".into()))?;
                if ["[N/A]", "N/A", "[Not Supported]"].contains(&memory.trim()) {
                    return Ok(json!({"vendor":name.trim(),"vram":null,"vramDynamic":true,"sharedMemory":true}));
                }
                let mib = memory
                    .trim()
                    .parse::<f64>()
                    .map_err(|_| ValidationError("invalid NVIDIA VRAM".into()))?;
                require(mib.is_finite() && mib > 0.0, "invalid NVIDIA VRAM")?;
                Ok(json!({"vendor":name.trim(),"vram":mib,"vramDynamic":false}))
            })
            .collect();
    }
    let value: Value =
        serde_json::from_str(raw).map_err(|error| ValidationError(error.to_string()))?;
    let entries = if platform == "darwin" {
        value["SPDisplaysDataType"]
            .as_array()
            .cloned()
            .ok_or_else(|| ValidationError("missing display controllers".into()))?
    } else if let Some(entries) = value.as_array() {
        entries.clone()
    } else if value.is_object() {
        vec![value]
    } else {
        return Err(ValidationError("invalid GPU response".into()));
    };
    entries.iter().map(|entry| {
        let name = entry[if platform == "darwin" { "sppci_model" } else { "Name" }].as_str().ok_or_else(|| ValidationError("missing GPU name".into()))?;
        let mib = if platform == "darwin" {
            let memory = entry["spdisplays_vram"].as_str().or(entry["spdisplays_vram_shared"].as_str());
            memory.and_then(|text| { let mut parts = text.split_whitespace(); let number = parts.next()?.parse::<f64>().ok()?; let unit = parts.next()?; match unit { "GB" => Some(number * 1024.0), "MB" => Some(number), _ => None } }).unwrap_or(0.0)
        } else { entry["AdapterRAM"].as_f64().unwrap_or(0.0) / 1048576.0 };
        Ok(json!({"vendor":name,"vram":mib,"vramDynamic": if vendor(name) == GpuVendor::Intel { Value::Null } else { json!(false) }}))
    }).collect()
}

pub async fn command_output(program: &str, args: &[&str]) -> Result<String, ValidationError> {
    let mut child = Command::new(program)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .kill_on_drop(true)
        .spawn()
        .map_err(|error| ValidationError(error.to_string()))?;
    let stdout = child
        .stdout
        .take()
        .ok_or_else(|| ValidationError("missing probe output".into()))?;
    let operation = async {
        let mut bytes = Vec::new();
        stdout
            .take(1048577)
            .read_to_end(&mut bytes)
            .await
            .map_err(|error| ValidationError(error.to_string()))?;
        require(
            bytes.len() <= 1048576,
            "hardware probe output exceeds 1 MiB",
        )?;
        let status = child
            .wait()
            .await
            .map_err(|error| ValidationError(error.to_string()))?;
        require(status.success(), "hardware probe command failed")?;
        String::from_utf8(bytes).map_err(|_| ValidationError("probe output is not UTF-8".into()))
    };
    tokio::time::timeout(Duration::from_secs(3), operation)
        .await
        .map_err(|_| ValidationError("hardware probe timed out".into()))?
}

pub async fn detect() -> Result<(Hardware, Vec<String>), ValidationError> {
    let platform = match std::env::consts::OS {
        "macos" => "darwin",
        "windows" => "win32",
        "linux" => "linux",
        _ => return Err(ValidationError("unsupported platform".into())),
    };
    let mut warnings = Vec::new();
    let gpu = match platform {
        "darwin" => command_output("/usr/sbin/system_profiler", &["SPDisplaysDataType", "-json"]).await,
        "win32" => command_output("powershell.exe", &["-NoProfile", "-NonInteractive", "-Command", "Get-CimInstance Win32_VideoController | Select-Object Name,AdapterRAM | ConvertTo-Json -Compress"]).await,
        _ => command_output("nvidia-smi", &["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"]).await,
    };
    let mut controllers = match gpu.and_then(|text| parse_gpu_output(platform, &text)) {
        Ok(gpus) => gpus,
        Err(error) => {
            warnings.push(format!(
                "GPU probe unavailable: {error}; dedicated VRAM unknown"
            ));
            vec![]
        }
    };
    if platform == "win32" {
        match command_output("nvidia-smi", &["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"]).await.and_then(|raw| parse_gpu_output("linux", &raw)) {
            Ok(precise) if !precise.is_empty() => controllers = merge_nvidia(controllers, precise),
            _ => warnings.push("Windows GPU memory uses WMI fallback; large dedicated VRAM values may be truncated".into()),
        }
    }
    if platform == "linux" {
        match linux_drm().and_then(|entries| map_linux_drm(&entries)) {
            Ok(entries) => controllers.extend(entries),
            Err(error) => warnings.push(format!("DRM GPU probe unavailable: {error}")),
        }
    }
    let measurements = tokio::task::spawn_blocking(|| {
        let mut system = sysinfo::System::new();
        system.refresh_memory();
        // macOS computes "important usage" capacity for sysinfo disks, which can take tens of seconds.
        #[cfg(unix)]
        let disks = rustix::fs::statvfs("/")
            .map(|stats| {
                vec![json!({"mount":"/","available":stats.f_bavail.saturating_mul(stats.f_frsize)})]
            })
            .unwrap_or_default();
        #[cfg(not(unix))]
        let disks = sysinfo::Disks::new_with_refreshed_list()
            .iter()
            .map(|disk| json!({"mount":disk.mount_point().to_string_lossy(),"available":disk.available_space()}))
            .collect::<Vec<_>>();
        (
            system.total_memory(),
            system.available_memory(),
            system.free_memory(),
            disks,
        )
    });
    let (total, available, free, disks) =
        tokio::time::timeout(Duration::from_secs(3), measurements)
            .await
            .map_err(|_| ValidationError("RAM/disk probe timed out".into()))?
            .map_err(|error| ValidationError(error.to_string()))?;
    let snapshot = json!({"arch":std::env::consts::ARCH,"platform":platform,"total":total,"available":available,"free":free,"controllers":controllers,"disks":disks,"unifiedMemory":(platform == "linux" && kfd_apu(&linux_kfd_nodes())).then_some(true)});
    let fallback = map_snapshot(
        &json!({"arch":std::env::consts::ARCH,"platform":platform,"total":total,"free":free.max(1),"controllers":[],"disks":[]}),
    )?;
    let (hardware, fallback_warnings) = detect_with(|| Ok(snapshot), &fallback)?;
    warnings.extend(fallback_warnings);
    Ok((hardware, warnings))
}

pub fn merge_nvidia(mut controllers: Vec<Value>, precise: Vec<Value>) -> Vec<Value> {
    controllers.retain(|entry| vendor(entry["vendor"].as_str().unwrap_or("")) != GpuVendor::Nvidia);
    controllers.extend(precise);
    controllers
}

/// A KFD topology node with both CPU cores and GPU SIMDs is an APU sharing system memory.
pub fn kfd_apu(nodes: &[String]) -> bool {
    nodes.iter().any(|properties| {
        let count = |key: &str| {
            properties.lines().find_map(|line| {
                let (name, value) = line.split_once(' ')?;
                (name == key)
                    .then(|| value.trim().parse::<u64>().ok())
                    .flatten()
            })
        };
        count("cpu_cores_count").is_some_and(|cores| cores > 0)
            && count("simd_count").is_some_and(|simds| simds > 0)
    })
}

fn linux_kfd_nodes() -> Vec<String> {
    use std::io::Read;
    let Ok(nodes) = std::fs::read_dir("/sys/class/kfd/kfd/topology/nodes") else {
        return vec![];
    };
    nodes
        .take(64)
        .filter_map(|node| {
            let mut text = String::new();
            std::fs::File::open(node.ok()?.path().join("properties"))
                .ok()?
                .take(65537)
                .read_to_string(&mut text)
                .ok()?;
            (text.len() <= 65536).then_some(text)
        })
        .collect()
}

pub fn map_linux_drm(entries: &[Value]) -> Result<Vec<Value>, ValidationError> {
    entries
        .iter()
        .map(|entry| {
            let id = entry["vendor"]
                .as_str()
                .ok_or_else(|| ValidationError("missing DRM vendor".into()))?;
            let vendor = match id.trim() {
                "0x1002" => "AMD",
                "0x8086" => "Intel",
                "0x10de" => "NVIDIA",
                _ => "unknown",
            };
            let bytes = match entry["bytes"].as_str() {
                Some(raw) => raw
                    .trim()
                    .parse::<u64>()
                    .map_err(|_| ValidationError("invalid DRM memory bytes".into()))?,
                None if entry["bytes"].is_null() => 0,
                _ => return Err(ValidationError("invalid DRM memory measurement".into())),
            };
            require(bytes <= 9007199254740991, "DRM memory exceeds safe range")?;
            Ok(json!({"vendor":vendor,"vram":bytes as f64 / 1048576.0,"vramDynamic":bytes == 0}))
        })
        .collect()
}

fn linux_drm() -> Result<Vec<Value>, ValidationError> {
    use std::io::Read;
    let read = |path: &std::path::Path| -> Option<String> {
        let mut text = String::new();
        std::fs::File::open(path)
            .ok()?
            .take(4097)
            .read_to_string(&mut text)
            .ok()?;
        (text.len() <= 4096).then_some(text)
    };
    let directories =
        std::fs::read_dir("/sys/class/drm").map_err(|error| ValidationError(error.to_string()))?;
    let mut entries = Vec::new();
    for entry in directories.take(256) {
        let entry = entry.map_err(|error| ValidationError(error.to_string()))?;
        let name = entry.file_name().to_string_lossy().into_owned();
        if !name.strip_prefix("card").is_some_and(|suffix| {
            !suffix.is_empty() && suffix.bytes().all(|byte| byte.is_ascii_digit())
        }) {
            continue;
        }
        let device = entry.path().join("device");
        let Some(vendor) = read(&device.join("vendor")) else {
            continue;
        };
        if vendor.trim() == "0x10de" {
            continue;
        }
        let bytes = read(&device.join("mem_info_vram_total"))
            .or_else(|| read(&device.join("lmem_total_bytes")));
        entries.push(json!({"vendor":vendor,"bytes":bytes}));
    }
    Ok(entries)
}