tessera-command 0.5.12

The tesserax command: opens a recipe, then serves, fetches or runs tasks
Documentation
//! `recipe`: inspect a recipe's profiles and print its effective configuration.

use crate::source::{Origin, Stop, open_recipe};
use serde_json::{Value, json};
use std::fmt::Write as _;
use tessera_frontend::recipe::{Host, Recipe, Resolved, Selection};

const GIB: f64 = (1u64 << 30) as f64;

#[derive(Default)]
struct Args {
    json: bool,
    list: bool,
    backend: Option<String>,
    arch: Option<String>,
    device: Option<String>,
    gpus: Option<u32>,
    vram_gib: Option<f64>,
    host_gib: Option<f64>,
    integrated: Option<bool>,
}

fn parse_args(rest: &[String]) -> Result<Args, Stop> {
    let mut out = Args::default();
    let mut iter = rest.iter();
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--json" => out.json = true,
            "--list" => out.list = true,
            "--backend" => out.backend = Some(iter.next().ok_or(Stop::Usage)?.clone()),
            "--arch" => out.arch = Some(iter.next().ok_or(Stop::Usage)?.clone()),
            "--device" => out.device = Some(iter.next().ok_or(Stop::Usage)?.clone()),
            "--gpus" => {
                let raw = iter.next().ok_or(Stop::Usage)?;
                let n: u32 = raw
                    .parse()
                    .map_err(|_| Stop::Failed(format!("invalid --gpus {raw:?}")))?;
                out.gpus = Some(n);
            }
            "--vram-gib" => {
                let raw = iter.next().ok_or(Stop::Usage)?;
                let g: f64 = raw
                    .parse()
                    .map_err(|_| Stop::Failed(format!("invalid --vram-gib {raw:?}")))?;
                out.vram_gib = Some(g);
            }
            "--host-gib" => {
                let raw = iter.next().ok_or(Stop::Usage)?;
                let g: f64 = raw
                    .parse()
                    .map_err(|_| Stop::Failed(format!("invalid --host-gib {raw:?}")))?;
                out.host_gib = Some(g);
            }
            "--integrated" => {
                let raw = iter.next().ok_or(Stop::Usage)?;
                let b: bool = raw
                    .parse()
                    .map_err(|_| Stop::Failed(format!("invalid --integrated {raw:?}")))?;
                out.integrated = Some(b);
            }
            _ => return Err(Stop::Usage),
        }
    }
    Ok(out)
}

fn build_host(args: &Args) -> Host {
    let settings = tessera_frontend::frontend_settings::read();
    let specs = crate::size::specs(&settings);
    let mut host = crate::size::host(&specs, args.gpus);
    if let Some(b) = &args.backend {
        host.backend = b.clone();
    }
    if let Some(a) = &args.arch {
        host.arch = a.clone();
    }
    if let Some(d) = &args.device {
        host.device = d.clone();
    }
    if let Some(g) = args.gpus {
        host.gpus = g;
    }
    if let Some(v) = args.vram_gib {
        host.vram_bytes = (v.max(0.0) * GIB).round() as u64;
    }
    if let Some(h) = args.host_gib {
        host.host_bytes = (h.max(0.0) * GIB).round() as u64;
    }
    if let Some(i) = args.integrated {
        host.integrated = i;
    }
    host
}

pub fn run(origin: Option<Origin>, rest: &[String]) -> Result<(), Stop> {
    let args = parse_args(rest)?;
    let origin = origin.ok_or_else(|| Stop::Failed("recipe requires --recipe <src>".into()))?;
    let (raw, explicit) = open_recipe(&origin)?;
    let raw = raw.ok_or_else(|| Stop::Failed("recipe requires --recipe <src>".into()))?;
    let host = build_host(&args);
    let text = render(&raw, explicit.as_deref(), &host, args.list, args.json)?;
    print!("{text}");
    Ok(())
}

pub(crate) fn render(
    raw: &Recipe,
    explicit: Option<&str>,
    host: &Host,
    list: bool,
    as_json: bool,
) -> Result<String, Stop> {
    if list {
        return Ok(render_list(raw, explicit, host, as_json));
    }
    let resolved = raw.resolve_profile(explicit, Some(host))?;
    if as_json {
        let out = effective_json(raw, &resolved, host)?;
        return Ok(format!(
            "{}\n",
            serde_json::to_string_pretty(&out).map_err(|e| Stop::Failed(e.to_string()))?
        ));
    }
    render_toml(&resolved)
}

