mesh-llm-native-runtime 0.75.0

Native runtime manifest, selection, and cache policy for Mesh LLM
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use crate::{NativeRuntimeManifest, manifest::NATIVE_RUNTIME_MANIFEST_FILE};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::{
    fs,
    path::{Path, PathBuf},
};

/// Relative path of the hardware benchmark executable shipped by GPU runtimes.
///
/// The manifest checksum must include this path before the executable is
/// selected or run. CPU and Vulkan runtimes intentionally do not provide it.
#[cfg(target_os = "windows")]
pub const GPU_BENCHMARK_TOOL_PATH: &str = "tools/mesh-llm-gpu-benchmark.exe";
#[cfg(not(target_os = "windows"))]
pub const GPU_BENCHMARK_TOOL_PATH: &str = "tools/mesh-llm-gpu-benchmark";

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct NativeRuntimeCacheRoot {
    pub path: PathBuf,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct InstalledNativeRuntime {
    pub mesh_version: String,
    pub native_runtime_id: String,
    pub flavor: String,
    pub path: PathBuf,
    pub manifest: NativeRuntimeManifest,
}

impl InstalledNativeRuntime {
    /// Resolve the manifest-verified GPU benchmark helper inside this runtime.
    pub fn gpu_benchmark_tool(&self) -> Result<PathBuf> {
        if !self
            .manifest
            .runtime
            .tools
            .contains_key(GPU_BENCHMARK_TOOL_PATH)
        {
            anyhow::bail!(
                "native runtime {} does not provide the GPU benchmark tool",
                self.native_runtime_id
            );
        }
        let path = self.path.join(GPU_BENCHMARK_TOOL_PATH);
        if !path.is_file() {
            anyhow::bail!(
                "native runtime GPU benchmark tool is missing: {}",
                path.display()
            );
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;

            if fs::metadata(&path)?.permissions().mode() & 0o111 == 0 {
                anyhow::bail!(
                    "native runtime GPU benchmark tool is not executable: {}",
                    path.display()
                );
            }
        }
        Ok(path)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NativeRuntimePruneMode {
    KeepActiveAndPrevious,
    ActiveOnly,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct CachePrunePlan {
    #[serde(default)]
    pub remove_dirs: Vec<PathBuf>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NativeRuntimeCache {
    root: PathBuf,
}

impl NativeRuntimeCache {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self { root: root.into() }
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn runtime_dir(&self, mesh_version: &str, native_runtime_id: &str) -> PathBuf {
        self.root.join(mesh_version).join(native_runtime_id)
    }

    pub fn installed(&self) -> Result<Vec<InstalledNativeRuntime>> {
        let mut installed = Vec::new();
        if !self.root.exists() {
            return Ok(installed);
        }
        for version_entry in fs::read_dir(&self.root)
            .with_context(|| format!("read native runtime cache {}", self.root.display()))?
        {
            let version_entry = version_entry?;
            if !version_entry.file_type()?.is_dir() {
                continue;
            }
            installed.extend(installed_in_version_dir(&version_entry.path())?);
        }
        installed.sort_by(|left, right| {
            (&left.mesh_version, &left.native_runtime_id)
                .cmp(&(&right.mesh_version, &right.native_runtime_id))
        });
        Ok(installed)
    }

    /// Returns strictly validated runtimes for one MeshLLM version.
    ///
    /// TODO(issue #1162): Remove this resolver-specific compatibility boundary
    /// once the oldest supported upgrade path no longer contains pre-checksum
    /// runtime caches, if full-cache resolver enumeration is safe again.
    pub(crate) fn installed_for_version(
        &self,
        mesh_version: &str,
    ) -> Result<Vec<InstalledNativeRuntime>> {
        installed_in_version_dir(&self.root.join(mesh_version))
    }

    pub fn find_installed(
        &self,
        mesh_version: &str,
        native_runtime_id: &str,
    ) -> Result<Option<InstalledNativeRuntime>> {
        let dir = self.runtime_dir(mesh_version, native_runtime_id);
        if !dir.join(NATIVE_RUNTIME_MANIFEST_FILE).exists() {
            return Ok(None);
        }
        installed_runtime_from_dir(&dir)
    }

    pub fn install_from_dir(&self, source_dir: &Path) -> Result<InstalledNativeRuntime> {
        let manifest = NativeRuntimeManifest::read_from_dir(source_dir)?;
        manifest.validate()?;
        let mesh_version = manifest
            .runtime
            .mesh_version
            .as_deref()
            .unwrap_or("unknown");
        let target = self.runtime_dir(mesh_version, manifest.runtime.native_runtime_id());
        if target.exists() {
            fs::remove_dir_all(&target)
                .with_context(|| format!("replace native runtime {}", target.display()))?;
        }
        copy_dir_recursive(source_dir, &target)?;
        installed_runtime_from_dir(&target)?.context("installed native runtime manifest missing")
    }

    pub fn remove(&self, mesh_version: &str, native_runtime_id: &str) -> Result<bool> {
        let dir = self.runtime_dir(mesh_version, native_runtime_id);
        if !dir.exists() {
            return Ok(false);
        }
        fs::remove_dir_all(&dir)
            .with_context(|| format!("remove native runtime {}", dir.display()))?;
        Ok(true)
    }

    pub fn prune_plan(
        &self,
        active_mesh_version: &str,
        mode: NativeRuntimePruneMode,
    ) -> Result<CachePrunePlan> {
        let mut versions = self.installed_versions()?;
        versions.sort();
        let previous = match mode {
            NativeRuntimePruneMode::ActiveOnly => None,
            NativeRuntimePruneMode::KeepActiveAndPrevious => versions
                .iter()
                .rfind(|version| version.as_str() != active_mesh_version)
                .cloned(),
        };
        let remove_dirs = versions
            .into_iter()
            .filter(|version| version != active_mesh_version)
            .filter(|version| Some(version) != previous.as_ref())
            .map(|version| self.root.join(version))
            .collect();
        Ok(CachePrunePlan { remove_dirs })
    }

    pub fn prune(
        &self,
        active_mesh_version: &str,
        mode: NativeRuntimePruneMode,
    ) -> Result<CachePrunePlan> {
        let plan = self.prune_plan(active_mesh_version, mode)?;
        for dir in &plan.remove_dirs {
            if dir.exists() {
                fs::remove_dir_all(dir)
                    .with_context(|| format!("remove native runtime cache {}", dir.display()))?;
            }
        }
        Ok(plan)
    }

    fn installed_versions(&self) -> Result<Vec<String>> {
        if !self.root.exists() {
            return Ok(Vec::new());
        }
        let mut versions = Vec::new();
        for entry in fs::read_dir(&self.root)
            .with_context(|| format!("read native runtime cache {}", self.root.display()))?
        {
            let entry = entry?;
            if entry.file_type()?.is_dir() {
                versions.push(entry.file_name().to_string_lossy().to_string());
            }
        }
        Ok(versions)
    }
}

pub fn native_runtime_cache_root(base_cache_dir: &Path) -> PathBuf {
    base_cache_dir.join("mesh-llm").join("native-runtimes")
}

fn installed_runtime_from_dir(dir: &Path) -> Result<Option<InstalledNativeRuntime>> {
    if !dir.join(NATIVE_RUNTIME_MANIFEST_FILE).exists() {
        return Ok(None);
    }
    let manifest = NativeRuntimeManifest::read_from_dir(dir)?;
    let mesh_version = manifest
        .runtime
        .mesh_version
        .clone()
        .unwrap_or_else(|| "unknown".to_string());
    Ok(Some(InstalledNativeRuntime {
        mesh_version,
        native_runtime_id: manifest.runtime.id.clone(),
        flavor: manifest.runtime.backend.kind.to_string(),
        path: dir.to_path_buf(),
        manifest,
    }))
}

fn installed_in_version_dir(version_dir: &Path) -> Result<Vec<InstalledNativeRuntime>> {
    let mut installed = Vec::new();
    if !version_dir.is_dir() {
        return Ok(installed);
    }
    for runtime_entry in fs::read_dir(version_dir)
        .with_context(|| format!("read native runtime cache {}", version_dir.display()))?
    {
        let runtime_entry = runtime_entry?;
        if !runtime_entry.file_type()?.is_dir() {
            continue;
        }
        if let Some(runtime) = installed_runtime_from_dir(&runtime_entry.path())? {
            installed.push(runtime);
        }
    }
    installed.sort_by(|left, right| left.native_runtime_id.cmp(&right.native_runtime_id));
    Ok(installed)
}

fn copy_dir_recursive(source: &Path, target: &Path) -> Result<()> {
    fs::create_dir_all(target).with_context(|| format!("create {}", target.display()))?;
    for entry in fs::read_dir(source).with_context(|| format!("read {}", source.display()))? {
        let entry = entry?;
        let source_path = entry.path();
        let target_path = target.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_dir_recursive(&source_path, &target_path)?;
        } else {
            fs::copy(&source_path, &target_path).with_context(|| {
                format!(
                    "copy {} to {}",
                    source_path.display(),
                    target_path.display()
                )
            })?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        NativeRuntimeArtifact, NativeRuntimeBackend, NativeRuntimeManifest, NativeRuntimePlatform,
    };

    fn write_runtime(dir: &Path, version: &str, id: &str) {
        fs::create_dir_all(dir.join("lib")).unwrap();
        fs::write(dir.join("lib/libmeshllm_ffi.so"), b"native runtime").unwrap();
        let manifest = NativeRuntimeManifest {
            runtime: NativeRuntimeArtifact {
                id: id.to_string(),
                mesh_version: Some(version.to_string()),
                skippy_abi: "0.1.25".to_string(),
                platform: NativeRuntimePlatform {
                    os: "linux".to_string(),
                    arch: "x86_64".to_string(),
                    target: None,
                },
                backend: NativeRuntimeBackend::cpu(),
                rank: 0,
                libraries: vec!["lib/libmeshllm_ffi.so".to_string()],
                files: Default::default(),
                tools: Default::default(),
                url: None,
                sha256: None,
                signature: None,
            },
        };
        manifest.write_to_dir(dir).unwrap();
    }

    #[test]
    fn installs_bundle_runtime_into_versioned_cache() {
        let temp = tempfile::tempdir().unwrap();
        let source = temp.path().join("source");
        write_runtime(&source, "0.68.0", "meshllm-native-linux-x86_64-cpu");

        let cache = NativeRuntimeCache::new(temp.path().join("cache"));
        let installed = cache.install_from_dir(&source).unwrap();

        assert_eq!(installed.mesh_version, "0.68.0");
        assert!(installed.path.ends_with("meshllm-native-linux-x86_64-cpu"));
    }

    #[test]
    fn installed_for_version_ignores_legacy_cache_versions() {
        let temp = tempfile::tempdir().unwrap();
        let cache = NativeRuntimeCache::new(temp.path().join("cache"));
        write_runtime(
            &cache.runtime_dir("0.75.0", "meshllm-native-linux-x86_64-cpu"),
            "0.75.0",
            "meshllm-native-linux-x86_64-cpu",
        );

        let legacy = cache.runtime_dir("0.74.0", "meshllm-native-linux-x86_64-cpu");
        fs::create_dir_all(legacy.join("lib")).unwrap();
        fs::write(legacy.join("lib/libmeshllm_ffi.so"), b"legacy runtime").unwrap();
        fs::write(
            legacy.join(NATIVE_RUNTIME_MANIFEST_FILE),
            r#"{
  "runtime": {
    "id": "meshllm-native-linux-x86_64-cpu",
    "mesh_version": "0.74.0",
    "skippy_abi": "0.1.25",
    "platform": {"os": "linux", "arch": "x86_64"},
    "backend": {"kind": "cpu"},
    "libraries": ["lib/libmeshllm_ffi.so"]
  }
}"#,
        )
        .unwrap();

        let installed = cache.installed_for_version("0.75.0").unwrap();

        assert_eq!(installed.len(), 1);
        assert_eq!(installed[0].mesh_version, "0.75.0");
        assert!(cache.installed().is_err());
    }

    #[test]
    fn installed_for_version_ignores_file_at_version_path() {
        let temp = tempfile::tempdir().unwrap();
        let cache = NativeRuntimeCache::new(temp.path().join("cache"));
        fs::create_dir_all(cache.root()).unwrap();
        fs::write(cache.root().join("0.75.0"), b"partial cache artifact").unwrap();

        let installed = cache.installed_for_version("0.75.0").unwrap();

        assert!(installed.is_empty());
    }

    #[test]
    fn prune_keeps_active_and_previous_by_default() {
        let temp = tempfile::tempdir().unwrap();
        let cache = NativeRuntimeCache::new(temp.path().join("cache"));
        for version in ["0.67.0", "0.68.0", "0.69.0"] {
            write_runtime(
                &cache.runtime_dir(version, "meshllm-native-linux-x86_64-cpu"),
                version,
                "meshllm-native-linux-x86_64-cpu",
            );
        }

        let plan = cache
            .prune_plan("0.69.0", NativeRuntimePruneMode::KeepActiveAndPrevious)
            .unwrap();

        assert_eq!(plan.remove_dirs, vec![cache.root().join("0.67.0")]);
    }

    #[test]
    fn installed_runtime_exposes_load_plan() {
        let temp = tempfile::tempdir().unwrap();
        let source = temp.path().join("source");
        write_runtime(&source, "0.68.0", "meshllm-native-linux-x86_64-cpu");

        let cache = NativeRuntimeCache::new(temp.path().join("cache"));
        let installed = cache.install_from_dir(&source).unwrap();
        let plan = installed.load_plan().unwrap();

        assert_eq!(plan.native_runtime_id, "meshllm-native-linux-x86_64-cpu");
        assert_eq!(
            plan.libraries,
            vec![
                cache
                    .runtime_dir("0.68.0", "meshllm-native-linux-x86_64-cpu")
                    .join("lib/libmeshllm_ffi.so")
            ]
        );
    }

    #[cfg(unix)]
    #[test]
    fn gpu_benchmark_tool_must_be_declared_and_executable() {
        use std::os::unix::fs::PermissionsExt;

        let temp = tempfile::tempdir().unwrap();
        let source = temp.path().join("source");
        write_runtime(&source, "0.68.0", "meshllm-native-linux-x86_64-cuda12");

        let cache = NativeRuntimeCache::new(temp.path().join("cache"));
        let mut installed = cache.install_from_dir(&source).unwrap();
        let tool = installed.path.join(GPU_BENCHMARK_TOOL_PATH);
        fs::create_dir_all(tool.parent().unwrap()).unwrap();
        fs::write(&tool, b"benchmark tool").unwrap();
        installed
            .manifest
            .runtime
            .tools
            .insert(GPU_BENCHMARK_TOOL_PATH.to_string(), "0".repeat(64));

        let error = installed.gpu_benchmark_tool().unwrap_err();
        assert!(error.to_string().contains("not executable"));

        let mut permissions = fs::metadata(&tool).unwrap().permissions();
        permissions.set_mode(0o755);
        fs::set_permissions(&tool, permissions).unwrap();
        assert_eq!(installed.gpu_benchmark_tool().unwrap(), tool);
    }
}