diff --git a/CHANGELOG.md b/CHANGELOG.md index 294696d8..d29fa324 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,8 @@ - A libbaseRT is judged by its engine ABI number: baseRT 0.4.0 and later state one (`baseRT_abi_version()`), and a library whose number equals the one this build was built for serves whatever its version says. A 0.3.x library states none and serves as the line that carried this ABI before it was numbered. The check at load still verifies every function; the model configuration is read by size from a library of 0.4.0 or later (`baseRT_get_config_into`), so the struct may grow without a new number, and by value with a size check from an older one. - `superfluid runtime install basert` picks an engine by the ABI number baseRT publishes beside each bundle (`basert-engine-abi-.txt`): the newest release with this build's number, or a 0.3.x engine, and another only with `--untested`. -- `superfluid compat [--json]` prints what this build was built for, and each release carries the same as `compat.json` beside its tarball, so a host can choose a release before downloading it. `superfluid runtimes --json` reports a ready runtime's `abi` and, for `basert`, `requires`. +- `superfluid compat [--json]` prints what this build was built and tested for, per runtime, and each release carries the same as `compat.json` beside its tarball, so a host can choose a release before downloading it: for basert the header version, the ABI number, the line accepted without one and the engines it installs on its own; for llama.cpp and MLX the upstream versions each shipped adapter installs on its own. An adapter declares its part with the `Runtime::compat` method, and its worker answers `compat --json`. `superfluid runtimes --json` reports a ready runtime's `abi` and, for `basert`, `requires`. +- `superfluid runtime versions [--json]` lists the versions an adapter installs on its own, newest first: which install on this machine and as what, and which are installed. `superfluid runtimes` gains an `INSTALLABLE` column, the newest such version here, and `installable` in its JSON. A worker answers `versions` from its recipe alone; the `Runtime::versions` method plans each tested version by default. - `superfluid serve` exits 4 when the runtime for the model is not installed or cannot run here, distinct from a usage error (2). - superfluid finds its workerd and adapters beside its real executable, so a symlink or a shim on `PATH` keeps the worker process. - [Hosting superfluid in another product](docs/serving/hosts.md) documents the contract a host builds on. diff --git a/crates/superfluid-adapters/superfluid-adapter-basert/src/lib.rs b/crates/superfluid-adapters/superfluid-adapter-basert/src/lib.rs index 1c1247af..bc52e89f 100644 --- a/crates/superfluid-adapters/superfluid-adapter-basert/src/lib.rs +++ b/crates/superfluid-adapters/superfluid-adapter-basert/src/lib.rs @@ -5,7 +5,7 @@ pub mod recipe; use std::path::Path; use std::sync::Arc; -use superfluid_adapter_kit::install::{Host, Plan, Request}; +use superfluid_adapter_kit::install::{Candidate, Host, Plan, Request}; use superfluid_adapter_kit::{Pull, PullOption}; use superfluid_adapter_kit::{ring_specs_for, Device, Format, Loaded, Probe, Runtime, RuntimeInfo, Tokenizer, TokenizerSource, WorkerArgs}; use superfluid_engine_ffi::{libbasert, FfiEngineConfig, NativeEngine, TokenizerHandle}; @@ -13,6 +13,16 @@ use superfluid_engine_ffi::{libbasert, FfiEngineConfig, NativeEngine, TokenizerH pub struct Basert; impl Runtime for Basert { + fn compat(&self) -> serde_json::Value { + let abi = libbasert::abi_built_for(); + serde_json::json!({ + "basert_version": libbasert::BUILT_FOR, + "abi": abi, + "unnumbered_minor": abi.and_then(libbasert::unnumbered_minor_for), + "pinned_engines": recipe::pinned().iter().map(|p| serde_json::json!({"version": p.version, "abi": p.abi})).collect::>(), + }) + } + fn info(&self) -> RuntimeInfo { RuntimeInfo { id: "basert", @@ -115,6 +125,11 @@ impl Runtime for Basert { fn plan(&self, req: &Request, host: &Host) -> Option, String>> { Some(recipe::plan(req, host)) } + + fn versions(&self, host: &Host) -> Vec { + // The pins alone, offline: `plan` would consult the release listing when a pin fails. + recipe::versions(host) + } } /// The `.base` file `basert list --json` holds for `id`: the variant named with the id, diff --git a/crates/superfluid-adapters/superfluid-adapter-basert/src/recipe.rs b/crates/superfluid-adapters/superfluid-adapter-basert/src/recipe.rs index 368b2cc9..70c20cdf 100644 --- a/crates/superfluid-adapters/superfluid-adapter-basert/src/recipe.rs +++ b/crates/superfluid-adapters/superfluid-adapter-basert/src/recipe.rs @@ -1,6 +1,6 @@ //! What installing basert fetches. -use superfluid_adapter_kit::install::{fetch_json, version_key, Asset, Host, Plan, Request}; +use superfluid_adapter_kit::install::{fetch_json, version_key, Asset, Candidate, Host, Plan, Request}; use serde_json::Value; fn recipe() -> Value { @@ -75,6 +75,45 @@ pub fn plan(req: &Request, host: &Host) -> Result, String> { }) } +/// The pinned engines, newest first, each planned from the pins alone: the driven ones install, the others say why not. +pub fn versions(host: &Host) -> Vec { + versions_with(host, &pinned()) +} + +pub fn versions_with(host: &Host, pins: &[Pin]) -> Vec { + use superfluid_engine_ffi::libbasert::{abi_built_for, compatible, unnumbered_minor_for, BUILT_FOR}; + let mut pins: Vec<&Pin> = pins.iter().collect(); + pins.sort_by_key(|p| std::cmp::Reverse(version_key(&p.version))); + let not_driven = |abi: Option| -> String { + let why = match (abi, abi_built_for()) { + (Some(n), Some(w)) => format!("states engine ABI {n}; this build drives ABI {w}"), + (None, Some(w)) => match unnumbered_minor_for(w) { + Some(minor) => format!("states no engine ABI and is not a {minor}.x engine; this build drives ABI {w}"), + None => format!("states no engine ABI; this build drives ABI {w}"), + }, + (_, None) => format!("is not a baseRT {}.x engine, which this build drives", minor(BUILT_FOR).iter().map(u64::to_string).collect::>().join(".")), + }; + format!("{why} (--untested installs it anyway)") + }; + pins.into_iter() + .map(|pin| { + let version = pin.version.clone(); + let here = if compatible(pin.abi, abi_built_for(), &version).is_err() { + Err(not_driven(pin.abi)) + } else { + let req = Request { version: Some(version.clone()), ..Request::default() }; + plan_with(&req, host, std::slice::from_ref(pin), &Value::Null).and_then(|mut plans| { + if plans.is_empty() { + return Err("nothing to install here".to_string()); + } + Ok(plans.remove(0)) + }) + }; + Candidate { version, here } + }) + .collect() +} + pub fn plan_with(req: &Request, host: &Host, pins: &[Pin], releases: &Value) -> Result, String> { use superfluid_engine_ffi::libbasert::{abi_built_for, compatible, unnumbered_minor_for, BUILT_FOR}; let (part, backend) = platform(host)?; @@ -248,6 +287,27 @@ mod tests { assert!(e.contains(&format!("engine ABI {same}, or a 0.3.x engine that states none")) && e.contains("the newest is 0.5.0"), "{e}"); } + #[test] + fn the_versions_listed_are_the_pins_newest_first_and_only_the_driven_ones_install() { + let (same, other) = (abi(), abi() + 1); + let pins = [pin("0.2.0", None, "ab"), pin("0.4.5", Some(same), "ef"), pin("0.5.0", Some(other), "01"), pin("0.3.9", None, "cd")]; + let listed = versions_with(&mac(), &pins); + assert_eq!(listed.iter().map(|c| c.version.as_str()).collect::>(), ["0.5.0", "0.4.5", "0.3.9", "0.2.0"]); + assert_eq!(listed[0].here, Err(format!("states engine ABI {other}; this build drives ABI {same} (--untested installs it anyway)"))); + assert_eq!(listed[3].here, Err(format!("states no engine ABI and is not a 0.3.x engine; this build drives ABI {same} (--untested installs it anyway)"))); + assert_eq!(listed[1].here.as_ref().map(|p| (p.install.as_str(), p.tested)), Ok(("0.4.5-metal", true))); + assert_eq!(listed[1].here.as_ref().unwrap().assets[0].url, "https://pinned/basert-engine-macos-arm64-0.4.5.tar.gz", "no release listing was needed"); + assert_eq!(listed[2].here.as_ref().map(|p| p.install.as_str()), Ok("0.3.9-metal"), "the unnumbered line"); + let linux = Host { os: "linux".into(), arch: "x64".into(), ..Host::default() }; + let elsewhere = versions_with(&linux, &pins); + for (i, driven) in [(0, false), (1, true), (2, true), (3, false)] { + let e = elsewhere[i].here.as_ref().unwrap_err(); + assert_eq!(e.contains("baseRT publishes engines for"), driven, "{e}"); + assert_eq!(e.contains("this build drives ABI"), !driven, "{e}"); + } + assert!(versions(&mac()).iter().any(|c| c.here.is_ok()), "the recipe pins an engine this build drives"); + } + #[test] fn a_release_with_no_pinned_digest_needs_one_named() { let same = "0.4.9".to_string(); diff --git a/crates/superfluid-adapters/superfluid-adapter-kit/src/install.rs b/crates/superfluid-adapters/superfluid-adapter-kit/src/install.rs index 7974ecf0..c982f6df 100644 --- a/crates/superfluid-adapters/superfluid-adapter-kit/src/install.rs +++ b/crates/superfluid-adapters/superfluid-adapter-kit/src/install.rs @@ -221,6 +221,36 @@ impl Plan { } } +/// A version an adapter installs on its own, planned for a host: the first plan, or why it does not install there. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Candidate { + pub version: String, + pub here: Result, +} + +impl Candidate { + pub fn to_json(&self) -> Value { + match &self.here { + Ok(p) => json!({"version": self.version, "plan": p.to_json()}), + Err(why) => json!({"version": self.version, "error": why}), + } + } + + pub fn from_json(v: &Value) -> Result { + let version = v["version"].as_str().ok_or("a listed version without \"version\"")?.to_string(); + let here = match v["error"].as_str() { + Some(why) => Err(why.to_string()), + None => Ok(Plan::from_json(&v["plan"])?), + }; + Ok(Candidate { version, here }) + } + + /// What the install fetches, wheels included. + pub fn size(&self) -> u64 { + self.here.as_ref().map(|p| p.size() + p.extra["wheels_size"].as_u64().unwrap_or(0)).unwrap_or(0) + } +} + pub fn backend_rank(backend: &str) -> u32 { let family = backend.split(['-', '_']).next().unwrap_or(backend); match family { diff --git a/crates/superfluid-adapters/superfluid-adapter-kit/src/lib.rs b/crates/superfluid-adapters/superfluid-adapter-kit/src/lib.rs index e57986da..b14518eb 100644 --- a/crates/superfluid-adapters/superfluid-adapter-kit/src/lib.rs +++ b/crates/superfluid-adapters/superfluid-adapter-kit/src/lib.rs @@ -19,7 +19,7 @@ pub use superfluid_worker::{ring_specs_for, WorkerArgs}; pub mod conformance; pub mod install; -use install::{Host, Manifest, Plan, Request}; +use install::{Candidate, Host, Manifest, Plan, Request}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PullOption { @@ -193,6 +193,12 @@ pub trait Runtime: Send + Sync { true } + /// What this adapter was built and tested for, as a release carries it (`superfluid compat`, `compat.json`): + /// `tested` names the versions it installs on its own; the rest of the keys are the adapter's to define. + fn compat(&self) -> serde_json::Value { + serde_json::json!({}) + } + fn prepare(&self, _args: &WorkerArgs) {} fn probe(&self, args: &WorkerArgs) -> Result; @@ -231,6 +237,26 @@ pub trait Runtime: Send + Sync { None } + /// The versions this adapter installs on its own, newest first, each planned for `host` as `plan` would (`superfluid runtime + /// versions`). Answered from the recipe alone, never the network: by default every `tested` version `compat` names. + fn versions(&self, host: &Host) -> Vec { + let tested: Vec = + self.compat()["tested"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default(); + tested + .into_iter() + .map(|version| { + let req = Request { version: Some(version.clone()), ..Request::default() }; + let here = match self.plan(&req, host) { + Some(Ok(mut plans)) if !plans.is_empty() => Ok(plans.remove(0)), + Some(Ok(_)) => Err("nothing to install here".to_string()), + Some(Err(why)) => Err(why), + None => Err(format!("the {} runtime is not installed from a project", self.info().id)), + }; + Candidate { version, here } + }) + .collect() + } + fn pull_options(&self) -> Option<&'static [PullOption]> { None } @@ -345,6 +371,23 @@ pub fn worker_main(rt: &dyn Runtime) -> ! { if argv.first().map(String::as_str) == Some("pull") { pull_command(rt, &name, &argv[1..]); } + if argv.first().map(String::as_str) == Some("compat") { + // Always JSON; nothing of the runtime is needed. + rt.prepare(&WorkerArgs::default()); + println!("{}", serde_json::to_string(&rt.compat()).expect("compat is JSON")); + std::process::exit(0); + } + if argv.first().map(String::as_str) == Some("versions") { + rt.prepare(&WorkerArgs::default()); + let host = Host::detect(); + let v = serde_json::json!({ + "host": host.to_json(), + "describe": host.describe(), + "versions": rt.versions(&host).iter().map(Candidate::to_json).collect::>(), + }); + println!("{v}"); + std::process::exit(0); + } let (command, rest) = match argv.first().map(String::as_str) { Some(c @ ("version" | "check")) => (Some(c), &argv[1..]), _ => (None, &argv[..]), @@ -511,6 +554,55 @@ mod tests { Fake { runs, asked_facts: AtomicBool::new(false) } } + /// A runtime that installs two versions of itself, the older one nowhere. + struct Installs; + + impl Runtime for Installs { + fn info(&self) -> RuntimeInfo { + RuntimeInfo { id: "inst", aliases: &[], formats: vec![], tokenizer: TokenizerSource::HuggingFace } + } + fn compat(&self) -> serde_json::Value { + serde_json::json!({"tested": ["2.0", "1.0"]}) + } + fn probe(&self, _args: &WorkerArgs) -> Result { + Err("never".into()) + } + fn open(&self, _args: &WorkerArgs) -> Result { + Err("never".into()) + } + fn plan(&self, req: &Request, host: &Host) -> Option, String>> { + let version = req.version.clone().unwrap_or_else(|| "2.0".into()); + if version == "1.0" { + return Some(Err(format!("inst 1.0 publishes no build for {}", host.platform()))); + } + Some(Ok(vec![Plan { + id: "inst".into(), + install: format!("{version}-cpu"), + backend: "cpu".into(), + assets: vec![install::Asset { name: "a.tgz".into(), url: "https://x/a.tgz".into(), sha256: None, size: Some(7) }], + tested: true, + why: "a test".into(), + version, + extra: serde_json::json!({"wheels_size": 3}), + }])) + } + } + + #[test] + fn the_versions_listed_are_the_tested_ones_each_planned_here() { + let host = Host { os: "linux".into(), arch: "x64".into(), ..Host::default() }; + let listed = Installs.versions(&host); + assert_eq!(listed.iter().map(|c| c.version.as_str()).collect::>(), ["2.0", "1.0"], "the adapter's order"); + assert_eq!(listed[0].here.as_ref().map(|p| p.install.as_str()), Ok("2.0-cpu")); + assert_eq!(listed[0].size(), 10, "the assets and the wheels"); + assert_eq!(listed[1].here, Err("inst 1.0 publishes no build for linux-x64".to_string())); + assert_eq!(listed[1].size(), 0); + for c in &listed { + assert_eq!(&Candidate::from_json(&c.to_json()).unwrap(), c); + } + assert!(Fake { runs: true, asked_facts: AtomicBool::new(false) }.versions(&host).is_empty(), "no compat, no versions"); + } + #[test] fn a_runtime_that_does_not_run_here_says_why_and_lists_no_device() { let report = check(&fake(false), &WorkerArgs::default()); diff --git a/crates/superfluid-adapters/superfluid-adapter-llamacpp/src/lib.rs b/crates/superfluid-adapters/superfluid-adapter-llamacpp/src/lib.rs index 98af767d..283199c3 100644 --- a/crates/superfluid-adapters/superfluid-adapter-llamacpp/src/lib.rs +++ b/crates/superfluid-adapters/superfluid-adapter-llamacpp/src/lib.rs @@ -17,6 +17,10 @@ pub use tokenizer::LlamaTokenizer; pub struct Llamacpp; impl Runtime for Llamacpp { + fn compat(&self) -> serde_json::Value { + serde_json::json!({"tested": crate::recipe::tested().into_iter().map(|(v, _)| v).collect::>()}) + } + fn info(&self) -> RuntimeInfo { RuntimeInfo { id: "llamacpp", diff --git a/crates/superfluid-adapters/superfluid-adapter-mlx/src/lib.rs b/crates/superfluid-adapters/superfluid-adapter-mlx/src/lib.rs index 55c9cf60..3dab6bae 100644 --- a/crates/superfluid-adapters/superfluid-adapter-mlx/src/lib.rs +++ b/crates/superfluid-adapters/superfluid-adapter-mlx/src/lib.rs @@ -75,6 +75,10 @@ impl Mlx { } impl Runtime for Mlx { + fn compat(&self) -> serde_json::Value { + serde_json::json!({"tested": crate::recipe::tested(), "python": crate::recipe::python_version()}) + } + fn info(&self) -> RuntimeInfo { RuntimeInfo { id: "mlx", diff --git a/crates/superfluid-daemon/src/bin/superfluid.rs b/crates/superfluid-daemon/src/bin/superfluid.rs index a2e0ce09..dca2ecff 100644 --- a/crates/superfluid-daemon/src/bin/superfluid.rs +++ b/crates/superfluid-daemon/src/bin/superfluid.rs @@ -52,7 +52,7 @@ fn runtimes_cmd(args: &[String]) { } let found = superfluid_daemon::runtimes_report::with_installs(&catalog); if json { - let rows = superfluid_daemon::runtimes_report::table_json(&found); + let rows = superfluid_daemon::runtimes_report::table_json_of(&found, Some(&catalog)); println!("{}", serde_json::to_string_pretty(&rows).expect("json")); return; } @@ -104,6 +104,17 @@ fn runtime_cmd(args: &[String]) { done }; match sub.as_str() { + "versions" => { + if rest.iter().any(|a| a != "--json") { + usage(); + } + let listing = superfluid_daemon::versions::of(&catalog, id).unwrap_or_else(|e| fail(e)); + if rest.iter().any(|a| a == "--json") { + println!("{}", serde_json::to_string_pretty(&listing.json()).expect("json")); + } else { + print!("{}", listing.text()); + } + } "install" => { let mut req = Request::default(); let mut dry_run = false; @@ -473,10 +484,11 @@ fn main() { return; } if command == Some("compat") { + let catalog = superfluid_daemon::runtimes::Catalog::from_env(); if args[1..].iter().any(|a| a == "--json") { - println!("{}", serde_json::to_string_pretty(&cli::compat_json()).expect("compat is JSON")); + println!("{}", serde_json::to_string_pretty(&superfluid_daemon::compat::json(&catalog)).expect("compat is JSON")); } else { - print!("{}", cli::compat_text()); + print!("{}", superfluid_daemon::compat::text(&catalog)); } return; } diff --git a/crates/superfluid-daemon/src/cli.rs b/crates/superfluid-daemon/src/cli.rs index 022722c1..607f15bd 100644 --- a/crates/superfluid-daemon/src/cli.rs +++ b/crates/superfluid-daemon/src/cli.rs @@ -371,8 +371,9 @@ pub const RUNTIMES_HELP: &str = "List the inference runtimes here, or which one Usage: superfluid runtimes [] [--json] - With no model: one row per runtime and install, its state, version, the formats it reads and - its device, then what to do about any that is not ready. + With no model: one row per runtime and install, its state, version, the newest version its + adapter installs on its own here (INSTALLABLE; `superfluid runtime versions ` lists them + all), the formats it reads and its device, then what to do about any that is not ready. With a model: which runtime reads it and what that runtime serves and refuses (exit 1 if none). Options: @@ -382,6 +383,8 @@ Options: pub const RUNTIME_HELP: &str = "Install and manage inference runtimes. Usage: + superfluid runtime versions [--json] List the versions the adapter installs on its own: which install + here, as what, and which are installed superfluid runtime install [options] Fetch and install a runtime for this machine superfluid runtime update Install the newest tested build beside the current one superfluid runtime repair [] Reinstall an install in place @@ -399,6 +402,7 @@ Install options: --dry-run Print the plan and stop Examples: + superfluid runtime versions llamacpp superfluid runtime install llamacpp superfluid runtime install llamacpp --backend vulkan --dry-run "; @@ -461,56 +465,23 @@ pub fn command_help(command: &str) -> Option { pub const COMMANDS: &[&str] = &["serve", "launch", "stop", "runtimes", "runtime", "compat", "session", "media", "top", "fleet", "node", "help", "version"]; -pub const COMPAT_HELP: &str = "What this build was built for: the runtime contracts it checks at load. +pub const COMPAT_HELP: &str = "What this build was built and tested for, per runtime. Usage: superfluid compat [--json] - basert: the baseRT header version this build carries and the engine ABI number it checks. - A libbaseRT with the same ABI number serves, whatever its version; one that states no - number (0.3.0 and older) serves if it is of the line that carried this ABI before it was - numbered, 0.3.x. A release carries the same data beside its tarball, as compat.json, so a - host can choose a release before downloading it. + basert: the baseRT header version this build carries, the engine ABI number it checks and + the line accepted without one (0.3.x), and the engines it installs on its own. A libbaseRT + with the same ABI number serves, whatever its version. + llamacpp, mlx: the runtime versions each shipped adapter installs on its own, the ones it + was built and tested against (`--untested` installs another). + A release carries the same data beside its tarball, as compat.json, so a host can choose a + release before downloading it. `superfluid runtime versions ` lists one runtime's versions + with which install on this machine. Options: --json Print JSON "; -/// `superfluid compat --json`: what this build was built for, per runtime. -pub fn compat_json() -> serde_json::Value { - #[allow(unused_mut)] // a build without the basert adapter inserts nothing - let mut runtimes = serde_json::Map::new(); - #[cfg(feature = "basert")] - runtimes.insert( - "basert".into(), - serde_json::json!({ - "basert_version": superfluid_engine_ffi::libbasert::BUILT_FOR, - "abi": superfluid_engine_ffi::libbasert::abi_built_for(), - "unnumbered_minor": superfluid_engine_ffi::libbasert::abi_built_for().and_then(superfluid_engine_ffi::libbasert::unnumbered_minor_for), - }), - ); - serde_json::json!({"superfluid": env!("CARGO_PKG_VERSION"), "runtimes": runtimes}) -} - -/// `superfluid compat`, for a person. -pub fn compat_text() -> String { - let mut out = format!("{}\n", version()); - let c = compat_json(); - match c["runtimes"].get("basert") { - Some(b) => { - let abi = b["abi"].as_u64().map(|n| format!("engine ABI {n}")).unwrap_or_else(|| "no engine ABI number (a header before 0.4.0)".into()); - let unnumbered = match b["unnumbered_minor"].as_str() { - Some(minor) => format!("one that states no number serves if it is baseRT {minor}.x"), - None => "one that states no number does not serve".to_string(), - }; - out.push_str(&format!( - "basert: built against baseRT {} headers, {abi}. A libbaseRT with the same ABI number serves, whatever its version; {unnumbered}.\n", - b["basert_version"].as_str().unwrap_or("?"), - )); - } - None => out.push_str("basert: not in this build (no `basert` feature)\n"), - } - out -} /// `$SUPERFLUID_HOME/sessions`. pub fn default_sessions(home: &Path) -> PathBuf { diff --git a/crates/superfluid-daemon/src/compat.rs b/crates/superfluid-daemon/src/compat.rs new file mode 100644 index 00000000..7298faf7 --- /dev/null +++ b/crates/superfluid-daemon/src/compat.rs @@ -0,0 +1,121 @@ +//! `superfluid compat [--json]`: what this build was built and tested for, per runtime. + +use std::process::Command; + +use serde_json::{json, Map, Value}; + +use crate::runtimes::Catalog; + +/// Every adapter this build ships: a linked one in process, a shipped worker through `compat --json`. +pub fn json(catalog: &Catalog) -> Value { + let mut runtimes: Map = Map::new(); + for rt in crate::linked::runtimes() { + runtimes.insert(rt.info().id.into(), rt.compat()); + } + for id in catalog.shipped_ids() { + if runtimes.contains_key(id.name()) { + continue; + } + let Some(worker) = catalog.shipped(id) else { continue }; + let mut cmd = Command::new(&worker); + crate::exec::without_secrets(&mut cmd).args(["compat", "--json"]); + let answer = match cmd.output() { + Ok(out) if out.status.success() => serde_json::from_slice::(&out.stdout) + .unwrap_or_else(|e| json!({"error": format!("{}: compat is not JSON: {e}", worker.display())})), + Ok(out) => json!({"error": format!("{} compat exited {}", worker.display(), out.status)}), + Err(e) => json!({"error": format!("{}: {e}", worker.display())}), + }; + runtimes.insert(id.name().into(), answer); + } + json!({"superfluid": env!("CARGO_PKG_VERSION"), "runtimes": runtimes}) +} + +/// `superfluid compat`, for a person. +pub fn text(catalog: &Catalog) -> String { + let c = json(catalog); + let mut out = format!("{}\n", crate::cli::version()); + let Some(runtimes) = c["runtimes"].as_object() else { return out }; + for (id, r) in runtimes { + if let Some(e) = r["error"].as_str() { + out.push_str(&format!("{id}: {e}\n")); + continue; + } + let line = match id.as_str() { + "basert" => { + let abi = r["abi"].as_u64().map(|n| format!("engine ABI {n}")).unwrap_or_else(|| "no engine ABI number (a header before 0.4.0)".into()); + let unnumbered = match r["unnumbered_minor"].as_str() { + Some(minor) => format!("one that states no number serves if it is baseRT {minor}.x"), + None => "one that states no number does not serve".to_string(), + }; + let pinned: Vec = r["pinned_engines"] + .as_array() + .map(|a| a.iter().filter_map(|p| p["version"].as_str().map(str::to_string)).collect()) + .unwrap_or_default(); + format!( + "built against baseRT {} headers, {abi}. A libbaseRT with the same ABI number serves, whatever its version; {unnumbered}. \ + Installs on its own: {}", + r["basert_version"].as_str().unwrap_or("?"), + if pinned.is_empty() { "nothing".to_string() } else { pinned.join(", ") } + ) + } + _ => { + let tested: Vec = + r["tested"].as_array().map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default(); + let python = r["python"].as_str().map(|p| format!(" on Python {p}")).unwrap_or_default(); + format!("installs on its own{python}: {}", if tested.is_empty() { "nothing".to_string() } else { tested.join(", ") }) + } + }; + out.push_str(&format!("{id}: {line}\n")); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + use std::path::PathBuf; + + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("superfluid-compat-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn every_shipped_adapter_answers_for_its_runtime() { + let root = scratch("shipped"); + let beside = root.join("bin"); + let libexec = root.join("libexec").join("superfluid"); + std::fs::create_dir_all(&beside).unwrap(); + std::fs::create_dir_all(&libexec).unwrap(); + let toy = libexec.join("superfluid-worker-toyrt"); + // The toy also tells whether a credential reached it. + std::fs::write(&toy, "#!/bin/sh\n[ \"$1\" = compat ] || exit 2\necho \"{\\\"tested\\\":[\\\"t2\\\",\\\"t1\\\"],\\\"saw\\\":\\\"${SUPERFLUID_COMPAT_SENTINEL_TOKEN:-}\\\"}\"\n").unwrap(); + std::fs::set_permissions(&toy, std::fs::Permissions::from_mode(0o755)).unwrap(); + let broken = libexec.join("superfluid-worker-oldrt"); + std::fs::write(&broken, "#!/bin/sh\nexit 2\n").unwrap(); + std::fs::set_permissions(&broken, std::fs::Permissions::from_mode(0o755)).unwrap(); + let cat = Catalog::new(root.join("home"), Some(beside.clone()), beside.join("superfluid-workerd")); + std::env::set_var("SUPERFLUID_COMPAT_SENTINEL_TOKEN", "hunter2"); + let c = json(&cat); + std::env::remove_var("SUPERFLUID_COMPAT_SENTINEL_TOKEN"); + assert_eq!(c["superfluid"], env!("CARGO_PKG_VERSION")); + assert_eq!(c["runtimes"]["toyrt"]["tested"][0], "t2"); + assert_eq!(c["runtimes"]["toyrt"]["saw"], "", "a credential-named variable is not handed to the worker"); + for id in crate::linked::ids() { + assert!(c["runtimes"][id.name()].is_object(), "the linked {} adapter answers in process: {c}", id.name()); + } + assert!(c["runtimes"]["oldrt"]["error"].as_str().unwrap().contains("exited"), "{c}"); + #[cfg(feature = "basert")] + { + assert!(c["runtimes"]["basert"]["basert_version"].is_string(), "{c}"); + assert!(c["runtimes"]["basert"]["pinned_engines"].is_array(), "{c}"); + } + let t = text(&cat); + assert!(t.contains("toyrt: installs on its own: t2, t1"), "{t}"); + assert!(t.contains("oldrt: ") && t.contains("exited"), "{t}"); + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/crates/superfluid-daemon/src/lib.rs b/crates/superfluid-daemon/src/lib.rs index 8d0e8f67..59f2fe3b 100644 --- a/crates/superfluid-daemon/src/lib.rs +++ b/crates/superfluid-daemon/src/lib.rs @@ -7,6 +7,7 @@ pub mod atem; pub mod bus; pub mod capabilities; pub mod cli; +pub mod compat; pub mod codec; mod exec; pub mod completion_bucket; @@ -49,6 +50,7 @@ pub mod installs; pub mod pulls; pub mod runtimes; pub mod runtimes_report; +pub mod versions; pub mod linked; pub mod dylib_tokenizer; pub mod export; diff --git a/crates/superfluid-daemon/src/runtimes_report.rs b/crates/superfluid-daemon/src/runtimes_report.rs index 570fc5e5..4cab52bc 100644 --- a/crates/superfluid-daemon/src/runtimes_report.rs +++ b/crates/superfluid-daemon/src/runtimes_report.rs @@ -20,7 +20,7 @@ fn state(f: &Found) -> &'static str { } } -fn columns(rows: &[Vec]) -> String { +pub(crate) fn columns(rows: &[Vec]) -> String { let n = rows.iter().map(Vec::len).max().unwrap_or(0); let widths: Vec = (0..n).map(|c| rows.iter().filter_map(|r| r.get(c)).map(|s| s.chars().count()).max().unwrap_or(0)).collect(); let mut out = String::new(); @@ -69,9 +69,13 @@ pub fn table(found: &[Found], packages: &Path) -> String { } pub fn table_of(found: &[Found], packages: &Path, catalog: Option<&Catalog>) -> String { - let mut rows = vec![["RUNTIME", "STATE", "INSTALL", "VERSION", "READS", "DEVICE", "WORKER"].map(String::from).to_vec()]; + let mut rows = vec![["RUNTIME", "STATE", "INSTALL", "VERSION", "INSTALLABLE", "READS", "DEVICE", "WORKER"].map(String::from).to_vec()]; let mut problems = Vec::new(); for f in found { + let installable = match (catalog, f.id.install()) { + (Some(c), None) => crate::versions::cell(&crate::versions::of(c, f.id)), + _ => "-".to_string(), + }; let reads = f .info .as_ref() @@ -86,19 +90,40 @@ pub fn table_of(found: &[Found], packages: &Path, catalog: Option<&Catalog>) -> } }; let worker = f.worker.as_ref().map(|w| format!("{}: {}", w.source.name(), w.bin.display())).unwrap_or_else(|| "-".into()); - rows.push(vec![f.id.to_string(), state(f).into(), install_cell(f, catalog), version, reads, device, worker]); + rows.push(vec![f.id.to_string(), state(f).into(), install_cell(f, catalog), version, installable, reads, device, worker]); } let mut out = if found.is_empty() { "no runtime is installed here\n".to_string() } else { columns(&rows) }; for p in problems { out.push_str(&p); out.push('\n'); } + if catalog.is_some() && !found.is_empty() { + out.push_str("`superfluid runtime versions ` lists every version an adapter installs on its own\n"); + } out.push_str(&format!("installed runtimes: {}\n", packages.display())); out } pub fn table_json(found: &[Found]) -> Value { - Value::Array(found.iter().map(runtime_json).collect()) + table_json_of(found, None) +} + +/// With a catalog, a runtime's row carries `installable`, the versions its adapter installs here. +pub fn table_json_of(found: &[Found], catalog: Option<&Catalog>) -> Value { + Value::Array( + found + .iter() + .map(|f| { + let mut v = runtime_json(f); + if let (Some(c), None) = (catalog, f.id.install()) { + if let Ok(listing) = crate::versions::of(c, f.id) { + v["installable"] = json!(crate::versions::here(&listing)); + } + } + v + }) + .collect(), + ) } fn runtime_json(f: &Found) -> Value { @@ -312,9 +337,9 @@ mod tests { let cat = Catalog::new(home.clone(), None, home.join("superfluid-workerd")); let text = table(&cat.survey(), &home.join("runtimes")); let lines: Vec<&str> = text.lines().collect(); - assert!(lines[0].starts_with("RUNTIME STATE INSTALL VERSION READS DEVICE"), "{text}"); - assert!(lines[1].starts_with("llamacpp ready v1-metal (default) v1 gguf Metal: Apple M5 Pro, 36.0 GB installed: "), "{text}"); - assert!(lines[2].starts_with("mlx broken v1-metal (default) - mlx -"), "{text}"); + assert!(lines[0].starts_with("RUNTIME STATE INSTALL VERSION INSTALLABLE READS DEVICE"), "{text}"); + assert!(lines[1].starts_with("llamacpp ready v1-metal (default) v1 - gguf Metal: Apple M5 Pro, 36.0 GB installed: "), "{text}"); + assert!(lines[2].starts_with("mlx broken v1-metal (default) - - mlx -"), "{text}"); assert!(lines[3].starts_with("mlx: the mlx runtime at ") && lines[3].contains("`superfluid runtime repair mlx`"), "{text}"); let json = table_json(&cat.survey()); assert_eq!(json[0]["formats"][0]["id"], "gguf"); @@ -338,7 +363,7 @@ mod tests { let cat = Catalog::new(home.clone(), Some(beside.clone()), beside.join("superfluid-workerd")); let text = table(&cat.survey(), &home.join("runtimes")); let lines: Vec<&str> = text.lines().collect(); - assert!(lines[1].starts_with("llamacpp not installed - - gguf - shipped with superfluid: "), "{text}"); + assert!(lines[1].starts_with("llamacpp not installed - - - gguf - shipped with superfluid: "), "{text}"); assert_eq!( lines[2], "llamacpp: the llamacpp runtime is not installed: llama.cpp not found: install it with `superfluid runtime install llamacpp`", @@ -350,6 +375,33 @@ mod tests { assert_eq!(json[0]["formats"][0]["id"], "gguf"); } + #[test] + fn with_a_catalog_the_table_says_what_installs_here() { + if !crate::linked::ids().is_empty() { + return; + } + use crate::versions::tests::{fake_worker_listing, manifest, LISTING}; + let home = scratch("installable"); + let dir = manifest(&home, "llamacpp", "v1-metal", "t1", "metal", true); + fake_worker_listing(&dir.join("bin"), "superfluid-worker-llamacpp", &report("llamacpp", V, "true"), LISTING); + std::fs::create_dir_all(dir.join("lib")).unwrap(); + std::fs::write(dir.join("lib").join(crate::dylib_tokenizer::library_file("superfluid_tokenizer_llamacpp")), b"").unwrap(); + std::os::unix::fs::symlink("v1-metal", home.join("runtimes").join("llamacpp").join("current")).unwrap(); + install(&home, "mlx", &report("mlx", V, "true"), 0); + let cat = Catalog::new(home.clone(), None, home.join("superfluid-workerd")); + let found = with_installs(&cat); + let text = table_of(&found, &home.join("runtimes"), Some(&cat)); + let lines: Vec<&str> = text.lines().collect(); + assert!(lines[0].starts_with("RUNTIME STATE INSTALL VERSION INSTALLABLE READS DEVICE"), "{text}"); + assert!(lines[1].starts_with("llamacpp ready v1-metal (default) v1 t1 (installed) gguf Metal"), "{text}"); + assert!(lines[2].starts_with("mlx ready v1-metal (default) v1 - mlx Metal"), "{text}"); + assert!(text.contains("\n`superfluid runtime versions ` lists every version an adapter installs on its own\ninstalled runtimes: "), "{text}"); + let json = table_json_of(&found, Some(&cat)); + assert_eq!(json[0]["installable"], json!(["t1"])); + assert!(json[1]["installable"].is_null()); + assert!(table_json(&found)[0]["installable"].is_null(), "without a catalog nothing is asked"); + } + #[test] fn a_model_is_answered_by_every_runtime_and_served_by_its_formats() { if !crate::linked::ids().is_empty() { diff --git a/crates/superfluid-daemon/src/versions.rs b/crates/superfluid-daemon/src/versions.rs new file mode 100644 index 00000000..12239ea8 --- /dev/null +++ b/crates/superfluid-daemon/src/versions.rs @@ -0,0 +1,261 @@ +//! `superfluid runtime versions [--json]`, and the INSTALLABLE column of `superfluid runtimes`. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use serde_json::{json, Value}; +use superfluid_adapter_kit::install::{Candidate, Host}; + +use crate::installs::{self, Install}; +use crate::runtime_pick::RuntimeId; +use crate::runtimes::Catalog; + +pub struct Listing { + pub id: RuntimeId, + pub host: String, + /// What the adapter lists, in its order (newest first). + pub candidates: Vec, + pub installs: Vec, + pub default: Option, + pub pinned: Option, +} + +/// What the adapter lists for this machine: the worker named by `SUPERFLUID_WORKER_` when one is, else the +/// linked adapter in process, else the worker `runtime install` would use; a worker answers from its recipe alone. +pub fn of(catalog: &Catalog, id: RuntimeId) -> Result { + let named = std::env::var_os(crate::runtimes::worker_env(id.base())).map(PathBuf::from); + of_with(catalog, id, named.as_deref()) +} + +pub fn of_with(catalog: &Catalog, id: RuntimeId, named: Option<&Path>) -> Result { + let id = id.base(); + let (host, candidates) = match (named, crate::linked::get(id)) { + (Some(worker), _) => asked(worker)?, + (None, Some(rt)) => { + let host = Host::detect(); + (host.describe(), rt.versions(&host)) + } + (None, None) => asked(&installs::installer(catalog, id)?)?, + }; + Ok(Listing { + id, + host, + candidates, + installs: installs::list(catalog, id), + default: installs::default(catalog, id).map(|i| i.name), + pinned: installs::pinned(catalog, id), + }) +} + +fn asked(worker: &Path) -> Result<(String, Vec), String> { + let mut cmd = Command::new(worker); + crate::exec::without_secrets(&mut cmd).arg("versions").stdin(Stdio::null()); + let out = crate::exec::when_not_busy(|| cmd.output()).map_err(|e| format!("{} could not start: {e}", worker.display()))?; + if !out.status.success() { + return Err(format!("{} lists no versions ({}): an adapter from before the listing existed", worker.display(), out.status)); + } + let v: Value = serde_json::from_slice(&out.stdout).map_err(|e| format!("{} versions printed no listing: {e}", worker.display()))?; + let listed = v["versions"].as_array().ok_or_else(|| format!("{} versions printed no listing", worker.display()))?; + let candidates = listed.iter().map(Candidate::from_json).collect::, _>>()?; + Ok((v["describe"].as_str().unwrap_or_default().to_string(), candidates)) +} + +/// The versions that install here, newest first (`installable` in `superfluid runtimes --json`). +pub fn here(listing: &Listing) -> Vec<&str> { + listing.candidates.iter().filter(|c| c.here.is_ok()).map(|c| c.version.as_str()).collect() +} + +/// The INSTALLABLE cell: the newest listed version that installs here, marked when an install of it exists. +pub fn cell(listing: &Result) -> String { + let Ok(l) = listing else { return "-".into() }; + match l.candidates.iter().find(|c| c.here.is_ok()) { + None => "none here".into(), + Some(c) if l.installs.iter().any(|i| i.manifest.version == c.version) => format!("{} (installed)", c.version), + Some(c) => c.version.clone(), + } +} + +/// A line of the listing: a listed version, or an installed one the adapter does not list. +struct Row<'a> { + version: &'a str, + listed: Option<&'a Candidate>, + installed: Vec<&'a Install>, +} + +impl Listing { + fn rows(&self) -> Vec> { + let of_version = |v: &str| self.installs.iter().filter(|i| i.manifest.version == v).collect::>(); + let mut rows: Vec = + self.candidates.iter().map(|c| Row { version: &c.version, listed: Some(c), installed: of_version(&c.version) }).collect(); + for i in &self.installs { + if !rows.iter().any(|r| r.version == i.manifest.version) { + rows.push(Row { version: &i.manifest.version, listed: None, installed: of_version(&i.manifest.version) }); + } + } + rows + } + + fn mark(&self, name: &str) -> String { + if self.pinned.as_deref() == Some(name) { + format!("{name} (pinned)") + } else if self.default.as_deref() == Some(name) { + format!("{name} (default)") + } else { + name.to_string() + } + } + + pub fn text(&self) -> String { + let mut out = format!("{}: the versions this adapter installs on its own, newest first; this machine is {}\n", self.id, self.host); + let rows = self.rows(); + if rows.is_empty() { + out.push_str(" none: the adapter lists no version, and nothing is installed\n"); + } else { + let mut table = vec![["VERSION", "INSTALLS HERE AS", "INSTALLED"].map(String::from).to_vec()]; + for r in &rows { + let here = match r.listed.map(|c| (c, &c.here)) { + Some((c, Ok(p))) => match c.size() { + 0 => p.install.clone(), + size => format!("{} ({:.1} MB)", p.install, size as f64 / 1e6), + }, + Some((_, Err(why))) => format!("no: {why}"), + None => "(not a version this adapter lists)".to_string(), + }; + let installed = match r.installed.as_slice() { + [] => "-".to_string(), + some => some.iter().map(|i| self.mark(&i.name)).collect::>().join(", "), + }; + table.push(vec![r.version.to_string(), here, installed]); + } + out.push_str(&crate::runtimes_report::columns(&table)); + } + out.push_str(&format!( + "`superfluid runtime install {} --version ` installs one; a version not listed installs with --untested\n", + self.id + )); + out + } + + pub fn json(&self) -> Value { + let versions: Vec = self + .rows() + .iter() + .map(|r| { + let mut v = json!({ + "version": r.version, + "listed": r.listed.is_some(), + "installed": r.installed.iter().map(|i| i.name.as_str()).collect::>(), + }); + match r.listed.map(|c| (c, &c.here)) { + Some((c, Ok(p))) => { + v["installable"] = true.into(); + v["install"] = json!(p.install); + v["backend"] = json!(p.backend); + v["size"] = json!(c.size()); + } + Some((_, Err(why))) => v["installable"] = json!(why), + None => {} + } + v + }) + .collect(); + json!({"id": self.id.name(), "host": self.host, "default": self.default, "pinned": self.pinned, "versions": versions}) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + use std::path::PathBuf; + + pub(crate) fn scratch(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("superfluid-versions-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + /// A worker that answers `versions` with `listing` and anything else with `report`. + pub(crate) fn fake_worker_listing(dir: &Path, name: &str, report: &str, listing: &str) -> PathBuf { + std::fs::create_dir_all(dir).unwrap(); + let p = dir.join(name); + std::fs::write(&p, format!("#!/bin/sh\nif [ \"$1\" = versions ]; then cat <<'EOF'\n{listing}\nEOF\nexit 0; fi\ncat <<'EOF'\n{report}\nEOF\nexit 0\n")) + .unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); + p + } + + /// An install as `superfluid runtime install` leaves it, for `installs::list`. + pub(crate) fn manifest(home: &Path, id: &str, name: &str, version: &str, backend: &str, tested: bool) -> PathBuf { + let dir = home.join("runtimes").join(id).join(name); + std::fs::create_dir_all(dir.join("bin")).unwrap(); + let m = json!({"id": id, "install": name, "version": version, "backend": backend, "worker": format!("bin/superfluid-worker-{id}"), "tested": tested}); + std::fs::write(dir.join("runtime.json"), format!("{m:#}\n")).unwrap(); + dir + } + + pub(crate) const LISTING: &str = r#"{"describe":"macOS arm64","versions":[ + {"version":"t2","error":"toyrt t2 publishes no build for macos-arm64"}, + {"version":"t1","plan":{"id":"toyrt","version":"t1","backend":"metal","install":"t1-metal","assets":[{"name":"a.tgz","url":"https://x/a.tgz","sha256":"ab","size":2500000}],"tested":true,"why":"w","extra":{"wheels_size":500000}}}]}"#; + + #[test] + fn a_listing_says_which_versions_install_here_and_which_are_installed() { + let root = scratch("listing"); + let (beside, libexec, home) = (root.join("bin"), root.join("libexec").join("superfluid"), root.join("home")); + std::fs::create_dir_all(&beside).unwrap(); + std::fs::create_dir_all(&libexec).unwrap(); + fake_worker_listing(&libexec, "superfluid-worker-toyrt", "{}", LISTING); + manifest(&home, "toyrt", "t1-metal", "t1", "metal", true); + manifest(&home, "toyrt", "t9-cpu", "t9", "cpu", false); + let cat = Catalog::new(home.clone(), Some(beside.clone()), beside.join("superfluid-workerd")); + let id = RuntimeId::new("toyrt"); + + let l = of(&cat, id).unwrap(); + assert_eq!((l.host.as_str(), l.default.as_deref(), l.pinned.as_deref()), ("macOS arm64", Some("t1-metal"), None)); + let text = l.text(); + // Columns are padded to the widest cell; the words and their order are what is checked. + let squeezed: Vec = text.lines().map(|l| l.split_whitespace().collect::>().join(" ")).collect(); + assert_eq!(squeezed[0], "toyrt: the versions this adapter installs on its own, newest first; this machine is macOS arm64"); + assert_eq!(squeezed[1], "VERSION INSTALLS HERE AS INSTALLED"); + assert_eq!(squeezed[2], "t2 no: toyrt t2 publishes no build for macos-arm64 -"); + assert_eq!(squeezed[3], "t1 t1-metal (3.0 MB) t1-metal (default)"); + assert_eq!(squeezed[4], "t9 (not a version this adapter lists) t9-cpu"); + assert_eq!(squeezed[5], "`superfluid runtime install toyrt --version ` installs one; a version not listed installs with --untested"); + assert_eq!(squeezed.len(), 6); + let lines: Vec<&str> = text.lines().collect(); + assert!(lines[1].starts_with("VERSION INSTALLS HERE AS") && lines[2].starts_with("t2 no: "), "aligned: {text}"); + assert_eq!(lines[1].find("INSTALLED"), lines[3].find("t1-metal (default)"), "aligned: {text}"); + let j = l.json(); + assert_eq!(j["id"], "toyrt"); + assert_eq!(j["versions"][0]["installable"], "toyrt t2 publishes no build for macos-arm64"); + assert_eq!(j["versions"][0]["installed"], json!([])); + assert_eq!((j["versions"][1]["installable"].as_bool(), j["versions"][1]["install"].as_str()), (Some(true), Some("t1-metal"))); + assert_eq!((j["versions"][1]["size"].as_u64(), j["versions"][1]["installed"][0].as_str()), (Some(3_000_000), Some("t1-metal"))); + assert_eq!((j["versions"][2]["listed"].as_bool(), j["versions"][2]["installable"].is_null()), (Some(false), true)); + assert_eq!(here(&l), ["t1"]); + assert_eq!(cell(&Ok(l)), "t1 (installed)"); + + std::fs::write(home.join("runtimes").join("toyrt").join("pinned"), "t9-cpu\n").unwrap(); + let l = of(&cat, id).unwrap(); + let text = l.text(); + let squeezed: Vec = text.lines().map(|l| l.split_whitespace().collect::>().join(" ")).collect(); + assert_eq!(squeezed[3], "t1 t1-metal (3.0 MB) t1-metal", "{text}"); + assert_eq!(squeezed[4], "t9 (not a version this adapter lists) t9-cpu (pinned)", "{text}"); + assert_eq!(l.json()["pinned"], "t9-cpu"); + + let bare = Listing { installs: vec![], default: None, pinned: None, candidates: vec![Candidate { version: "t2".into(), here: Err("no".into()) }], ..l }; + assert_eq!(cell(&Ok(bare)), "none here"); + + crate::runtimes::tests::fake_worker(&libexec, "superfluid-worker-oldrt", "{}", 2); + let Err(e) = of(&cat, RuntimeId::new("oldrt")) else { panic!("an old worker listed versions") }; + assert!(e.contains("lists no versions"), "{e}"); + assert_eq!(cell(&Err(e)), "-"); + let named = fake_worker_listing(&root.join("elsewhere"), "superfluid-worker-named", "{}", r#"{"describe":"here","versions":[{"version":"n1","error":"not here"}]}"#); + for id in crate::linked::ids().into_iter().chain([RuntimeId::new("toyrt")]) { + let l = of_with(&cat, id, Some(&named)).unwrap(); + assert_eq!((l.host.as_str(), l.candidates.len(), l.candidates[0].version.as_str()), ("here", 1, "n1"), "{}", id.name()); + } + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/docs/design/adapters.md b/docs/design/adapters.md index 49fdff4d..fa69a9a3 100644 --- a/docs/design/adapters.md +++ b/docs/design/adapters.md @@ -45,10 +45,12 @@ pub trait Runtime: Send + Sync { fn prepare(&self, _args: &WorkerArgs) {} fn named(&self, _args: &WorkerArgs) -> Option { None } fn static_capabilities(&self) -> String { String::new() } + fn compat(&self) -> serde_json::Value { json!({}) } // what the adapter was built and tested for: `tested` versions, by convention fn reads(&self, path: &Path) -> Result<(), String> { /* by info().formats */ } fn model_facts(&self, _path: &Path) -> Option> { None } fn tokenizer(&self, _model: &Path) -> Option, String>> { None } fn plan(&self, _req: &Request, _host: &Host) -> Option, String>> { None } + fn versions(&self, host: &Host) -> Vec { /* each `tested` version of compat(), planned here */ } fn pull_options(&self) -> Option<&'static [PullOption]> { None } fn pull(&self, _pull: &Pull, _args: &WorkerArgs) -> Result { /* refuses */ } fn install(&self, plan: &Plan, dir: &Path) -> Result, String> { /* fetch into dir/lib */ } @@ -79,6 +81,8 @@ superfluid-worker- version superfluid-worker- check [--model ] superfluid-worker- plan [--version V] [--backend B] [--from ] [--sha256 H] [--untested] superfluid-worker- install --into --plan +superfluid-worker- compat +superfluid-worker- versions superfluid-worker- pull [--offline] [--