fn render_toml(resolved: &Resolved) -> Result<String, Stop> {
    let mut out = String::new();
    let sel = match resolved.selection {
        Selection::Base => "base",
        Selection::Explicit => "explicit",
        Selection::Auto => "auto",
        Selection::Default => "default",
    };
    match &resolved.profile {
        Some(name) => {
            let _ = writeln!(out, "# profile: {name} ({sel})");
        }
        None => {
            let _ = writeln!(out, "# profile: none ({sel})");
        }
    }
    if resolved.filter.is_some() {
        if resolved.mismatches.is_empty() {
            let _ = writeln!(out, "# filter: matched");
        } else {
            let _ = writeln!(
                out,
                "# filter: MISMATCH ({})",
                resolved.mismatches.join("; ")
            );
        }
    }
    out.push_str(&resolved.recipe.effective_toml()?);
    Ok(out)
}

fn effective_json(raw: &Recipe, resolved: &Resolved, host: &Host) -> Result<Value, Stop> {
    let r = &resolved.recipe;
    let flags: Vec<String> = r
        .flags()
        .into_iter()
        .flat_map(|(k, v)| match v {
            Some(val) => vec![k, val],
            None => vec![k],
        })
        .collect();
    let lower = match &r.lower {
        Some(l) => serde_json::to_value(l).map_err(|e| Stop::Failed(e.to_string()))?,
        None => Value::Null,
    };
    let serve = serde_json::to_value(&r.serve).map_err(|e| Stop::Failed(e.to_string()))?;
    let config = serde_json::to_value(&r.config).map_err(|e| Stop::Failed(e.to_string()))?;
    let profiles = profile_entries(raw, resolved.profile.as_deref(), host);
    Ok(json!({
        "name": r.name,
        "about": r.about,
        "profile": resolved.profile,
        "selection": resolved.selection,
        "filter": resolved.filter,
        "filter_matches": resolved.mismatches.is_empty(),
        "filter_mismatches": resolved.mismatches,
        "host": {
            "backend": host.backend,
            "arch": host.arch,
            "device": host.device,
            "gpus": host.gpus,
            "vram_gib": (host.vram_gib() * 10.0).round() / 10.0,
            "host_gib": (host.host_gib() * 10.0).round() / 10.0,
            "integrated": host.integrated,
        },
        "weights": {
            "path": r.weights.path,
            "hf": r.weights.hf,
            "extra": r.weights.extra,
            "width": r.weights.width,
        },
        "names": r.names,
        "module": r.module,
        "script": r.script,
        "lower": lower,
        "serve": serve,
        "flags": flags,
        "config": config,
        "profiles": profiles,
    }))
}

fn profile_entries(raw: &Recipe, selected: Option<&str>, host: &Host) -> Vec<Value> {
    raw.profile
        .iter()
        .map(|(name, prof)| {
            let mismatches = prof
                .filter
                .as_ref()
                .map(|f| f.mismatches(host))
                .unwrap_or_default();
            json!({
                "name": name,
                "about": prof.about,
                "filter": prof.filter,
                "matches": mismatches.is_empty(),
                "mismatches": mismatches,
                "selected": selected == Some(name.as_str()),
            })
        })
        .collect()
}

fn render_list(raw: &Recipe, explicit: Option<&str>, host: &Host, as_json: bool) -> String {
    let selected = raw
        .resolve_profile(explicit, Some(host))
        .ok()
        .and_then(|r| r.profile);
    if as_json {
        let out = json!({
            "name": raw.name,
            "about": raw.about,
            "default_profile": raw.default_profile,
            "selected": selected,
            "profiles": profile_entries(raw, selected.as_deref(), host),
        });
        return format!(
            "{}\n",
            serde_json::to_string_pretty(&out).unwrap_or_default()
        );
    }
    let mut out = String::new();
    let _ = writeln!(out, "recipe: {}", raw.name);
    if let Some(def) = &raw.default_profile {
        let _ = writeln!(out, "default_profile: {def}");
    }
    if raw.profile.is_empty() {
        let _ = writeln!(out, "profiles: (none)");
        return out;
    }
    for (name, prof) in &raw.profile {
        let mark = if selected.as_deref() == Some(name.as_str()) {
            "*"
        } else {
            " "
        };
        let status = match &prof.filter {
            None => "no filter".to_string(),
            Some(f) => {
                let miss = f.mismatches(host);
                if miss.is_empty() {
                    "match".to_string()
                } else {
                    format!("no match: {}", miss.join("; "))
                }
            }
        };
        let about = prof.about.as_deref().unwrap_or("");
        if about.is_empty() {
            let _ = writeln!(out, "{mark} {name} [{status}]");
        } else {
            let _ = writeln!(out, "{mark} {name} [{status}] — {about}");
        }
    }
    out
}