Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<N>.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 <id> [--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.
Expand Down
17 changes: 16 additions & 1 deletion crates/superfluid-adapters/superfluid-adapter-basert/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,24 @@ 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};

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::<Vec<_>>(),
})
}

fn info(&self) -> RuntimeInfo {
RuntimeInfo {
id: "basert",
Expand Down Expand Up @@ -115,6 +125,11 @@ impl Runtime for Basert {
fn plan(&self, req: &Request, host: &Host) -> Option<Result<Vec<Plan>, String>> {
Some(recipe::plan(req, host))
}

fn versions(&self, host: &Host) -> Vec<Candidate> {
// 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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -75,6 +75,45 @@ pub fn plan(req: &Request, host: &Host) -> Result<Vec<Plan>, 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<Candidate> {
versions_with(host, &pinned())
}

pub fn versions_with(host: &Host, pins: &[Pin]) -> Vec<Candidate> {
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<u32>| -> 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::<Vec<_>>().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<Vec<Plan>, String> {
use superfluid_engine_ffi::libbasert::{abi_built_for, compatible, unnumbered_minor_for, BUILT_FOR};
let (part, backend) = platform(host)?;
Expand Down Expand Up @@ -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::<Vec<_>>(), ["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();
Expand Down
30 changes: 30 additions & 0 deletions crates/superfluid-adapters/superfluid-adapter-kit/src/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Plan, String>,
}

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<Candidate, String> {
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 {
Expand Down
94 changes: 93 additions & 1 deletion crates/superfluid-adapters/superfluid-adapter-kit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Probe, String>;
Expand Down Expand Up @@ -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<Candidate> {
let tested: Vec<String> =
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
}
Expand Down Expand Up @@ -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::<Vec<_>>(),
});
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[..]),
Expand Down Expand Up @@ -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<Probe, String> {
Err("never".into())
}
fn open(&self, _args: &WorkerArgs) -> Result<Loaded, String> {
Err("never".into())
}
fn plan(&self, req: &Request, host: &Host) -> Option<Result<Vec<Plan>, 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::<Vec<_>>(), ["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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>()})
}

fn info(&self) -> RuntimeInfo {
RuntimeInfo {
id: "llamacpp",
Expand Down
4 changes: 4 additions & 0 deletions crates/superfluid-adapters/superfluid-adapter-mlx/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
18 changes: 15 additions & 3 deletions crates/superfluid-daemon/src/bin/superfluid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down
Loading
Loading