diff --git a/backend/AGENTS.md b/backend/AGENTS.md index b9c2bda2..bf1dec63 100644 --- a/backend/AGENTS.md +++ b/backend/AGENTS.md @@ -110,8 +110,25 @@ backend/ ## CLI code -- `dotc` writes the exact three-line startup protocol to stdout after backend preparation; diagnostics and failures go to stderr, so stdout stays machine-readable. -- Guided prompts use the controlling terminal (`/dev/tty`) only, never stdout or stderr. +- Commands are `dotc `. Reuse the existing verbs (`list`, `show`, `catalog`, `deploy`, `pause`, `resume`, `teardown`, `logs`) before adding one, with the same meaning in every group. +- Aliases follow one policy in every group: `ls` for `list`, and plural nouns (`models`) as hidden aliases. A group's help describes the group; clap lists its verbs. +- Flags keep one name everywhere: `--name` for a display name, `--yes` to answer confirmations, `--manager` for the manager address, and the global `--yaml`. +- Streams: + - stdout carries human output, or exactly one YAML document per result under `--yaml`. + - stderr carries failures, warnings, notices, progress and diagnostics. + - Prompts, their context (reviews before a confirmation, commands to run on another machine) and confirmations use the controlling terminal (`/dev/tty`), never stdout or stderr. + - The server-run path is the exception: it writes only the exact three-line startup protocol to stdout. The `dev workload` JSON process protocol is the harness's contract and stays as is. +- Every command with a result takes `--yaml`; `server`, `code` and `dev` have none and refuse it. +- `--yaml` never prompts: a command that would ask fails, naming the flag that answers it. A failure prints nothing on stdout, its plain failure on stderr, and exits non-zero; errors are never YAML. A streaming command prints one document per entry, separated by `---`; a long-running one prints progress on stderr and one final document. +- A YAML document is the management response's proto JSON mapping (`pbjson`) rendered through `cli/src/output.rs`, plus the fields the CLI adds, such as resolved node names and the UTF-8 `text` of a log line next to its raw `content`. A view is an envelope of proto messages plus resolved names (a `#[serde(flatten)]` message beside the added fields), never a reshaping: no renamed, derived or dropped fields. Write one only when no single response holds the result. Mask secret values in the message unless the command's reveal flag is given. +- Commands that take a deployment, node or route resolve it through the shared resolver (`cli/src/reference.rs`), passing every candidate with its ID, shown name and aliases; never match names or IDs by hand. Its order (exact ID, exact name, ID fragment, name prefix, name words) is fixed: the first step that matches decides, and several matches there fail listing them, even when a later step would single one out. - Human output goes through the shared terminal layout (`cli/src/terminal/`) and failure rendering (`cli/src/failure.rs`); never hand-format tables, alignment or spacing. A failure is a one-line verdict, facts and copyable next commands; the cause chain shows only with `--verbose`. +- Success output carries no next-step commands. A fact the operator still needs, such as nodes to rejoin, is an info or warning line. - Wording is short and sentence case: say what happened or is asked, in operator words (`node`, `site`, `model`) rather than code identifiers, one success line per outcome; review blocks show only what the operator decides on. Explanations belong in `--help` and `docs/usage.md`. -- Result records, the startup protocol, JSON, exit codes and non-terminal stderr keep their plain stable form. +- YAML documents, the startup protocol, exit codes and non-terminal stderr keep their plain stable form. +- The `dotc model deploy` wizard (`cli/src/model/wizard/`) mirrors the console's model deploy dialog: the same steps, order, field placement and labels. The console leads: a dialog change is decided there, and the wizard follows it in the same change or records in its change why it differs. Context values, bounds, fits and warnings come from the server's answers, never from CLI arithmetic. The same holds for apps once `dotc` has an app wizard. +- Agent guides (`dotc --skill`) teach coding agents to use `dotc`; every agent reads the root one, so keep it small: + - The root guide (`cli/src/skill/guide.md`) holds only what every command group shares: what `dotc` is, output and `--yaml` rules, references. The command list is generated. + - A group's workflow goes in its own guide (`cli/src/skill/.md`, listed in `GROUP_GUIDES`, printed by `dotc --skill`), never in the root. Add one only when the group has a workflow its command list doesn't make obvious. + - A guide says which commands to run in which order and the rules an agent would get wrong. It never lists flags, defaults, ranges or output formats, which `--help` and the server own. Short sentences and lists; aim for under 60 lines. + - Keep guides true: a change to a command's flags, verbs, defaults or workflow updates the guide that mentions it in the same change. A contract test parses every `dotc` line a guide shows, but only a reader catches a wrong explanation. diff --git a/backend/Cargo.lock b/backend/Cargo.lock index ab6e2022..b4d751f6 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -1002,6 +1002,7 @@ dependencies = [ "rustls", "serde", "serde_json", + "serde_yaml_ng", "tempfile", "thiserror 2.0.21", "time", diff --git a/backend/cli/Cargo.toml b/backend/cli/Cargo.toml index 1ca55fb8..d33b3a66 100644 --- a/backend/cli/Cargo.toml +++ b/backend/cli/Cargo.toml @@ -45,6 +45,7 @@ ratatui = { version = "0.30.2", default-features = false, features = ["crossterm [dev-dependencies] dotcore = { path = "../core", features = ["test-support"] } +serde_yaml_ng.workspace = true tempfile.workspace = true tonic.workspace = true vt100 = "0.18.1" diff --git a/backend/cli/src/application/list.rs b/backend/cli/src/application/list.rs index b6bf93d1..3236990b 100644 --- a/backend/cli/src/application/list.rs +++ b/backend/cli/src/application/list.rs @@ -1,20 +1,20 @@ //! Shows the application deployments of the running site with their state, node and //! application, for example one ready Open WebUI and one paused. //! -//! On a terminal it prints a table; without one it prints one record block per deployment on -//! stdout, each carrying the id, name, state, node, application and whether the state is stale. +//! It prints a table, on the terminal or as plain text without one. Asked for YAML, it prints the +//! deployments as the manager returns them, with secret values masked. use clap::Args; use dotcore_proto::dotcore::application::v1::ApplicationDeployment; use super::{ - node_of, + document, node_of, projection::{application_display_name, observation_stale, presentation_name, state_label}, }; use crate::{ - management::{ManagerArgs, NodeNames, list_deployments, single_line}, - node::write_records, - terminal::{Message, TerminalCondition, controlling_terminal_condition, open_terminal}, + management::{DeploymentListDocument, ManagerArgs, NodeNames, list_deployments, single_line}, + output::{OutputFormat, present, write_yaml}, + terminal::Message, }; /// Arguments for listing application deployments. @@ -24,27 +24,28 @@ pub struct ApplicationListArgs { manager: ManagerArgs, } -/// Lists the application deployments on the terminal, else as records. -pub(crate) async fn application_list(arguments: ApplicationListArgs) -> anyhow::Result<()> { +/// Lists the application deployments as YAML when asked, else as a table. +pub(crate) async fn application_list( + arguments: ApplicationListArgs, + format: OutputFormat, +) -> anyhow::Result<()> { let manager = arguments.manager.connect().await?; let deployments = list_deployments::(&manager).await?; let nodes = manager.node_names().await; - if controlling_terminal_condition() == TerminalCondition::Interactive { - let mut terminal = open_terminal(); - if deployments.is_empty() { - terminal.message(&Message::Info("No application deployments".to_owned()))?; - } else { - terminal.message(&table(&deployments, &nodes))?; - } - return Ok(()); + if format == OutputFormat::Yaml { + return write_yaml(&DeploymentListDocument::new( + deployments + .into_iter() + .map(|deployment| document(deployment, &nodes, false)) + .collect(), + )); } - let blocks = deployments - .iter() - .map(|deployment| record_block(deployment, &nodes)) - .collect::>(); - write_records(&blocks.join("\n")) + if deployments.is_empty() { + return present(&[Message::Info("No application deployments".to_owned())]); + } + present(&[table(&deployments, &nodes)]) } /// Builds the deployments table, header first. A state the manager cannot confirm carries a @@ -79,19 +80,6 @@ fn table(deployments: &[ApplicationDeployment], nodes: &NodeNames) -> Message { } } -/// Renders one deployment as a record block ending in a newline. -fn record_block(deployment: &ApplicationDeployment, nodes: &NodeNames) -> String { - format!( - "Application deployment\nDOTCORE_APPLICATION_DEPLOYMENT_ID={}\nDOTCORE_APPLICATION_DEPLOYMENT_NAME={}\nDOTCORE_APPLICATION_DEPLOYMENT_STATE={}\nDOTCORE_APPLICATION_DEPLOYMENT_STALE={}\nDOTCORE_APPLICATION_DEPLOYMENT_NODE={}\nDOTCORE_APPLICATION_DEPLOYMENT_APPLICATION={}\n", - single_line(&deployment.application_deployment_id), - single_line(presentation_name(deployment)), - state_label(deployment), - observation_stale(deployment), - single_line(node_of(deployment, nodes)), - single_line(application_display_name(deployment)), - ) -} - #[cfg(test)] mod tests { use dotcore_proto::dotcore::application::v1::ApplicationDeployment; diff --git a/backend/cli/src/application/mod.rs b/backend/cli/src/application/mod.rs index 0a42feba..8e309cf8 100644 --- a/backend/cli/src/application/mod.rs +++ b/backend/cli/src/application/mod.rs @@ -3,8 +3,9 @@ //! //! Deployments are named by id or name and shown with the same state words as the web console, //! for example "Pausing" for a deployment asked to pause whose workload still runs. On a -//! terminal the commands print tables and messages; without one they print result records on -//! stdout, for example `DOTCORE_APPLICATION_DEPLOYMENT_STATE=Ready`. +//! terminal the commands print tables and messages, and as plain text without one. Asked for YAML, +//! every command prints the +//! manager's own message instead. mod list; mod parameters; @@ -16,8 +17,8 @@ use dotcore_proto::dotcore::{ application::v1::{ ApplicationDeployment, ApplicationDeploymentDesiredState, DeploymentLogEntry, DeploymentLogResumePosition, DeploymentLogSourceState, FollowDeploymentLogsRequest, - ListApplicationDeploymentsRequest, PauseDeploymentRequest, ReadDeploymentLogsRequest, - RemoveApplicationDeploymentRequest, ResumeDeploymentRequest, + GetApplicationDeploymentRequest, ListApplicationDeploymentsRequest, PauseDeploymentRequest, + ReadDeploymentLogsRequest, RemoveApplicationDeploymentRequest, ResumeDeploymentRequest, follow_deployment_logs_response, }, catalog::v1::StoragePlacement, @@ -26,13 +27,16 @@ use dotcore_proto::dotcore::{ use futures_util::StreamExt; use tonic::Status; -use crate::management::{ - DeploymentGroup, Lifecycle, LogEntry, LogEvent, LogEvents, LogPage, LogPosition, LogSource, - LogSourceState, LoggedDeployment, LogsArgs, ManagedDeployment, Manager, ManagerArgs, NodeNames, - change_lifecycle, deployment_logs, single_line, teardown, +use crate::{ + management::{ + DeploymentDocument, DeploymentGroup, Lifecycle, LogEntry, LogEvent, LogEvents, LogPage, + LogPosition, LogSource, LogSourceState, LoggedDeployment, LogsArgs, ManagedDeployment, + Manager, ManagerArgs, NodeNames, change_lifecycle, deployment_logs, single_line, teardown, + }, + output::OutputFormat, }; use list::{ApplicationListArgs, application_list}; -use projection::{desired_state_label, state_label}; +use projection::desired_state_label; use show::{ApplicationShowArgs, application_show}; /// Commands that manage the application deployments of a running site. @@ -46,40 +50,50 @@ pub struct ApplicationCommand { /// Actions supported by the application command group. #[derive(Debug, Subcommand)] enum ApplicationSubcommand { - /// List the application deployments with their state, node and application; runs against - /// the running site manager (`--manager`). + /// List the application deployments with their state and node + /// + /// Runs against the running site manager. #[command(alias = "ls")] List(ApplicationListArgs), - /// Show one application deployment by name or id. + /// Show one application deployment by name or ID Show(ApplicationShowArgs), - /// Ask the manager to pause an application deployment; returns without waiting for the pause. + /// Pause an application deployment, without waiting for it to pause Pause(LifecycleArgs), - /// Ask the manager to resume a paused application deployment; returns without waiting. + /// Resume a paused application deployment, without waiting for it to resume Resume(LifecycleArgs), - /// Remove an application deployment, its workloads and the data placed with it after - /// confirmation; data shared by the app is kept. + /// Remove an application deployment and its workloads after confirmation + /// + /// Removes the data placed with the deployment; data shared by the app is kept. Teardown(ApplicationTeardownArgs), - /// Print the most recent log lines of an application deployment, on any node, and follow - /// new ones with --follow; lines go to stdout and source states to stderr. + /// Print the recent log lines of an application deployment + /// + /// Reads from any node. With `--follow`, keeps printing new lines. Lines go to stdout and + /// source states to stderr. + #[command(mut_arg("reference", |argument| argument.help("Name or ID of the application deployment")))] Logs(LogsArgs), } impl ApplicationCommand { /// Runs the chosen action. - pub(crate) async fn dispatch(self) -> anyhow::Result<()> { + pub(crate) async fn dispatch(self, format: OutputFormat) -> anyhow::Result<()> { match self.command { - Some(ApplicationSubcommand::List(arguments)) => application_list(arguments).await, - Some(ApplicationSubcommand::Show(arguments)) => application_show(arguments).await, + Some(ApplicationSubcommand::List(arguments)) => { + application_list(arguments, format).await + } + Some(ApplicationSubcommand::Show(arguments)) => { + application_show(arguments, format).await + } Some(ApplicationSubcommand::Pause(arguments)) => { change_lifecycle::( &arguments.manager, &arguments.reference, Lifecycle::Pause, + format, ) .await } @@ -88,6 +102,7 @@ impl ApplicationCommand { &arguments.manager, &arguments.reference, Lifecycle::Resume, + format, ) .await } @@ -96,11 +111,12 @@ impl ApplicationCommand { &arguments.manager, &arguments.reference, arguments.yes, + format, ) .await } Some(ApplicationSubcommand::Logs(arguments)) => { - deployment_logs::(arguments).await + deployment_logs::(arguments, format).await } None => anyhow::bail!("application command requires an action"), } @@ -115,7 +131,7 @@ impl ApplicationCommand { /// Arguments selecting the application deployment to pause or resume. #[derive(Debug, Args)] struct LifecycleArgs { - /// Name or id of the application deployment. + /// Name or ID of the application deployment. #[arg(value_name = "DEPLOYMENT")] reference: String, @@ -126,7 +142,7 @@ struct LifecycleArgs { /// Arguments selecting the application deployment to tear down. #[derive(Debug, Args)] struct ApplicationTeardownArgs { - /// Name or id of the application deployment. + /// Name or ID of the application deployment. #[arg(value_name = "DEPLOYMENT")] reference: String, @@ -149,6 +165,16 @@ impl ManagedDeployment for ApplicationDeployment { .map(|response| response.into_inner().deployments) } + async fn get(manager: &Manager, id: &str) -> Result, Status> { + manager + .applications() + .get_application_deployment(GetApplicationDeploymentRequest { + application_deployment_id: id.to_owned(), + }) + .await + .map(|response| response.into_inner().deployment) + } + async fn request( manager: &Manager, id: String, @@ -177,6 +203,10 @@ impl ManagedDeployment for ApplicationDeployment { } } + fn placement(&self) -> Option<&ExactPlacement> { + self.placement.as_ref() + } + fn accepts(&self, lifecycle: Lifecycle) -> bool { self.desired_state() == match lifecycle { @@ -186,16 +216,16 @@ impl ManagedDeployment for ApplicationDeployment { } } - fn state_label(&self) -> &'static str { - state_label(self) - } - fn desired_state_label(&self) -> &'static str { desired_state_label(self.desired_state()) } /// What tearing a deployment down does to its data: storage placed with the deployment is /// deleted, storage shared by the app is kept, each listed by binding name. + fn mask_secrets(&mut self) { + parameters::mask_secrets(self); + } + fn teardown_consequence(&self) -> String { let bindings = |placement: StoragePlacement| { self.storage_attachments @@ -224,12 +254,14 @@ impl ManagedDeployment for ApplicationDeployment { } impl LoggedDeployment for ApplicationDeployment { + type Entry = DeploymentLogEntry; + async fn read_logs( manager: &Manager, id: String, sources: Vec, page_size: u32, - ) -> Result { + ) -> Result, Status> { let page = manager .applications() .read_deployment_logs(ReadDeploymentLogsRequest { @@ -267,7 +299,7 @@ impl LoggedDeployment for ApplicationDeployment { id: String, sources: Vec, positions: Vec, - ) -> Result { + ) -> Result, Status> { let events = manager .applications() .follow_deployment_logs(FollowDeploymentLogsRequest { @@ -316,13 +348,14 @@ fn log_source(name: String, label: String, state: DeploymentLogSourceState) -> L } } -fn log_entry(entry: DeploymentLogEntry) -> LogEntry { +fn log_entry(entry: DeploymentLogEntry) -> LogEntry { LogEntry { - source_name: entry.source_name, - source_label: entry.source_label, + source_name: entry.source_name.clone(), + source_label: entry.source_label.clone(), timestamp: entry.timestamp, - content: entry.content, + content: entry.content.clone(), truncated: entry.truncated, + message: entry, } } @@ -334,9 +367,16 @@ fn node_of<'a>(deployment: &'a ApplicationDeployment, nodes: &'a NodeNames) -> & .map_or("", |placement| nodes.display(&placement.site_node_id)) } -/// The exact placement of a deployment. -fn placement(deployment: &ApplicationDeployment) -> Option<&ExactPlacement> { - deployment.placement.as_ref() +/// The YAML document of a deployment, with its secret values masked unless revealed. +fn document( + mut deployment: ApplicationDeployment, + nodes: &NodeNames, + reveal_secrets: bool, +) -> DeploymentDocument { + if !reveal_secrets { + parameters::mask_secrets(&mut deployment); + } + DeploymentDocument::new(deployment, nodes) } #[cfg(test)] diff --git a/backend/cli/src/application/parameters.rs b/backend/cli/src/application/parameters.rs index 8e836307..a6de889c 100644 --- a/backend/cli/src/application/parameters.rs +++ b/backend/cli/src/application/parameters.rs @@ -2,7 +2,7 @@ use dotcore_proto::dotcore::application::v1::ApplicationDeployment; -use crate::parameters::{ParameterInput, ParameterRow, retained}; +use crate::parameters::{ParameterInput, ParameterRow, mask_secret_values, retained}; /// The deployment's retained parameters in catalog order. A parameter without a retained value, /// such as one its switch disabled, is left out. @@ -27,3 +27,15 @@ pub(super) fn rows(deployment: &ApplicationDeployment, reveal_secrets: bool) -> }) .collect() } + +/// Masks the deployment's secret parameter values in place. +pub(super) fn mask_secrets(deployment: &mut ApplicationDeployment) { + let Some(snapshot) = deployment.snapshot.as_mut() else { + return; + }; + let definitions = snapshot + .graph + .as_ref() + .map_or(&[][..], |graph| &graph.parameters); + mask_secret_values(definitions, &mut snapshot.parameter_values); +} diff --git a/backend/cli/src/application/projection.rs b/backend/cli/src/application/projection.rs index df657618..19d3e589 100644 --- a/backend/cli/src/application/projection.rs +++ b/backend/cli/src/application/projection.rs @@ -10,7 +10,7 @@ use dotcore_proto::dotcore::application::v1::{ ApplicationReadinessState, ApplicationServiceLifecycleState, }; -use crate::management::Addressable; +use crate::reference::Referable; /// The state word of the deployment, for example `Pausing`. A requested teardown reads /// `Tearing down`, a requested pause reads `Pausing` until the workloads are paused or @@ -184,7 +184,7 @@ fn lifecycle_label(state: ApplicationLifecycleState) -> &'static str { } } -impl Addressable for ApplicationDeployment { +impl Referable for ApplicationDeployment { fn id(&self) -> &str { &self.application_deployment_id } @@ -193,8 +193,8 @@ impl Addressable for ApplicationDeployment { presentation_name(self) } - fn stored_name(&self) -> &str { - &self.application_deployment_name + fn aliases(&self) -> Vec<&str> { + vec![&self.application_deployment_name] } } diff --git a/backend/cli/src/application/show.rs b/backend/cli/src/application/show.rs index 24b24aa8..3e34d40d 100644 --- a/backend/cli/src/application/show.rs +++ b/backend/cli/src/application/show.rs @@ -1,14 +1,14 @@ //! Shows what an operator needs to manage one application deployment, for example its state, //! node, endpoint, services or failure message. //! -//! On a terminal it prints labeled values for what is known; without one it prints one record -//! block on stdout that always carries every key, empty when the value is absent. +//! It prints labeled values for what is known, on the terminal or as plain text without one. Asked +//! for YAML, it prints the deployment as the manager returns it, with secret values masked unless revealed. use clap::Args; use dotcore_proto::dotcore::application::v1::ApplicationDeployment; use super::{ - node_of, parameters, placement, + document, node_of, parameters, projection::{ application_display_name, desired_state_label, endpoint, observation_stale, presentation_name, readiness, readiness_label, service_label, state_label, @@ -16,16 +16,16 @@ use super::{ }, }; use crate::{ - management::{ManagerArgs, NodeNames, find_deployment, single_line}, - node::write_records, - parameters::{ParameterRow, record_lines, write_parameters}, - terminal::{Message, TerminalCondition, controlling_terminal_condition, open_terminal}, + management::{ManagedDeployment, ManagerArgs, NodeNames, find_deployment, single_line}, + output::{OutputFormat, present, write_yaml}, + parameters::{ParameterRow, parameter_messages}, + terminal::Message, }; /// Arguments selecting the application deployment to show. #[derive(Debug, Args)] pub struct ApplicationShowArgs { - /// Name or id of the application deployment. + /// Name or ID of the application deployment. #[arg(value_name = "DEPLOYMENT")] reference: String, @@ -37,26 +37,28 @@ pub struct ApplicationShowArgs { manager: ManagerArgs, } -/// Shows the deployment on the terminal, else as a record block. -pub(crate) async fn application_show(arguments: ApplicationShowArgs) -> anyhow::Result<()> { +/// Shows the deployment as YAML when asked, else as labeled values. +pub(crate) async fn application_show( + arguments: ApplicationShowArgs, + format: OutputFormat, +) -> anyhow::Result<()> { let manager = arguments.manager.connect().await?; let deployment = find_deployment::(&manager, &arguments.reference).await?; let nodes = manager.node_names().await; - let details = Details::of(&deployment, &nodes, arguments.reveal_secrets); - if controlling_terminal_condition() == TerminalCondition::Interactive { - let mut terminal = open_terminal(); - terminal.message(&Message::Heading(format!( - "Application deployment {}", - details.name - )))?; - terminal.message(&Message::KeyValues(details.pairs()))?; - write_parameters(&mut *terminal, &details.parameters)?; - return Ok(()); + if format == OutputFormat::Yaml { + return write_yaml(&document(deployment, &nodes, arguments.reveal_secrets)); } - write_records(&details.record_block()) + let details = Details::of(&deployment, &nodes, arguments.reveal_secrets); + + let mut messages = vec![ + Message::Heading(format!("Application deployment {}", details.name)), + Message::KeyValues(details.pairs()), + ]; + messages.extend(parameter_messages(&details.parameters)); + present(&messages) } /// The shown facts of one deployment; absent facts are empty. @@ -133,14 +135,21 @@ impl Details { readiness, stale: observation_stale(deployment), node: single_line(node_of(deployment, nodes)), - execution_target: placement(deployment).map_or_else(String::new, |placement| { - single_line(&placement.execution_target_id) - }), - execution_target_name: placement(deployment).map_or_else(String::new, |placement| { - single_line( - nodes.target_display(&placement.site_node_id, &placement.execution_target_id), - ) - }), + execution_target: deployment + .placement() + .map_or_else(String::new, |placement| { + single_line(&placement.execution_target_id) + }), + execution_target_name: deployment + .placement() + .map_or_else(String::new, |placement| { + single_line( + nodes.target_display( + &placement.site_node_id, + &placement.execution_target_id, + ), + ) + }), application: single_line(application_display_name(deployment)), services, endpoint: single_line(endpoint(deployment)), @@ -183,34 +192,4 @@ impl Details { pairs.retain(|(_, value)| !value.is_empty()); pairs } - - fn record_block(&self) -> String { - let services = self - .services - .iter() - .map(|(name, state)| format!("{name}: {state}")) - .collect::>() - .join(", "); - let mut block = format!( - "Application deployment\nDOTCORE_APPLICATION_DEPLOYMENT_ID={}\nDOTCORE_APPLICATION_DEPLOYMENT_NAME={}\nDOTCORE_APPLICATION_DEPLOYMENT_STATE={}\nDOTCORE_APPLICATION_DEPLOYMENT_DESIRED_STATE={}\nDOTCORE_APPLICATION_DEPLOYMENT_READINESS={}\nDOTCORE_APPLICATION_DEPLOYMENT_STALE={}\nDOTCORE_APPLICATION_DEPLOYMENT_NODE={}\nDOTCORE_APPLICATION_DEPLOYMENT_EXECUTION_TARGET={}\nDOTCORE_APPLICATION_DEPLOYMENT_APPLICATION={}\nDOTCORE_APPLICATION_DEPLOYMENT_SERVICES={services}\nDOTCORE_APPLICATION_DEPLOYMENT_ENDPOINT={}\nDOTCORE_APPLICATION_DEPLOYMENT_ROUTE={}\nDOTCORE_APPLICATION_DEPLOYMENT_FAILURE={}\nDOTCORE_APPLICATION_DEPLOYMENT_MESSAGE={}\n", - self.id, - self.name, - self.state, - self.desired_state, - self.readiness, - self.stale, - self.node, - self.execution_target, - self.application, - self.endpoint, - self.route, - self.failure, - self.message, - ); - block.push_str(&record_lines( - "DOTCORE_APPLICATION_DEPLOYMENT_PARAMETER", - &self.parameters, - )); - block - } } diff --git a/backend/cli/src/code/mod.rs b/backend/cli/src/code/mod.rs index faca6d56..1b223cda 100644 --- a/backend/cli/src/code/mod.rs +++ b/backend/cli/src/code/mod.rs @@ -105,7 +105,7 @@ impl CodeArgs { /// The named route, else the one picked on the terminal. fn choose_route<'a>(&self, routes: &'a [String]) -> anyhow::Result<&'a str> { match &self.model { - Some(name) => Ok(find_route(self.agent, routes, name)?), + Some(name) => find_route(self.agent, routes, name), // The picker's terminal is dropped at the end of this arm, restoring the terminal // mode before the agent takes it over. None => pick_route(self.agent, routes, open_terminal().as_mut()), @@ -142,7 +142,7 @@ pub(crate) enum CodeError { #[error("the site has no ready inference route; create one, or wait for its model to be ready")] NoRoute, - #[error("no ready inference route is named {name:?}; ready routes: {}", .ready.join(", "))] + #[error("no ready inference route matches {name:?}; ready routes: {}", .ready.join(", "))] UnknownRoute { agent: CodingAgent, name: String, @@ -201,7 +201,7 @@ mod tests { ]) .expect("code command"); - let Command::Code(code) = cli.command else { + let Some(Command::Code(code)) = cli.command else { panic!("code command"); }; assert_eq!(code.agent, CodingAgent::Opencode); diff --git a/backend/cli/src/code/selection.rs b/backend/cli/src/code/selection.rs index f0c06f3e..aaa037e6 100644 --- a/backend/cli/src/code/selection.rs +++ b/backend/cli/src/code/selection.rs @@ -1,31 +1,34 @@ //! Chooses the inference route a coding agent starts with, among the routes the inference API //! lists: the one the operator named, else the one picked on the terminal. //! -//! A named route must be listed. Without a name the operator picks on the controlling terminal; -//! without a terminal the command asks for a name instead. +//! A named route must be listed, and may be named by a unique part of its name. Without a name +//! the operator picks on the controlling terminal; without a terminal the command asks for a name +//! instead. use super::{CodeError, CodingAgent}; use crate::{ management::single_line, + reference::{Referable, ReferenceError, ReferenceKind, resolve}, terminal::{SelectItem, SelectPrompt, Terminal, TerminalCondition}, }; -/// Finds the listed route named `name` for `agent`. +/// Finds the listed route that `name` names for `agent`. pub(super) fn find_route<'a>( agent: CodingAgent, routes: &'a [String], name: &str, -) -> Result<&'a str, CodeError> { +) -> anyhow::Result<&'a str> { require_routes(routes)?; - routes - .iter() - .find(|route| *route == name) - .map(String::as_str) - .ok_or_else(|| CodeError::UnknownRoute { + match resolve(ReferenceKind::Route, name, routes) { + Ok(route) => Ok(route), + Err(ReferenceError::Unknown { .. }) => Err(CodeError::UnknownRoute { agent, name: name.to_owned(), ready: route_names(routes), - }) + } + .into()), + Err(error) => Err(error.into()), + } } /// Asks the operator to pick a route on `terminal`. @@ -50,6 +53,17 @@ pub(super) fn pick_route<'a>( Ok(&routes[terminal.select(&prompt)?]) } +/// A route is named by its name alone, which also serves as its id. +impl Referable for String { + fn id(&self) -> &str { + self + } + + fn name(&self) -> &str { + self + } +} + fn require_routes(routes: &[String]) -> Result<(), CodeError> { if routes.is_empty() { return Err(CodeError::NoRoute); @@ -71,18 +85,28 @@ mod tests { } #[test] - fn a_named_route_must_be_listed() { - let routes = routes(); - + fn a_named_route_must_be_listed_and_may_be_named_by_a_unique_part() { + let routes = ["draft", "qwen-chat", "qwen-code"] + .map(str::to_owned) + .to_vec(); + let find = + |name| find_route(CodingAgent::Opencode, &routes, name).map_err(|e| e.to_string()); + + assert_eq!(find("qwen-chat"), Ok("qwen-chat")); + assert_eq!(find("Draft"), Ok("draft")); + assert_eq!(find("code"), Ok("qwen-code")); + assert_eq!(find("dra"), Ok("draft")); assert_eq!( - find_route(CodingAgent::Opencode, &routes, "chat").ok(), - Some("chat") + find("qwen"), + Err("2 inference routes match \"qwen\": qwen-chat, qwen-code".to_owned()) ); assert_eq!( - find_route(CodingAgent::Opencode, &routes, "Chat") - .expect_err("names match exactly") - .to_string(), - "no ready inference route is named \"Chat\"; ready routes: draft, chat, code" + find("d"), + Err( + "no ready inference route matches \"d\"; ready routes: draft, qwen-chat, \ + qwen-code" + .to_owned() + ) ); } @@ -90,9 +114,10 @@ mod tests { fn no_listed_route_fails_before_naming_or_picking() { let mut terminal = ScriptedTerminal::interactive([]); + let error = find_route(CodingAgent::Opencode, &[], "chat").expect_err("no route"); assert!(matches!( - find_route(CodingAgent::Opencode, &[], "chat"), - Err(CodeError::NoRoute) + error.downcast_ref::(), + Some(CodeError::NoRoute) )); let error = pick_route(CodingAgent::Opencode, &[], &mut terminal).expect_err("no route"); assert!(matches!( diff --git a/backend/cli/src/config.rs b/backend/cli/src/config.rs index 3bfb29d2..4e3fbf7d 100644 --- a/backend/cli/src/config.rs +++ b/backend/cli/src/config.rs @@ -4,12 +4,20 @@ //! The configuration command reports path policy and the node host a manager site records, //! without mutating the site or creating directories. +use std::path::PathBuf; + use anyhow::Result; -use clap::{Args, Subcommand, ValueEnum}; +use clap::{Args, Subcommand}; use dotcore::composition::{NodeRole, node_role}; use dotcore_domain::ResolvedSitePaths; +use serde::Serialize; -use crate::{RootPathArgs, site::recorded_host}; +use crate::{ + RootPathArgs, + output::{OutputFormat, write_plain, write_yaml}, + site::recorded_host, + terminal::Message, +}; /// Commands that inspect effective Dotcore process configuration. #[derive(Debug, Args)] @@ -21,51 +29,99 @@ pub struct ConfigCommand { #[derive(Debug, Subcommand)] enum ConfigSubcommand { - /// Show effective process paths, the node role (`manager` or `joined-node`), and the node - /// host a manager site records, without mutating the site. - Show(ConfigShowArgs), + /// Show the effective process paths and this site folder's role + /// + /// Also shows the node host a manager site records. Nothing is changed. + Show, } -#[derive(Debug, Args)] -struct ConfigShowArgs { - /// Select the machine-readable output representation. - #[arg(long, value_enum)] - format: ConfigFormat, +impl ConfigCommand { + pub(crate) fn dispatch(self, paths: &RootPathArgs, format: OutputFormat) -> Result<()> { + let Some(ConfigSubcommand::Show) = self.command else { + anyhow::bail!("config command requires an action"); + }; + let document = ConfigDocument::of(paths.process_paths()?); + if format == OutputFormat::Yaml { + return write_yaml(&document); + } + write_plain(&[Message::KeyValues(document.pairs())]) + } } -#[derive(Clone, Copy, Debug, ValueEnum)] -enum ConfigFormat { - Json, +/// The effective process configuration: where the process keeps its files and what role the +/// folder gives it. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct ConfigDocument { + role: &'static str, + site_dir: PathBuf, + + /// The master catalog folder, when one is configured. + #[serde(skip_serializing_if = "Option::is_none")] + master_catalog_dir: Option, + + cache_dir: PathBuf, + model_artifact_cache_dir: PathBuf, + workload_cache_dir: PathBuf, + + /// The node host a manager site records; absent for a joined node or an uninitialized site. + #[serde(skip_serializing_if = "Option::is_none")] + node_host: Option, } -impl ConfigCommand { - pub(crate) fn dispatch(self, paths: &RootPathArgs) -> Result<()> { - let Some(ConfigSubcommand::Show(arguments)) = self.command else { - anyhow::bail!("config command requires an action"); +impl ConfigDocument { + fn of(paths: ResolvedSitePaths) -> Self { + let (role, node_host) = match node_role(&paths.root) { + NodeRole::Manager => ("manager", recorded_host(&paths.root)), + // A joined node folder holds no site inputs, so it records no node host here. + NodeRole::JoinedNode => ("joined-node", None), }; - match arguments.format { - ConfigFormat::Json => show_json(paths.process_paths()?), + Self { + role, + model_artifact_cache_dir: paths.model_artifact_cache_root(), + workload_cache_dir: paths.workload_cache_root(), + site_dir: paths.root, + master_catalog_dir: paths.master_catalog_root, + cache_dir: paths.cache_root, + node_host: node_host.map(|host| host.to_string()), } } -} -fn show_json(paths: ResolvedSitePaths) -> Result<()> { - let (role, node_host) = match node_role(&paths.root) { - NodeRole::Manager => ("manager", recorded_host(&paths.root)), - // A joined node folder holds no site inputs, so it records no node host here. - NodeRole::JoinedNode => ("joined-node", None), - }; - let output = serde_json::json!({ - "role": role, - "siteDir": paths.root, - "masterCatalogDir": paths.master_catalog_root, - "cacheDir": paths.cache_root, - "modelArtifactCacheDir": paths.model_artifact_cache_root(), - "workloadCacheDir": paths.workload_cache_root(), - "nodeHost": node_host.map(|host| host.to_string()), - }); - println!("{output}"); - Ok(()) + /// The facts as labeled values, without the node host when none is recorded. + fn pairs(&self) -> Vec<(String, String)> { + let mut pairs = vec![ + ("role".to_owned(), self.role.to_owned()), + ( + "site folder".to_owned(), + self.site_dir.display().to_string(), + ), + ( + "cache folder".to_owned(), + self.cache_dir.display().to_string(), + ), + ( + "model artifact cache folder".to_owned(), + self.model_artifact_cache_dir.display().to_string(), + ), + ( + "workload cache folder".to_owned(), + self.workload_cache_dir.display().to_string(), + ), + ]; + if let Some(catalog) = &self.master_catalog_dir { + pairs.insert( + 2, + ( + "master catalog folder".to_owned(), + catalog.display().to_string(), + ), + ); + } + if let Some(host) = &self.node_host { + pairs.push(("node host".to_owned(), host.clone())); + } + pairs + } } /// Reads one process variable: `None` when it is unset, an error when it is not valid UTF-8. diff --git a/backend/cli/src/deploy/mod.rs b/backend/cli/src/deploy/mod.rs new file mode 100644 index 00000000..ab108db1 --- /dev/null +++ b/backend/cli/src/deploy/mod.rs @@ -0,0 +1,226 @@ +//! Inputs every deploy command shares: `--set` overrides and the plain values they carry. +//! +//! An override, or an answer given step by step, holds a value as written: a boolean, a number or +//! text. It gets its parameter's type here, so a mistyped value fails naming the parameter before +//! anything is sent. Ranges, choices and completeness stay with the server, which validates every +//! deployment. + +use std::fmt; + +/// A value as an override or an answer writes it, before it gets its parameter's type. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum PlainValue { + /// A boolean. + Boolean(bool), + + /// A non-negative integer. + Number(u64), + + /// Text, as every `--set` value is written. + Text(String), +} + +impl PlainValue { + /// The value with the given type: a boolean from `true` or `false`, an integer from its + /// decimal digits, and text from any scalar. Fails with what the type expects. + pub(crate) fn typed(&self, kind: ValueKind) -> Result { + match (kind, self) { + (ValueKind::Boolean, Self::Boolean(value)) => Ok(TypedValue::Boolean(*value)), + (ValueKind::Boolean, Self::Text(text)) => match text.as_str() { + "true" => Ok(TypedValue::Boolean(true)), + "false" => Ok(TypedValue::Boolean(false)), + _ => Err(ValueError::Expected(kind)), + }, + (ValueKind::UnsignedInteger, Self::Number(value)) => { + Ok(TypedValue::UnsignedInteger(*value)) + } + (ValueKind::UnsignedInteger, Self::Text(text)) => text + .parse() + .map(TypedValue::UnsignedInteger) + .map_err(|_| ValueError::Expected(kind)), + (ValueKind::Text, Self::Text(text)) => Ok(TypedValue::Text(text.clone())), + (ValueKind::Text, Self::Number(value)) => Ok(TypedValue::Text(value.to_string())), + (ValueKind::Text, Self::Boolean(value)) => Ok(TypedValue::Text(value.to_string())), + (ValueKind::Boolean | ValueKind::UnsignedInteger, _) => Err(ValueError::Expected(kind)), + } + } +} + +/// The type a parameter gives its value. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum ValueKind { + /// `true` or `false`. + Boolean, + + /// A non-negative whole number. + UnsignedInteger, + + /// Text: a choice, free text or a secret. + Text, +} + +impl fmt::Display for ValueKind { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::Boolean => "true or false", + Self::UnsignedInteger => "a whole number", + Self::Text => "text", + }) + } +} + +/// A value with its parameter's type. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum TypedValue { + /// A boolean value. + Boolean(bool), + + /// An unsigned integer value. + UnsignedInteger(u64), + + /// A text value. + Text(String), +} + +impl From for PlainValue { + fn from(value: TypedValue) -> Self { + match value { + TypedValue::Boolean(value) => Self::Boolean(value), + TypedValue::UnsignedInteger(value) => Self::Number(value), + TypedValue::Text(value) => Self::Text(value), + } + } +} + +/// Why a value doesn't have its parameter's type. +#[derive(Debug, thiserror::Error)] +pub(crate) enum ValueError { + /// The value is of another type than the parameter's. + #[error("expects {0}")] + Expected(ValueKind), +} + +/// One `--set =` override, applied over the starting values. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct Setting { + /// What the override sets, such as a parameter ID. + pub(crate) key: String, + + /// The value as written. + pub(crate) value: PlainValue, +} + +impl Setting { + /// Parses `=` for clap; the value may itself contain `=`. + pub(crate) fn parse(text: &str) -> Result { + match text.split_once('=') { + Some((key, value)) if !key.is_empty() => Ok(Self { + key: key.to_owned(), + value: PlainValue::Text(value.to_owned()), + }), + _ => Err("expected =".to_owned()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_values_take_their_parameter_type() { + let cases = [ + ( + PlainValue::Boolean(true), + ValueKind::Boolean, + TypedValue::Boolean(true), + ), + ( + PlainValue::Text("false".into()), + ValueKind::Boolean, + TypedValue::Boolean(false), + ), + ( + PlainValue::Number(4), + ValueKind::UnsignedInteger, + TypedValue::UnsignedInteger(4), + ), + ( + PlainValue::Text("32768".into()), + ValueKind::UnsignedInteger, + TypedValue::UnsignedInteger(32768), + ), + ( + PlainValue::Text("f16".into()), + ValueKind::Text, + TypedValue::Text("f16".into()), + ), + ( + PlainValue::Number(8), + ValueKind::Text, + TypedValue::Text("8".into()), + ), + ( + PlainValue::Boolean(true), + ValueKind::Text, + TypedValue::Text("true".into()), + ), + ]; + for (plain, kind, typed) in cases { + assert_eq!( + plain.typed(kind).expect("typed"), + typed, + "{plain:?} as {kind:?}" + ); + } + } + + #[test] + fn a_value_of_another_type_says_what_the_parameter_expects() { + let cases = [ + ( + PlainValue::Text("yes".into()), + ValueKind::Boolean, + "expects true or false", + ), + ( + PlainValue::Number(1), + ValueKind::Boolean, + "expects true or false", + ), + ( + PlainValue::Text("-1".into()), + ValueKind::UnsignedInteger, + "expects a whole number", + ), + ( + PlainValue::Boolean(true), + ValueKind::UnsignedInteger, + "expects a whole number", + ), + ]; + for (plain, kind, message) in cases { + let error = plain.typed(kind).expect_err("mistyped"); + assert_eq!(error.to_string(), message, "{plain:?} as {kind:?}"); + } + } + + #[test] + fn a_setting_splits_at_the_first_equals_sign() { + assert_eq!( + Setting::parse("custom=a=b").expect("setting"), + Setting { + key: "custom".into(), + value: PlainValue::Text("a=b".into()), + } + ); + assert_eq!( + Setting::parse("=1").expect_err("no key"), + "expected =" + ); + assert_eq!( + Setting::parse("total").expect_err("no value"), + "expected =" + ); + } +} diff --git a/backend/cli/src/failure.rs b/backend/cli/src/failure.rs index bc9d173a..158775ec 100644 --- a/backend/cli/src/failure.rs +++ b/backend/cli/src/failure.rs @@ -24,8 +24,9 @@ use tonic::Code; use crate::{ code::{CodeError, CodingAgent}, hint, - management::{DeploymentGroup, ManagementError, ReferenceError}, + management::{DeploymentGroup, ManagementError}, node::RejoinNameMismatch, + reference::{Candidate, ReferenceError, ReferenceKind}, terminal::{Message, NextStep}, }; @@ -485,25 +486,69 @@ fn manager_message(message: &str) -> Vec { fn reference_failure(error: &ReferenceError) -> Typed { match error { - ReferenceError::Unknown { group, reference } => ( + ReferenceError::Unknown { + kind: ReferenceKind::Deployment(group), + reference, + .. + } => ( format!("No {} matches {reference}", group.noun()), Vec::new(), vec![list_step(*group)], ), + ReferenceError::Unknown { + kind, + reference, + known, + } => ( + format!("No {} matches {reference}", kind.noun()), + candidate_table(*kind, known), + vec![pass_candidate_step(*kind)], + ), ReferenceError::Ambiguous { - group, + kind, reference, - ids, + matches, } => ( - format!("{} {}s are named {reference}", ids.len(), group.noun()), - ids.iter() - .map(|id| Message::Info(format!(" {id}"))) - .collect(), - vec![NextStep::new("Pass one of these ids instead")], + format!("{} {}s match {reference}", matches.len(), kind.noun()), + candidate_table(*kind, matches), + vec![pass_candidate_step(*kind)], ), } } +/// The objects a reference could name, by id and name, or by name for a kind without ids. +fn candidate_table(kind: ReferenceKind, candidates: &[Candidate]) -> Vec { + if candidates.is_empty() { + return Vec::new(); + } + let (header, rows) = if kind.has_ids() { + ( + vec!["ID".to_owned(), "NAME".to_owned()], + candidates + .iter() + .map(|candidate| vec![candidate.id.clone(), candidate.name.clone()]) + .collect(), + ) + } else { + ( + vec!["NAME".to_owned()], + candidates + .iter() + .map(|candidate| vec![candidate.name.clone()]) + .collect(), + ) + }; + vec![Message::Table { header, rows }] +} + +fn pass_candidate_step(kind: ReferenceKind) -> NextStep { + if kind.has_ids() { + NextStep::new("Pass one of these ids instead") + } else { + NextStep::new("Pass one of these names instead") + } +} + fn code_failure(error: &CodeError) -> Typed { let route_facts = |ready: &[String]| { ready @@ -535,7 +580,7 @@ fn code_failure(error: &CodeError) -> Typed { )], ), CodeError::UnknownRoute { agent, name, ready } => ( - format!("No ready inference route is named {name}"), + format!("No ready inference route matches {name}"), route_facts(ready), vec![ pass_route_step(*agent), @@ -669,10 +714,9 @@ mod tests { use super::{Failure, chain_line}; use crate::{ - management::{ - DeploymentGroup, ManagementError, Manager, ManagerAddress, ReferenceError, call_failed, - }, + management::{DeploymentGroup, ManagementError, Manager, ManagerAddress, call_failed}, node::RejoinNameMismatch, + reference::{Candidate, ReferenceError, ReferenceKind}, terminal::{Message, NextStep}, }; @@ -1219,44 +1263,98 @@ mod tests { } #[test] - fn unknown_and_ambiguous_references_point_at_the_list_or_the_ids() { + fn unknown_and_ambiguous_references_point_at_the_list_or_the_candidates() { + let candidate = |id: &str, name: &str| Candidate { + id: id.to_owned(), + name: name.to_owned(), + }; let unknown = anyhow::Error::new(ReferenceError::Unknown { - group: DeploymentGroup::Model, + kind: ReferenceKind::Deployment(DeploymentGroup::Model), reference: "gemma".to_owned(), + known: vec![candidate("qwen3-8-27b-3cfmn", "Qwen 3.8 27B")], }); let ambiguous = anyhow::Error::new(ReferenceError::Ambiguous { - group: DeploymentGroup::Model, - reference: "Qwen".to_owned(), - ids: vec!["model-2".to_owned(), "model-3".to_owned()], + kind: ReferenceKind::Deployment(DeploymentGroup::Model), + reference: "qwen".to_owned(), + matches: vec![ + candidate("qwen3-8-27b-3cfmn", "Qwen 3.8 27B"), + candidate("qwen3-8-8b-7tq2m", "Qwen 3.8 8B"), + ], + }); + let unknown_node = anyhow::Error::new(ReferenceError::Unknown { + kind: ReferenceKind::Node, + reference: "gpu9".to_owned(), + known: vec![ + candidate("node-00aa", "gpu1"), + candidate("node-00bb", "gpu2"), + ], + }); + let ambiguous_route = anyhow::Error::new(ReferenceError::Ambiguous { + kind: ReferenceKind::Route, + reference: "co".to_owned(), + matches: vec![candidate("code", "code"), candidate("coder", "coder")], }); assert_eq!( - lines(&Failure::from_error(&unknown), false), + lines(&Failure::from_error(&unknown), true), [ "✘ No model deployment matches gemma", "Next", " › List the model deployments:", " dotc model list", + "Cause", + " no model deployment matches \"gemma\"", ] ); assert_eq!( chain_line(&unknown), - "no model deployment is named or has id \"gemma\"; see `dotc model list`" + "no model deployment matches \"gemma\"; see `dotc model list`" ); assert_eq!( lines(&Failure::from_error(&ambiguous), false), [ - "✘ 2 model deployments are named Qwen", - " model-2", - " model-3", + "✘ 2 model deployments match qwen", + " ID NAME", + " qwen3-8-27b-3cfmn Qwen 3.8 27B", + " qwen3-8-8b-7tq2m Qwen 3.8 8B", "Next", " › Pass one of these ids instead", ] ); assert_eq!( chain_line(&ambiguous), - "2 model deployments are named \"Qwen\": model-2, model-3; pass one of the ids \ - instead" + "2 model deployments match \"qwen\": qwen3-8-27b-3cfmn (Qwen 3.8 27B), \ + qwen3-8-8b-7tq2m (Qwen 3.8 8B); pass one of the ids instead" + ); + assert_eq!( + lines(&Failure::from_error(&unknown_node), false), + [ + "✘ No node matches gpu9", + " ID NAME", + " node-00aa gpu1", + " node-00bb gpu2", + "Next", + " › Pass one of these ids instead", + ] + ); + assert_eq!( + chain_line(&unknown_node), + "no node matches \"gpu9\"; known nodes: node-00aa (gpu1), node-00bb (gpu2)" + ); + assert_eq!( + lines(&Failure::from_error(&ambiguous_route), false), + [ + "✘ 2 inference routes match co", + " NAME", + " code", + " coder", + "Next", + " › Pass one of these names instead", + ] + ); + assert_eq!( + chain_line(&ambiguous_route), + "2 inference routes match \"co\": code, coder; pass one of the names instead" ); } @@ -1271,7 +1369,7 @@ mod tests { assert_eq!( lines(&Failure::from_error(&error), false), [ - "✘ No ready inference route is named draft", + "✘ No ready inference route matches draft", " chat", " code", "Next", diff --git a/backend/cli/src/gc/mod.rs b/backend/cli/src/gc/mod.rs index 6c2b8011..c930beac 100644 --- a/backend/cli/src/gc/mod.rs +++ b/backend/cli/src/gc/mod.rs @@ -4,8 +4,9 @@ //! behind by an older loader once no node pins it, then shared workload storage that no workload //! has used for a number of days. Each step lists what it would remove and asks for confirmation //! before removing it. It acts on the whole machine, so it needs neither a running server nor a -//! site, and it never adds Nix roots or runs Nix garbage collection. On a terminal it prints -//! tables; without one it prints one record block per removal on stdout. +//! site, and it never adds Nix roots or runs Nix garbage collection. It prints +//! tables, on the terminal or as plain text without one. Asked for YAML, it +//! never asks, so it needs confirmation in advance, and prints one document of every removal. mod storage; @@ -16,14 +17,12 @@ use clap::Args; use dotcore_artifact::{ DockerOciClient, ImageCleanup, ImageRemoval, RemovalOutcome, RemovalReason, }; +use serde::Serialize; use crate::{ RootPathArgs, - node::{record_value, write_records}, - terminal::{ - ConfirmPrompt, Message, PromptError, Terminal, TerminalCondition, - controlling_terminal_condition, open_terminal, - }, + output::{LazyTerminal, OutputFormat, present_on, write_yaml}, + terminal::{ConfirmPrompt, Message, PromptError, Terminal, TerminalCondition}, }; /// Arguments of `dotc gc`. @@ -41,12 +40,26 @@ pub struct GcCommand { } impl GcCommand { - pub(crate) async fn dispatch(self, paths: &RootPathArgs) -> anyhow::Result<()> { - self.clean_images(paths).await?; - storage::clean(paths, self.unused_days, self.yes).await + pub(crate) async fn dispatch( + self, + paths: &RootPathArgs, + format: OutputFormat, + ) -> anyhow::Result<()> { + let images = self.clean_images(paths, format).await?; + let storage = storage::clean(paths, self.unused_days, self.yes, format).await?; + if format == OutputFormat::Yaml { + write_yaml(&GcDocument { images, storage })?; + } + Ok(()) } - async fn clean_images(&self, paths: &RootPathArgs) -> anyhow::Result<()> { + /// Removes the unused Docker image names and returns what happened to each, or none when the + /// operator declined or there was nothing to remove. + async fn clean_images( + &self, + paths: &RootPathArgs, + format: OutputFormat, + ) -> anyhow::Result> { let cache = dotcore_domain::CacheLayout(&paths.cache_root()?).model_artifacts(); let docker = DockerOciClient::connect() .await @@ -56,30 +69,64 @@ impl GcCommand { .plan() .await .context("Docker image cleanup planning failed")?; - let mut terminal = open_terminal(); - if !approve_removals(terminal.as_mut(), &planned, self.yes)? { - return Ok(()); + let mut terminal = LazyTerminal::new(); + if !approve_removals(&mut terminal, &planned, self.yes, format)? { + return Ok(Vec::new()); } let results = cleanup .apply() .await .context("Docker image cleanup failed")?; - if controlling_terminal_condition() == TerminalCondition::Interactive { - show_results(terminal.as_mut(), &results)?; - } else { - let blocks = results - .iter() - .map(|(removal, outcome)| record_block(removal, outcome)) - .collect::>>()?; - write_records(&blocks.join("\n"))?; + if format == OutputFormat::Human { + show_results(&mut terminal, &results)?; } let failed = results .iter() .filter(|(_, outcome)| matches!(outcome, RemovalOutcome::Failed(_))) .count(); anyhow::ensure!(failed == 0, "{failed} Docker image removals failed"); - Ok(()) + Ok(results + .iter() + .map(|(removal, outcome)| ImageResult::new(removal, outcome)) + .collect()) + } +} + +/// The YAML document of `dotc gc`: what each cleanup step removed. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct GcDocument { + images: Vec, + storage: Vec, +} + +/// What happened to one Docker image name. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct ImageResult { + image_id: String, + reference: String, + reason: &'static str, + result: &'static str, +} + +impl ImageResult { + fn new(removal: &ImageRemoval, outcome: &RemovalOutcome) -> Self { + Self { + image_id: removal.image_id.clone(), + reference: removal.reference.clone(), + reason: match removal.reason { + RemovalReason::UnusedName => "unusedName", + RemovalReason::DigestReference => "digestReference", + RemovalReason::UntaggedBuild => "untaggedBuild", + }, + result: match outcome { + RemovalOutcome::Removed => "removed", + RemovalOutcome::InUse => "inUse", + RemovalOutcome::Failed(_) => "failed", + }, + } } } @@ -88,6 +135,7 @@ fn approve_removals( terminal: &mut dyn Terminal, planned: &[ImageRemoval], yes: bool, + format: OutputFormat, ) -> anyhow::Result { approve( terminal, @@ -98,6 +146,7 @@ fn approve_removals( rows: planned.iter().map(removal_row).collect(), }, yes, + format, ) } @@ -113,16 +162,30 @@ struct Approval<'a> { /// Decides whether the planned removals go ahead: nothing to remove needs no approval, `yes` /// approves in advance, and otherwise the operator confirms the listed removals on the terminal. -/// Without a terminal it refuses, and a declined prompt returns [`PromptError::Cancelled`]. -fn approve(terminal: &mut dyn Terminal, approval: Approval<'_>, yes: bool) -> anyhow::Result { +/// Without a terminal, or asked for YAML, it refuses, and a declined prompt returns +/// [`PromptError::Cancelled`]. +fn approve( + terminal: &mut dyn Terminal, + approval: Approval<'_>, + yes: bool, + format: OutputFormat, +) -> anyhow::Result { let count = approval.rows.len(); if count == 0 { - terminal.message(&Message::Success(approval.nothing.to_owned()))?; + if format == OutputFormat::Human { + present_on(terminal, &[Message::Success(approval.nothing.to_owned())])?; + } return Ok(false); } if yes { return Ok(true); } + if format == OutputFormat::Yaml { + anyhow::bail!( + "{count} {} can be removed; --yaml never asks for confirmation, pass --yes to remove them", + approval.noun + ); + } if terminal.condition() == TerminalCondition::NonInteractive { anyhow::bail!( "{count} {} can be removed; run in a terminal or pass --yes to remove them without confirmation", @@ -130,7 +193,7 @@ fn approve(terminal: &mut dyn Terminal, approval: Approval<'_>, yes: bool) -> an ); } - terminal.message(&Message::Table { + terminal.prompt_context(&Message::Table { header: approval .header .iter() @@ -152,31 +215,40 @@ fn show_results( terminal: &mut dyn Terminal, results: &[(ImageRemoval, RemovalOutcome)], ) -> anyhow::Result<()> { - terminal.message(&Message::Table { - header: ["IMAGE", "NAME", "REASON", "RESULT"] - .map(str::to_owned) - .to_vec(), - rows: results - .iter() - .map(|(removal, outcome)| { - let mut row = removal_row(removal); - row.push(outcome_text(outcome)); - row - }) - .collect(), - })?; + present_on( + terminal, + &[Message::Table { + header: ["IMAGE", "NAME", "REASON", "RESULT"] + .map(str::to_owned) + .to_vec(), + rows: results + .iter() + .map(|(removal, outcome)| { + let mut row = removal_row(removal); + row.push(outcome_text(outcome)); + row + }) + .collect(), + }], + )?; let removed = results .iter() .filter(|(_, outcome)| outcome == &RemovalOutcome::Removed) .count(); - terminal.message(&Message::Success(format!( - "Removed {removed} of {} Docker image names", - results.len() - )))?; - terminal.message(&Message::Info( - "Nix store space is reclaimed separately by Nix garbage collection".to_owned(), - ))?; - terminal.message(&Message::Command("nix-store --gc".to_owned()))?; + present_on( + terminal, + &[Message::Success(format!( + "Removed {removed} of {} Docker image names", + results.len() + ))], + )?; + present_on( + terminal, + &[Message::Info( + "Nix store space is reclaimed separately by Nix garbage collection".to_owned(), + )], + )?; + present_on(terminal, &[Message::Command("nix-store --gc".to_owned())])?; Ok(()) } @@ -188,16 +260,6 @@ fn removal_row(removal: &ImageRemoval) -> Vec { ] } -fn record_block(removal: &ImageRemoval, outcome: &RemovalOutcome) -> anyhow::Result { - Ok(format!( - "Removal\nDOTCORE_GC_IMAGE={}\nDOTCORE_GC_NAME={}\nDOTCORE_GC_REASON={}\nDOTCORE_GC_RESULT={}\n", - record_value(&removal.image_id)?, - record_value(&removal.reference)?, - reason(removal.reason), - record_value(&outcome_text(outcome))?, - )) -} - fn reason(reason: RemovalReason) -> &'static str { match reason { RemovalReason::UnusedName => "unused name", @@ -226,26 +288,18 @@ mod tests { use crate::terminal::{ScriptedAnswer, ScriptedPrompt, ScriptedTerminal}; #[test] - fn records_name_the_removal_and_its_result() { - let removal = n8n_removal(); - - assert_eq!( - record_block(&removal, &RemovalOutcome::Removed).expect("removed record"), - "Removal\nDOTCORE_GC_IMAGE=sha256:0123456789abcdef\nDOTCORE_GC_NAME=dotcore-nix/docker-image-n8n:0123\nDOTCORE_GC_REASON=unused name\nDOTCORE_GC_RESULT=removed\n" - ); - assert!( - record_block(&removal, &RemovalOutcome::Failed("conflict".to_owned())) - .expect("failed record") - .ends_with("DOTCORE_GC_RESULT=failed: conflict\n") - ); - assert_eq!(short_id(&removal.image_id), "0123456789ab"); + fn the_short_image_id_drops_the_algorithm() { + assert_eq!(short_id(&n8n_removal().image_id), "0123456789ab"); } #[test] fn nothing_to_remove_needs_no_approval() { - let mut terminal = ScriptedTerminal::new(TerminalCondition::NonInteractive, []); + let mut terminal = ScriptedTerminal::interactive([]); - assert!(!approve_removals(&mut terminal, &[], false).expect("nothing to approve")); + assert!( + !approve_removals(&mut terminal, &[], false, OutputFormat::Human) + .expect("nothing to approve") + ); assert_eq!(terminal.lines(), ["✔ No Docker image to clean up"]); } @@ -254,14 +308,75 @@ mod tests { let planned = [n8n_removal()]; let mut terminal = ScriptedTerminal::new(TerminalCondition::NonInteractive, []); - let error = approve_removals(&mut terminal, &planned, false).expect_err("needs yes"); + let error = approve_removals(&mut terminal, &planned, false, OutputFormat::Human) + .expect_err("needs yes"); assert_eq!( error.to_string(), "1 Docker image names can be removed; run in a terminal or pass --yes to remove them without confirmation" ); - assert!(approve_removals(&mut terminal, &planned, true).expect("yes approves")); + assert!( + approve_removals(&mut terminal, &planned, true, OutputFormat::Human) + .expect("yes approves") + ); + assert!(terminal.prompts().is_empty()); + } + + #[test] + fn yaml_never_asks_so_removals_need_yes_and_nothing_to_remove_prints_nothing() { + let planned = [n8n_removal()]; + let mut terminal = ScriptedTerminal::interactive([]); + + let error = approve_removals(&mut terminal, &planned, false, OutputFormat::Yaml) + .expect_err("needs yes"); + + assert_eq!( + error.to_string(), + "1 Docker image names can be removed; --yaml never asks for confirmation, pass --yes to remove them" + ); assert!(terminal.prompts().is_empty()); + assert!(terminal.messages().is_empty()); + assert!( + approve_removals(&mut terminal, &planned, true, OutputFormat::Yaml) + .expect("yes approves") + ); + assert!( + !approve_removals(&mut terminal, &[], false, OutputFormat::Yaml) + .expect("nothing to approve") + ); + assert!(terminal.messages().is_empty()); + } + + #[test] + fn the_document_names_each_removal_and_its_result() { + let document = GcDocument { + images: vec![ + ImageResult::new(&n8n_removal(), &RemovalOutcome::Removed), + ImageResult::new(&n8n_removal(), &RemovalOutcome::InUse), + ], + storage: Vec::new(), + }; + + assert_eq!( + serde_json::to_value(&document).expect("document"), + serde_json::json!({ + "images": [ + { + "imageId": "sha256:0123456789abcdef", + "reference": "dotcore-nix/docker-image-n8n:0123", + "reason": "unusedName", + "result": "removed", + }, + { + "imageId": "sha256:0123456789abcdef", + "reference": "dotcore-nix/docker-image-n8n:0123", + "reason": "unusedName", + "result": "inUse", + }, + ], + "storage": [], + }) + ); } #[test] @@ -272,8 +387,12 @@ mod tests { ScriptedAnswer::Confirm(false), ]); - assert!(approve_removals(&mut terminal, &planned, false).expect("confirmed")); - let declined = approve_removals(&mut terminal, &planned, false).expect_err("declined"); + assert!( + approve_removals(&mut terminal, &planned, false, OutputFormat::Human) + .expect("confirmed") + ); + let declined = approve_removals(&mut terminal, &planned, false, OutputFormat::Human) + .expect_err("declined"); assert!(matches!( declined.downcast_ref::(), diff --git a/backend/cli/src/gc/storage.rs b/backend/cli/src/gc/storage.rs index f2f89365..81c1a4e6 100644 --- a/backend/cli/src/gc/storage.rs +++ b/backend/cli/src/gc/storage.rs @@ -12,21 +12,55 @@ use dotcore_runtime::WorkloadStorageKind; use dotcore_runtime_backends::docker::{ DockerMountedFolders, StorageArea, StorageCleanup, StorageRemoval, StorageRemovalOutcome, }; +use serde::Serialize; use super::{Approval, approve}; use crate::{ RootPathArgs, - node::{record_value, write_records}, - terminal::{ - Message, Terminal, TerminalCondition, controlling_terminal_condition, open_terminal, - }, + output::{LazyTerminal, OutputFormat, present_on}, + terminal::{Message, Terminal}, }; const DAY: Duration = Duration::from_secs(24 * 60 * 60); +/// What happened to one shared workload storage folder. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct StorageResult { + kind: &'static str, + area: String, + namespace: String, + key: String, + result: &'static str, +} + +impl StorageResult { + fn new(removal: &StorageRemoval, outcome: &StorageRemovalOutcome) -> Self { + Self { + kind: kind(removal.kind), + area: removal.area.clone(), + namespace: removal.namespace.clone(), + key: removal.key.clone(), + result: match outcome { + StorageRemovalOutcome::Removed => "removed", + StorageRemovalOutcome::InUse => "inUse", + StorageRemovalOutcome::UsedSincePlanning => "usedSincePlanning", + StorageRemovalOutcome::Failed(_) => "failed", + }, + } + } +} + /// Removes the shared workload storage that no workload used for more than `unused_days` days, -/// in every site's caches on this machine, the development data and the site folder's data. -pub(super) async fn clean(paths: &RootPathArgs, unused_days: u32, yes: bool) -> anyhow::Result<()> { +/// in every site's caches on this machine, the development data and the site folder's data, and +/// returns what happened to each folder, or none when the operator declined or there was nothing +/// to remove. +pub(super) async fn clean( + paths: &RootPathArgs, + unused_days: u32, + yes: bool, + format: OutputFormat, +) -> anyhow::Result> { let site_root = paths.site_dir()?; let areas = StorageArea::on_machine(&paths.cache_root()?, Some(&site_root)) .context("Workload storage listing failed")?; @@ -39,27 +73,24 @@ pub(super) async fn clean(paths: &RootPathArgs, unused_days: u32, yes: bool) -> .plan(now) .await .context("Workload storage cleanup planning failed")?; - let mut terminal = open_terminal(); - if !approve_storage(terminal.as_mut(), &planned, now, yes)? { - return Ok(()); + let mut terminal = LazyTerminal::new(); + if !approve_storage(&mut terminal, &planned, now, yes, format)? { + return Ok(Vec::new()); } let results = cleanup.apply(planned, real_time::wall_now()).await; - if controlling_terminal_condition() == TerminalCondition::Interactive { - show_results(terminal.as_mut(), &results, now)?; - } else { - let blocks = results - .iter() - .map(|(removal, outcome)| record_block(removal, outcome)) - .collect::>>()?; - write_records(&blocks.join("\n"))?; + if format == OutputFormat::Human { + show_results(&mut terminal, &results, now)?; } let failed = results .iter() .filter(|(_, outcome)| matches!(outcome, StorageRemovalOutcome::Failed(_))) .count(); anyhow::ensure!(failed == 0, "{failed} workload storage removals failed"); - Ok(()) + Ok(results + .iter() + .map(|(removal, outcome)| StorageResult::new(removal, outcome)) + .collect()) } /// Decides whether the planned storage removals go ahead, as [`approve`] does. @@ -68,6 +99,7 @@ fn approve_storage( planned: &[StorageRemoval], now: SystemTime, yes: bool, + format: OutputFormat, ) -> anyhow::Result { approve( terminal, @@ -81,6 +113,7 @@ fn approve_storage( .collect(), }, yes, + format, ) } @@ -91,29 +124,35 @@ fn show_results( results: &[(StorageRemoval, StorageRemovalOutcome)], now: SystemTime, ) -> anyhow::Result<()> { - terminal.message(&Message::Table { - header: HEADER - .iter() - .chain(&["RESULT"]) - .map(|&title| title.to_owned()) - .collect(), - rows: results - .iter() - .map(|(removal, outcome)| { - let mut row = removal_row(removal, now); - row.push(outcome_text(outcome)); - row - }) - .collect(), - })?; + present_on( + terminal, + &[Message::Table { + header: HEADER + .iter() + .chain(&["RESULT"]) + .map(|&title| title.to_owned()) + .collect(), + rows: results + .iter() + .map(|(removal, outcome)| { + let mut row = removal_row(removal, now); + row.push(outcome_text(outcome)); + row + }) + .collect(), + }], + )?; let removed = results .iter() .filter(|(_, outcome)| outcome == &StorageRemovalOutcome::Removed) .count(); - terminal.message(&Message::Success(format!( - "Removed {removed} of {} unused workload storage folders", - results.len() - )))?; + present_on( + terminal, + &[Message::Success(format!( + "Removed {removed} of {} unused workload storage folders", + results.len() + ))], + )?; Ok(()) } @@ -127,20 +166,6 @@ fn removal_row(removal: &StorageRemoval, now: SystemTime) -> Vec { ] } -fn record_block( - removal: &StorageRemoval, - outcome: &StorageRemovalOutcome, -) -> anyhow::Result { - Ok(format!( - "StorageRemoval\nDOTCORE_GC_STORAGE_KIND={}\nDOTCORE_GC_STORAGE_AREA={}\nDOTCORE_GC_STORAGE_NAMESPACE={}\nDOTCORE_GC_STORAGE_KEY={}\nDOTCORE_GC_STORAGE_RESULT={}\n", - kind(removal.kind), - record_value(&removal.area)?, - record_value(&removal.namespace)?, - record_value(&removal.key)?, - record_value(&outcome_text(outcome))?, - )) -} - fn kind(kind: WorkloadStorageKind) -> &'static str { match kind { WorkloadStorageKind::Cache => "cache", @@ -171,7 +196,9 @@ mod tests { use std::path::PathBuf; use super::*; - use crate::terminal::{ConfirmPrompt, ScriptedAnswer, ScriptedPrompt, ScriptedTerminal}; + use crate::terminal::{ + ConfirmPrompt, ScriptedAnswer, ScriptedPrompt, ScriptedTerminal, TerminalCondition, + }; #[test] fn the_operator_confirms_the_listed_storage() { @@ -179,7 +206,10 @@ mod tests { let planned = [engine_cache(now - DAY * 9)]; let mut terminal = ScriptedTerminal::interactive([ScriptedAnswer::Confirm(true)]); - assert!(approve_storage(&mut terminal, &planned, now, false).expect("confirmed")); + assert!( + approve_storage(&mut terminal, &planned, now, false, OutputFormat::Human) + .expect("confirmed") + ); assert_eq!( terminal.messages()[0], @@ -206,15 +236,22 @@ mod tests { #[test] fn nothing_to_remove_and_no_terminal_behave_as_for_images() { let now = SystemTime::UNIX_EPOCH + DAY * 30; - let mut terminal = ScriptedTerminal::new(TerminalCondition::NonInteractive, []); + let mut shown = ScriptedTerminal::interactive([]); - assert!(!approve_storage(&mut terminal, &[], now, false).expect("nothing to approve")); - assert_eq!( - terminal.lines(), - ["✔ No unused workload storage to clean up"] + assert!( + !approve_storage(&mut shown, &[], now, false, OutputFormat::Human) + .expect("nothing to approve") ); - let error = approve_storage(&mut terminal, &[engine_cache(now)], now, false) - .expect_err("needs yes"); + assert_eq!(shown.lines(), ["✔ No unused workload storage to clean up"]); + let mut terminal = ScriptedTerminal::new(TerminalCondition::NonInteractive, []); + let error = approve_storage( + &mut terminal, + &[engine_cache(now)], + now, + false, + OutputFormat::Human, + ) + .expect_err("needs yes"); assert_eq!( error.to_string(), "1 unused workload storage folders can be removed; run in a terminal or pass --yes to remove them without confirmation" @@ -222,12 +259,22 @@ mod tests { } #[test] - fn records_name_the_storage_and_its_result() { + fn the_document_names_the_storage_and_its_result() { let removal = engine_cache(SystemTime::UNIX_EPOCH); assert_eq!( - record_block(&removal, &StorageRemovalOutcome::InUse).expect("record"), - "StorageRemoval\nDOTCORE_GC_STORAGE_KIND=cache\nDOTCORE_GC_STORAGE_AREA=site-a\nDOTCORE_GC_STORAGE_NAMESPACE=engine-artifact\nDOTCORE_GC_STORAGE_KEY=sha256-0123\nDOTCORE_GC_STORAGE_RESULT=in use\n" + serde_json::to_value(StorageResult::new( + &removal, + &StorageRemovalOutcome::UsedSincePlanning + )) + .expect("document"), + serde_json::json!({ + "kind": "cache", + "area": "site-a", + "namespace": "engine-artifact", + "key": "sha256-0123", + "result": "usedSincePlanning", + }) ); } diff --git a/backend/cli/src/guided/capability.rs b/backend/cli/src/guided/capability.rs index dae3898f..ae8bd6fe 100644 --- a/backend/cli/src/guided/capability.rs +++ b/backend/cli/src/guided/capability.rs @@ -124,7 +124,7 @@ pub(crate) fn collect_inference( .apple .as_ref() .expect("unresolved inference must have an Apple probe"); - terminal.message(&Message::Info(summary( + terminal.prompt_context(&Message::Info(summary( "Accelerator detection", &[("nvidia", nvidia.state()), ("apple", apple.state())], )))?; @@ -160,7 +160,7 @@ pub(crate) fn collect_inference( offers.push(Some((InitialInferenceRuntime::Simulated, None))); } if items.is_empty() { - terminal.message(&Message::Info( + terminal.prompt_context(&Message::Info( "No inference: this node runs no local models.".to_owned(), ))?; return Ok(inference_pick(nvidia, &[])); @@ -180,7 +180,7 @@ pub(crate) fn collect_inference( .iter() .any(|(runtime, _)| *runtime == InitialInferenceRuntime::Simulated); if simulated && picked.len() > 1 { - terminal.message(&Message::Warning( + terminal.prompt_context(&Message::Warning( "Simulated hardware replaces the real GPUs: check one or the other.".to_owned(), ))?; continue; @@ -192,7 +192,7 @@ pub(crate) fn collect_inference( .iter() .any(|(runtime, _)| *runtime == InitialInferenceRuntime::Simulated); if picked.is_empty() { - terminal.message(&Message::Info( + terminal.prompt_context(&Message::Info( "No inference: this node runs no local models.".to_owned(), ))?; } @@ -228,7 +228,7 @@ fn collect_simulated_hardware(terminal: &mut dyn Terminal) -> anyhow::Result>(); match MachineDescription::simulated(&picked, std::env::consts::ARCH) { Ok(_) => return Ok(picked), - Err(error) => terminal.message(&Message::Warning(format!("{error}.")))?, + Err(error) => terminal.prompt_context(&Message::Warning(format!("{error}.")))?, } } } @@ -248,7 +248,7 @@ pub(crate) fn collect_applications( .docker .as_ref() .expect("unresolved applications must have a Docker probe"); - terminal.message(&Message::Info(summary( + terminal.prompt_context(&Message::Info(summary( "Applications detection", &[("docker", docker.state())], )))?; @@ -278,7 +278,7 @@ pub(crate) fn collect_applications( }) .collect::>(); if applications.is_empty() { - terminal.message(&Message::Info( + terminal.prompt_context(&Message::Info( "No applications: this node runs no applications.".to_owned(), ))?; } diff --git a/backend/cli/src/guided/host.rs b/backend/cli/src/guided/host.rs index cb46f1e1..7c78afbb 100644 --- a/backend/cli/src/guided/host.rs +++ b/backend/cli/src/guided/host.rs @@ -24,7 +24,7 @@ pub(super) fn collect_host( let reason = match selected.source() { HostSource::Flag | HostSource::Chosen => return Ok(selected), HostSource::Listener(_) | HostSource::Recorded => { - terminal.message(&Message::Info(format!( + terminal.prompt_context(&Message::Info(format!( "Node host: {}, {}", selected.host(), selected.source() @@ -36,10 +36,10 @@ pub(super) fn collect_host( }; let (prompt, choices) = host_selector(candidates, &selected); - terminal.message(&Message::Hint( + terminal.prompt_context(&Message::Hint( "Other nodes reach this node at this host.".to_owned(), ))?; - terminal.message(&Message::Hint(reason))?; + terminal.prompt_context(&Message::Hint(reason))?; let host = match &choices[terminal.select(&prompt)?] { HostChoice::Listed(host) => host.clone(), HostChoice::Other => collect_other_host(terminal)?, @@ -101,7 +101,7 @@ fn collect_other_host(terminal: &mut dyn Terminal) -> anyhow::Result return Ok(host), Err(error) => { - terminal.message(&Message::Error(format!("Node host {value:?} {error}")))? + terminal.prompt_context(&Message::Error(format!("Node host {value:?} {error}")))? } } } diff --git a/backend/cli/src/guided/mod.rs b/backend/cli/src/guided/mod.rs index d213b893..353a682b 100644 --- a/backend/cli/src/guided/mod.rs +++ b/backend/cli/src/guided/mod.rs @@ -253,7 +253,7 @@ pub async fn collect_guided_initial_site( let plan = plan_from_prepared(defaults.site_dir.clone(), host, prepared); display_summary(terminal, &plan)?; if let Some(warning) = host_warning { - terminal.message(&Message::Warning(warning))?; + terminal.prompt_context(&Message::Warning(warning))?; } if confirm(terminal)? { diff --git a/backend/cli/src/guided/node_name.rs b/backend/cli/src/guided/node_name.rs index c9af7988..d5ef0ab1 100644 --- a/backend/cli/src/guided/node_name.rs +++ b/backend/cli/src/guided/node_name.rs @@ -34,7 +34,7 @@ pub(super) fn collect_node_name( return Ok(None); } if !is_valid_display_name(name) { - terminal.message(&Message::Error( + terminal.prompt_context(&Message::Error( "Node name must contain 1 to 128 non-control characters".to_owned(), ))?; continue; diff --git a/backend/cli/src/guided/summary.rs b/backend/cli/src/guided/summary.rs index 890c4dfd..8c0ff9b0 100644 --- a/backend/cli/src/guided/summary.rs +++ b/backend/cli/src/guided/summary.rs @@ -28,7 +28,7 @@ pub(super) fn display_summary( .first() .context("validated guided site inputs lack a node")?; - terminal.message(&Message::Heading("Initial site plan".to_owned()))?; + terminal.prompt_context(&Message::Heading("Initial site plan".to_owned()))?; let mut rows = vec![ ( "site directory".to_owned(), @@ -53,8 +53,8 @@ pub(super) fn display_summary( }; rows.push(("native workloads".to_owned(), lifetime.to_owned())); } - terminal.message(&Message::KeyValues(rows))?; - terminal.message(&Message::Hint(NODE_HOST_CONSEQUENCE.to_owned()))?; + terminal.prompt_context(&Message::KeyValues(rows))?; + terminal.prompt_context(&Message::Hint(NODE_HOST_CONSEQUENCE.to_owned()))?; Ok(()) } diff --git a/backend/cli/src/guided/tests.rs b/backend/cli/src/guided/tests.rs index 385b1102..0b287f3c 100644 --- a/backend/cli/src/guided/tests.rs +++ b/backend/cli/src/guided/tests.rs @@ -808,6 +808,7 @@ fn prompt_titles(terminal: &ScriptedTerminal) -> Vec<&str> { ScriptedPrompt::Confirm(prompt) => prompt.title(), ScriptedPrompt::Input(prompt) | ScriptedPrompt::Secret(prompt) => prompt.title(), ScriptedPrompt::Countdown(prompt) => prompt.title(), + ScriptedPrompt::Form(prompt) => &prompt.title, }) .collect() } diff --git a/backend/cli/src/hardware/mod.rs b/backend/cli/src/hardware/mod.rs index 165817e8..e985aac4 100644 --- a/backend/cli/src/hardware/mod.rs +++ b/backend/cli/src/hardware/mod.rs @@ -1,8 +1,8 @@ //! `dotc hardware`: describes this machine's hardware and recommends models for it. //! -//! Both commands work without a site or a running server. `show` prints the machine as a -//! description other tools can load, and `recommend` ranks the master catalog's models for this -//! machine or for a description file. Results go to stdout in a stable plain form. +//! Both commands work without a site or a running server. `show` describes the machine, as a +//! description other tools can load when asked for YAML, and `recommend` ranks the master +//! catalog's models for this machine or for a description file. Results go to stdout. mod recommend; mod show; @@ -12,8 +12,9 @@ use clap::{Args, Subcommand}; use dotcore_catalog::{Catalog, OciArtifactPolicy}; use std::path::Path; -use crate::RootPathArgs; +use crate::{RootPathArgs, output::OutputFormat}; use recommend::{RecommendArgs, recommend}; +pub(crate) use show::gib; use show::show; /// Commands that describe the hardware of a machine, with no site involved. @@ -27,21 +28,23 @@ pub struct HardwareCommand { /// Actions supported by the hardware command group. #[derive(Debug, Subcommand)] enum HardwareSubcommand { - /// Print this machine's hardware as a machine description, with the hardware class of each - /// model target. The output has no host name, user name, path or address, so it is safe to - /// paste into a bug report. + /// Show this machine's hardware and the hardware class of each model target + /// + /// With `--yaml`, prints a machine description other commands load. The output has no host + /// name, user name, path or address, so it is safe to paste into a bug report. Show, - /// Rank the master catalog's models for each use case on this machine, or on the machine - /// description in a file. + /// Rank the master catalog's models for each use case on this machine + /// + /// Can rank for the machine description in a file instead. Recommend(RecommendArgs), } impl HardwareCommand { - pub(crate) fn dispatch(self, paths: &RootPathArgs) -> Result<()> { + pub(crate) fn dispatch(self, paths: &RootPathArgs, format: OutputFormat) -> Result<()> { match self.command { - Some(HardwareSubcommand::Show) => show(paths), - Some(HardwareSubcommand::Recommend(arguments)) => recommend(paths, arguments), + Some(HardwareSubcommand::Show) => show(paths, format), + Some(HardwareSubcommand::Recommend(arguments)) => recommend(paths, arguments, format), None => anyhow::bail!("hardware command requires an action"), } } diff --git a/backend/cli/src/hardware/recommend.rs b/backend/cli/src/hardware/recommend.rs index 6a80d014..770be3e1 100644 --- a/backend/cli/src/hardware/recommend.rs +++ b/backend/cli/src/hardware/recommend.rs @@ -5,7 +5,7 @@ //! whether it fits there now, its context per request, the total context it starts with and, when //! that total is overcommitted, what the engine does once its requests fill it. Each use case also //! names the catalog application that serves it, and says when no target runs it or none holds the -//! accelerators it prefers. +//! accelerators it prefers. Asked for YAML, it prints the same facts as one document. use std::path::PathBuf; @@ -16,9 +16,14 @@ use dotcore_catalog::{Catalog, CatalogModelId, context_behavior::FullPool}; use dotcore_domain::timing::Timing; use dotcore_node_hardware::MachineDescription; use dotcore_proto::dotcore::catalog::v1::{Application, UseCase}; +use serde::Serialize; use super::load_catalog; -use crate::{RootPathArgs, terminal::Message}; +use crate::{ + RootPathArgs, + output::{OutputFormat, write_text, write_yaml}, + terminal::Message, +}; /// Arguments of `dotc hardware recommend`. #[derive(Debug, Args)] @@ -54,7 +59,11 @@ impl UseCaseArg { } /// Prints the recommendations for the machine on stdout. -pub(super) fn recommend(paths: &RootPathArgs, arguments: RecommendArgs) -> Result<()> { +pub(super) fn recommend( + paths: &RootPathArgs, + arguments: RecommendArgs, + format: OutputFormat, +) -> Result<()> { let catalog = load_catalog(&paths.master_catalog()?)?; let machine = match &arguments.machine { Some(file) => read_machine(file)?, @@ -71,8 +80,10 @@ pub(super) fn recommend(paths: &RootPathArgs, arguments: RecommendArgs) -> Resul let idle = IdleMachine::new(&machine, Timing::for_process().node_control) .context("cannot work out the execution targets")?; let recommendations = idle.recommend(&catalog, &use_cases); - print!("{}", render(&catalog, &idle, &recommendations)); - Ok(()) + match format { + OutputFormat::Yaml => write_yaml(&document(&catalog, &idle, &recommendations)), + OutputFormat::Human => write_text(&render(&catalog, &idle, &recommendations)), + } } /// Reads a machine description from a YAML file. @@ -125,6 +136,56 @@ fn render( text } +/// The recommendations as one document: each use case with its recommended models, the targets +/// that run them, and the application that serves it. +fn document( + catalog: &Catalog, + machine: &IdleMachine, + recommendations: &[UseCaseRecommendations], +) -> RecommendationsDocument { + RecommendationsDocument { + use_cases: recommendations + .iter() + .map(|list| UseCaseDocument { + use_case: list.use_case, + recommendations: list + .rows + .iter() + .map(|row| RecommendationDocument { + model_id: row.model_id.clone(), + model_name: model_name(catalog, &row.model_id), + profile_id: row.profile_id.clone(), + profile_name: profile_name(catalog, &row.model_id, &row.profile_id), + context_per_request: row.context_tokens_per_request, + targets: row + .targets + .iter() + .map(|target| TargetDocument { + execution_target_id: target.placement.execution_target_id.clone(), + execution_target_name: target_name( + machine, + &target.placement.execution_target_id, + ), + fit: fit_key(target.fit), + starting_total_context: target.starting_total_context_tokens, + }) + .collect(), + }) + .collect(), + application: catalog + .list_application_releases() + .into_iter() + .find(|application| application.use_cases().any(|case| case == list.use_case)) + .map(|application| ApplicationDocument { + note: application_note(machine, &application), + application_id: application.application_id, + display_name: application.display_name, + }), + }) + .collect(), + } +} + /// Builds one use case's table: a row per recommended model and execution target. fn table(catalog: &Catalog, machine: &IdleMachine, list: &UseCaseRecommendations) -> Message { let rows = list @@ -175,8 +236,17 @@ fn table(catalog: &Catalog, machine: &IdleMachine, list: &UseCaseRecommendations /// Names the application that serves a use case, with a note when the machine can't run it or /// holds none of the accelerators it prefers. fn application_line(machine: &IdleMachine, application: &Application) -> Message { + let name = match application_note(machine, application) { + Some(note) => format!("{} ({note})", application.display_name), + None => application.display_name.clone(), + }; + Message::Info(format!("App: {name}")) +} + +/// Says what keeps the machine from running the application well, if anything. +fn application_note(machine: &IdleMachine, application: &Application) -> Option { let options = machine.recommend_application(application); - let note = if options.is_empty() { + if options.is_empty() { Some("no target can run it".to_owned()) } else if !options.iter().any(|option| option.matches_preference) { Some(format!( @@ -185,12 +255,7 @@ fn application_line(machine: &IdleMachine, application: &Application) -> Message )) } else { None - }; - let name = match note { - Some(note) => format!("{} ({note})", application.display_name), - None => application.display_name.clone(), - }; - Message::Info(format!("App: {name}")) + } } fn use_case_label(use_case: UseCase) -> &'static str { @@ -202,6 +267,15 @@ fn use_case_label(use_case: UseCase) -> &'static str { } } +fn fit_key(fit: RecommendationFit) -> &'static str { + match fit { + RecommendationFit::FitsNow => "fitsNow", + RecommendationFit::NeedsMemoryFreed => "needsMemoryFreed", + RecommendationFit::Unknown => "unknown", + RecommendationFit::Unreachable => "unreachable", + } +} + fn fit_label(fit: RecommendationFit) -> &'static str { match fit { RecommendationFit::FitsNow => "fits now", @@ -251,3 +325,57 @@ fn target_name(machine: &IdleMachine, execution_target_id: &str) -> String { |target| target.display_name.clone(), ) } + +/// The YAML document of `dotc hardware recommend`. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct RecommendationsDocument { + use_cases: Vec, +} + +/// The recommendations of one use case, best first. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct UseCaseDocument { + use_case: UseCase, + recommendations: Vec, + + /// The catalog application that serves the use case, when there is one. + #[serde(skip_serializing_if = "Option::is_none")] + application: Option, +} + +/// One recommended model profile and the targets that can run it. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct RecommendationDocument { + model_id: String, + model_name: String, + profile_id: String, + profile_name: String, + context_per_request: u64, + targets: Vec, +} + +/// How a recommended profile fits one execution target. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct TargetDocument { + execution_target_id: String, + execution_target_name: String, + fit: &'static str, + + #[serde(skip_serializing_if = "Option::is_none")] + starting_total_context: Option, +} + +/// The application that serves a use case, with what keeps this machine from running it well. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct ApplicationDocument { + application_id: String, + display_name: String, + + #[serde(skip_serializing_if = "Option::is_none")] + note: Option, +} diff --git a/backend/cli/src/hardware/show.rs b/backend/cli/src/hardware/show.rs index 98dc42fe..a71d06b7 100644 --- a/backend/cli/src/hardware/show.rs +++ b/backend/cli/src/hardware/show.rs @@ -1,8 +1,9 @@ -//! `dotc hardware show`: prints this machine's hardware as a machine description. +//! `dotc hardware show`: prints this machine's hardware. //! -//! The output is a YAML document that loads as a declared machine, preceded by comment lines -//! naming the Dotcore version and the hardware class of each model execution target. It carries -//! nothing that identifies the machine, so it is safe to share in a bug report. +//! A person gets a summary of the machine and the hardware class of each model execution target. +//! Asked for YAML, the output is a document that loads as a declared machine, preceded by comment +//! lines naming the Dotcore version and those classes. Neither carries anything that identifies +//! the machine, so both are safe to share in a bug report. use std::fmt::Write as _; @@ -11,13 +12,23 @@ use dotcore::model::IdleMachine; use dotcore_catalog::Catalog; use dotcore_domain::timing::Timing; use dotcore_node_hardware::MachineDescription; -use dotcore_proto::dotcore::site::v1::execution_target::RuntimeBinding; +use dotcore_proto::dotcore::{ + node::v1::gpu_description::Memory, site::v1::execution_target::RuntimeBinding, +}; use super::load_catalog; -use crate::{RootPathArgs, config::environment_value}; +use crate::{ + RootPathArgs, + config::environment_value, + output::{OutputFormat, write_plain, write_text}, + terminal::Message, +}; -/// Prints the description of this machine on stdout. -pub(super) fn show(paths: &RootPathArgs) -> Result<()> { +const GIB: f64 = 1024.0 * 1024.0 * 1024.0; + +/// Prints the description of this machine on stdout: a summary for a person, or the description +/// as YAML. +pub(super) fn show(paths: &RootPathArgs, format: OutputFormat) -> Result<()> { let machine = MachineDescription::from_local_host() .context("cannot describe the hardware of this machine")?; let catalog = paths @@ -25,15 +36,82 @@ pub(super) fn show(paths: &RootPathArgs) -> Result<()> { .map(|dir| load_catalog(&dir)) .transpose()?; let revision = packaged_revision()?; - print!( - "{}", - render(&machine, catalog.as_ref(), revision.as_deref())? - ); - Ok(()) + match format { + OutputFormat::Yaml => write_text(&render(&machine, catalog.as_ref(), revision.as_deref())?), + OutputFormat::Human => { + let classes = hardware_classes(&machine, catalog.as_ref())?; + write_plain(&summary(&machine, classes.as_deref(), revision.as_deref())) + } + } +} + +/// Lays the machine out for a person: its facts, its GPUs, and the hardware class of each model +/// target, or a line saying the classes are unknown. +fn summary( + machine: &MachineDescription, + classes: Option<&[(String, String)]>, + revision: Option<&str>, +) -> Vec { + let stored = machine.to_stored(); + let mut dotcore = env!("CARGO_PKG_VERSION").to_owned(); + if let Some(revision) = revision { + dotcore.push_str(&format!(" (revision {revision})")); + } + let mut messages = vec![ + Message::Heading("Hardware".to_owned()), + Message::KeyValues(vec![ + ("dotcore".to_owned(), dotcore), + ("platform".to_owned(), machine.platform().to_string()), + ("cpus".to_owned(), stored.cpu_count.to_string()), + ( + "host memory".to_owned(), + format!( + "{} ({} in use when idle)", + gib(stored.host_memory_total_bytes), + gib(stored.host_memory_idle_used_bytes) + ), + ), + ]), + ]; + if !stored.gpus.is_empty() { + messages.push(Message::Heading("GPUs".to_owned())); + messages.push(Message::Table { + header: ["MODEL", "VENDOR", "DRIVER", "MEMORY"] + .map(str::to_owned) + .to_vec(), + rows: stored + .gpus + .iter() + .map(|gpu| { + vec![ + gpu.model.clone(), + format!("{:?}", gpu.vendor()).to_lowercase(), + gpu.driver_version.clone(), + match &gpu.memory { + Some(Memory::Dedicated(memory)) => gib(memory.total_bytes), + Some(Memory::Unified(_)) => "unified".to_owned(), + None => String::new(), + }, + ] + }) + .collect(), + }); + } + match classes { + Some([]) => {} + Some(classes) => { + messages.push(Message::Heading("Hardware classes".to_owned())); + messages.push(Message::KeyValues(classes.to_vec())); + } + None => messages.push(Message::Info( + "Hardware classes are unknown: no master catalog found".to_owned(), + )), + } + messages } -/// Renders the report: comment lines, then the description. Without a catalog the classes cannot -/// be named, which the report says. +/// Renders the YAML report: comment lines, then the description. Without a catalog the classes +/// cannot be named, which the report says. fn render( machine: &MachineDescription, catalog: Option<&Catalog>, @@ -45,23 +123,10 @@ fn render( } report.push('\n'); - match catalog { - Some(catalog) => { - let idle = IdleMachine::new(machine, Timing::for_process().node_control) - .context("cannot work out the execution targets")?; - for (target, class) in idle.hardware_classes(catalog) { - if !matches!( - target.runtime_binding, - Some(RuntimeBinding::ModelRuntime(_)) - ) { - continue; - } - let class = class.map_or("none".to_owned(), |class| class.hardware_class_id); - writeln!( - report, - "# Hardware class of {}: {class}", - target.display_name - )?; + match hardware_classes(machine, catalog)? { + Some(classes) => { + for (target, class) in classes { + writeln!(report, "# Hardware class of {target}: {class}")?; } } None => report.push_str("# Hardware classes: unknown, no master catalog found\n"), @@ -71,6 +136,41 @@ fn render( Ok(report) } +/// The hardware class of each model execution target, named after the target, or `None` without +/// a catalog to name them from. +fn hardware_classes( + machine: &MachineDescription, + catalog: Option<&Catalog>, +) -> Result>> { + let Some(catalog) = catalog else { + return Ok(None); + }; + let idle = IdleMachine::new(machine, Timing::for_process().node_control) + .context("cannot work out the execution targets")?; + Ok(Some( + idle.hardware_classes(catalog) + .into_iter() + .filter(|(target, _)| { + matches!( + target.runtime_binding, + Some(RuntimeBinding::ModelRuntime(_)) + ) + }) + .map(|(target, class)| { + ( + target.display_name.clone(), + class.map_or("none".to_owned(), |class| class.hardware_class_id), + ) + }) + .collect(), + )) +} + +/// Formats a byte count in GiB with one decimal. +pub(crate) fn gib(bytes: u64) -> String { + format!("{:.1} GiB", bytes as f64 / GIB) +} + /// Returns the revision of the source a packaged Dotcore was built from, when it says so. fn packaged_revision() -> Result> { Ok( @@ -86,8 +186,8 @@ mod tests { use dotcore_node_hardware::MachineDescription; - use super::render; - use crate::hardware::load_catalog; + use super::{hardware_classes, render, summary}; + use crate::{hardware::load_catalog, output::plain_text}; const MACHINE: &str = "platform: linux/amd64 cpuCount: 8 @@ -133,6 +233,40 @@ gpus: ); } + #[test] + fn summary_lists_the_machine_its_gpus_and_the_hardware_class_of_each_model_target() { + let catalog = load_catalog( + &Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/recommendation-catalog"), + ) + .expect("fixture catalog"); + let machine = MachineDescription::from_yaml("fixture", MACHINE).expect("machine"); + let classes = hardware_classes(&machine, Some(&catalog)).expect("classes"); + + assert_eq!( + plain_text(&summary( + &machine, + classes.as_deref(), + Some("0123456789abcdef") + )), + format!( + "Hardware\n dotcore {} (revision 0123456789abcdef)\n platform linux/amd64\n cpus 8\n host memory 32.0 GiB (4.0 GiB in use when idle)\n\nGPUs\n MODEL VENDOR DRIVER MEMORY\n Fixture GPU X nvidia 580.173.02 32.0 GiB\n\nHardware classes\n Fixture GPU X nvidia-x\n", + env!("CARGO_PKG_VERSION") + ) + ); + } + + #[test] + fn summary_without_a_catalog_says_the_classes_are_unknown() { + let machine = MachineDescription::from_yaml("fixture", MACHINE).expect("machine"); + + let text = plain_text(&summary(&machine, None, None)); + + assert!( + text.ends_with("32.0 GiB\nHardware classes are unknown: no master catalog found\n"), + "{text}" + ); + } + #[test] fn whole_report_loads_back_as_the_declared_machine_it_describes() { let catalog = load_catalog( diff --git a/backend/cli/src/hint.rs b/backend/cli/src/hint.rs index 63243b78..cb4e21f5 100644 --- a/backend/cli/src/hint.rs +++ b/backend/cli/src/hint.rs @@ -19,7 +19,10 @@ use dotcore_site::{ }; use tonic::Code; -use crate::management::{DeploymentGroup, ManagementError, ReferenceError}; +use crate::{ + management::{DeploymentGroup, ManagementError}, + reference::{ReferenceError, ReferenceKind}, +}; /// Renders one error's own message followed by its command hint, if it has one. pub(crate) fn describe(error: &(dyn Error + 'static)) -> String { @@ -134,14 +137,25 @@ fn deployment_hint(error: &(dyn Error + 'static)) -> Option { }; } if let Some(error) = error.downcast_ref::() { - return Some(match error { - ReferenceError::Unknown { group, .. } => see_list(*group), - ReferenceError::Ambiguous { .. } => "; pass one of the ids instead".to_owned(), - }); + return match error { + ReferenceError::Unknown { + kind: ReferenceKind::Deployment(group), + .. + } => Some(see_list(*group)), + ReferenceError::Unknown { .. } => None, + ReferenceError::Ambiguous { kind, .. } => { + Some(format!("; pass one of the {} instead", identifiers(*kind))) + } + }; } None } +/// The plural word for what tells the objects of a kind apart, for example `ids`. +fn identifiers(kind: ReferenceKind) -> &'static str { + if kind.has_ids() { "ids" } else { "names" } +} + /// Names the options that fit the parameter set an unsolvable sizing fit says would solve. fn fit_hint(error: &(dyn Error + 'static)) -> Option { match error.downcast_ref::()? { diff --git a/backend/cli/src/lib.rs b/backend/cli/src/lib.rs index 839d9383..cf2eb7cc 100644 --- a/backend/cli/src/lib.rs +++ b/backend/cli/src/lib.rs @@ -21,6 +21,7 @@ use tokio::runtime::{Builder, Runtime}; mod application; mod code; mod config; +mod deploy; mod failure; mod gc; pub mod guided; @@ -30,11 +31,14 @@ mod hosts; mod management; mod model; mod node; +mod output; mod parameters; mod paths; +mod reference; mod runtime_confirmation; mod server; mod site; +mod skill; mod telemetry; pub mod terminal; #[cfg(test)] @@ -49,58 +53,72 @@ pub use paths::RootPathArgs; name = "dotc", version, arg_required_else_help = true, - subcommand_required = true + override_usage = "dotc [OPTIONS] \n dotc --skill", + after_help = "Coding agents: run `dotc --skill` for a guide to every command and its conventions." )] pub struct Cli { /// Show the complete cause chain of a failure on a terminal. #[arg(long, global = true)] pub verbose: bool, + /// Print the result as YAML on stdout, for scripts and agents; the command never asks a + /// question. + #[arg(long, global = true)] + pub yaml: bool, + + /// Print an agent skill describing this CLI and its commands, as Markdown on stdout. + #[arg(long)] + pub skill: bool, + #[command(flatten)] pub paths: RootPathArgs, + /// The command to run; absent only for `--skill`, which stands alone. #[command(subcommand)] - pub command: Command, + pub command: Option, + + /// The command group whose agent guide was asked for with its own `--skill`. + #[arg(skip)] + skill_group: Option<&'static skill::GroupGuide>, } /// Product CLI command groups. #[derive(Debug, Subcommand)] pub enum Command { - /// Inspect effective Dotcore process configuration. + /// Inspect the effective Dotcore process configuration Config(config::ConfigCommand), - /// Manage the bare local server process that `dotcore` supervises. + /// Manage the bare local server process that `dotcore` supervises Server(ServerCommand), - /// Create, reset, validate, and delete site inputs offline. + /// Create, reset, validate and delete site inputs offline + #[command(alias = "sites")] Site(site::SiteCommand), - /// Manage site nodes: `add`, `remove`, and `list` on the manager, `join` and `leave` on the - /// node's machine. + /// Manage the nodes of a site and this machine's membership in one + #[command(alias = "nodes")] Node(node::NodeCommand), - /// Manage the model deployments of the running site: `list`, `show`, `pause`, `resume`, - /// `teardown` and `logs`. + /// Inspect and control the model deployments of the running site #[command(alias = "models")] Model(model::ModelCommand), - /// Manage the application deployments of the running site: `list`, `show`, `pause`, `resume`, - /// `teardown` and `logs`. + /// Inspect and control the application deployments of the running site #[command(visible_alias = "app", alias = "applications")] Application(application::ApplicationCommand), - /// Start a coding agent on a site's inference API, with an inference route as its model. + /// Start a coding agent on a site's inference API Code(code::CodeArgs), - /// Run one transient development workload. + /// Run one transient development workload Dev(workload::DevCommand), - /// Remove Docker image names on this machine that no Docker-delivered Nix artifact uses, - /// after listing them and asking for confirmation. + /// Remove unused Docker image names from this machine after confirmation + /// + /// Lists the names no Docker-delivered Nix artifact uses, then asks before removing them. Gc(gc::GcCommand), - /// Describe this machine's hardware and recommend models for it, without a site: `show` and - /// `recommend`. + /// Describe this machine's hardware and recommend models for it Hardware(hardware::HardwareCommand), } @@ -115,14 +133,16 @@ pub struct ServerCommand { /// Actions supported by the local server command group. #[derive(Debug, Subcommand)] enum ServerSubcommand { - /// Run the bare backend server process for a site folder; settings come from the environment. - /// `dotcore` supervises this process and also serves the console and public listeners. + /// Run the bare backend server process for a site folder + /// + /// Settings come from the environment. `dotcore` supervises this process and also serves the + /// console and public listeners. Start, } -/// Initializes the process-wide tracing subscriber. The interactive node membership, model and application commands -/// default to warnings so their prompts and result records are not interleaved with routine -/// events; `RUST_LOG` overrides this. +/// Initializes the process-wide tracing subscriber. The interactive node membership, model and +/// application commands default to warnings so their prompts and output are not interleaved with +/// routine events; `RUST_LOG` overrides this. pub fn initialize_tracing() { let words = command_words(std::env::args_os()); dotcore::logging::initialize_with_default_filter(if quiet_by_default(&words) { @@ -143,17 +163,24 @@ pub fn build_runtime() -> Result { /// Dispatches a parsed command to its owning capability. pub async fn dispatch(cli: Cli) -> Result<()> { let paths = &cli.paths; - match cli.command { - Command::Config(command) => command.dispatch(paths), + let format = cli.output_format(); + if let Some(guide) = cli.skill_group { + return skill::print_group(&Cli::parser(), guide); + } + let Some(command) = cli.command else { + return skill::print(&Cli::parser()); + }; + match command { + Command::Config(command) => command.dispatch(paths, format), Command::Server(command) => command.dispatch(paths).await, - Command::Site(command) => command.dispatch(paths).await, - Command::Node(command) => command.dispatch(paths).await, - Command::Model(command) => command.dispatch().await, - Command::Application(command) => command.dispatch().await, + Command::Site(command) => command.dispatch(paths, format).await, + Command::Node(command) => command.dispatch(paths, format).await, + Command::Model(command) => command.dispatch(format).await, + Command::Application(command) => command.dispatch(format).await, Command::Code(command) => command.dispatch(paths).await, Command::Dev(command) => command.dispatch(paths).await, - Command::Gc(command) => command.dispatch(paths).await, - Command::Hardware(command) => command.dispatch(paths), + Command::Gc(command) => command.dispatch(paths, format).await, + Command::Hardware(command) => command.dispatch(paths, format), } } @@ -198,6 +225,7 @@ fn command_words(arguments: impl IntoIterator) -> Vec if paths::VALUE_OPTIONS.contains(&argument.as_ref()) { arguments.next(); } else if argument == "--verbose" + || argument == "--yaml" || paths::VALUE_OPTIONS.iter().any(|option| { argument .strip_prefix(option) @@ -215,6 +243,29 @@ fn command_words(arguments: impl IntoIterator) -> Vec words } +/// Reports whether anything besides `--skill` was given on the command line. The environment +/// still supplies the root path options. +fn skill_has_company(matches: &clap::ArgMatches) -> bool { + matches.subcommand_name().is_some() + || matches.ids().any(|id| { + id.as_str() != "skill" + && matches.value_source(id.as_str()) == Some(clap::parser::ValueSource::CommandLine) + }) +} + +/// Reports whether anything besides a group's `--skill` was given on the command line: a root +/// option, another option of the group or one of its commands. +fn group_skill_has_company(root: &clap::ArgMatches, group: &clap::ArgMatches) -> bool { + let on_command_line = |matches: &clap::ArgMatches, id: &str| { + matches.value_source(id) == Some(clap::parser::ValueSource::CommandLine) + }; + group.subcommand_name().is_some() + || root.ids().any(|id| on_command_line(root, id.as_str())) + || group + .ids() + .any(|id| id.as_str() != "skill" && on_command_line(group, id.as_str())) +} + /// Returns the arguments without the root path options and their values. fn without_root_paths(arguments: &[std::ffi::OsString]) -> Vec { let mut kept = Vec::new(); @@ -233,8 +284,8 @@ fn without_root_paths(arguments: &[std::ffi::OsString]) -> Vec bool { matches!( ( @@ -258,6 +309,24 @@ fn workload_arguments(words: &[String]) -> bool { && words.get(1).is_some_and(|word| word == "workload") } +impl Command { + /// Reports whether the command can print its result as YAML. The server, the coding agent and + /// the development workloads have no result to print: the server speaks its startup protocol, + /// the agent takes over the terminal and workloads speak their own JSON protocol. + fn prints_yaml(&self) -> bool { + match self { + Self::Config(_) + | Self::Site(_) + | Self::Node(_) + | Self::Model(_) + | Self::Application(_) + | Self::Gc(_) + | Self::Hardware(_) => true, + Self::Server(_) | Self::Code(_) | Self::Dev(_) => false, + } + } +} + impl ServerCommand { async fn dispatch(self, paths: &RootPathArgs) -> Result<()> { let Some(ServerSubcommand::Start) = self.command else { @@ -279,18 +348,67 @@ impl Cli { { let arguments = arguments.into_iter().map(Into::into).collect::>(); Self::reject_missing_action(&arguments)?; - let matches = Self::command().try_get_matches_from(arguments)?; + let matches = Self::parser().try_get_matches_from(arguments)?; let mut cli = ::from_arg_matches(&matches)?; cli.paths.site_dir_on_command_line = matches.value_source("site_dir") == Some(clap::parser::ValueSource::CommandLine); cli.paths.cache_dir_on_command_line = matches.value_source("cache_dir") == Some(clap::parser::ValueSource::CommandLine); + if cli.skill && skill_has_company(&matches) { + return Err(Self::command().error( + clap::error::ErrorKind::ArgumentConflict, + "--skill cannot be combined with other arguments", + )); + } + if let Some((name, group)) = matches.subcommand() + && group.try_get_one::("skill").ok().flatten() == Some(&true) + { + if group_skill_has_company(&matches, group) { + return Err(Self::command().error( + clap::error::ErrorKind::ArgumentConflict, + "--skill cannot be combined with other arguments", + )); + } + cli.skill_group = skill::group_guide(name); + } if let Some(message) = cli.argument_contract_error() { return Err(Self::command().error(clap::error::ErrorKind::ArgumentConflict, message)); } Ok(cli) } + /// The clap command, with `--yaml` hidden from the help of the groups that refuse it and + /// `--skill` on the groups that have an agent guide. Each group that refuses `--yaml` + /// redeclares the global flag hidden, so it replaces the visible one in it and its + /// subcommands. A group's `--skill` is not global: its commands keep `--help` only. + fn parser() -> clap::Command { + let hidden_yaml = || { + clap::Arg::new("yaml") + .long("yaml") + .action(clap::ArgAction::SetTrue) + .global(true) + .hide(true) + }; + + let mut command = Self::command(); + for group in ["server", "code", "dev"] { + command = command.mut_subcommand(group, |group| group.arg(hidden_yaml())); + } + for guide in skill::GROUP_GUIDES { + command = command.mut_subcommand(guide.group, |group| { + group.arg( + clap::Arg::new("skill") + .long("skill") + .action(clap::ArgAction::SetTrue) + .help( + "Print the agent guide for this command group, as Markdown on stdout", + ), + ) + }); + } + command + } + /// Parses process arguments and exits using clap's standard error contract. pub fn parse() -> Self { match Self::try_parse_from(std::env::args_os()) { @@ -332,7 +450,7 @@ impl Cli { /// otherwise run the bare group instead. fn reject_missing_action(arguments: &[std::ffi::OsString]) -> Result<(), clap::Error> { // The environment is replaced by its help annotation, so the help reads the same. - let without_environment = Self::command().mut_args(|argument| { + let without_environment = Self::parser().mut_args(|argument| { let Some(variable) = argument .get_env() .map(|name| name.to_string_lossy().into_owned()) @@ -356,9 +474,24 @@ impl Cli { } } + /// How the command presents its result. + fn output_format(&self) -> output::OutputFormat { + if self.yaml { + output::OutputFormat::Yaml + } else { + output::OutputFormat::Human + } + } + fn argument_contract_error(&self) -> Option<&'static str> { - match &self.command { - Command::Site(command) => command.argument_contract_error(), + let Some(command) = self.command.as_ref() else { + return (!self.skill).then_some("a command is required; see --help"); + }; + if self.yaml && !command.prints_yaml() { + return Some("--yaml is not available for this command"); + } + match command { + Command::Site(command) => command.argument_contract_error(self.yaml), Command::Node(command) => command.argument_contract_error(), Command::Model(command) => command.argument_contract_error(), Command::Application(command) => command.argument_contract_error(), @@ -376,12 +509,14 @@ impl Cli { mod tests { use clap::error::ErrorKind; + use clap::CommandFactory; + use super::Cli; #[test] fn server_start_is_the_canonical_server_command() { let command = Cli::try_parse_from(["dotc", "server", "start"]).expect("server start"); - assert!(matches!(command.command, super::Command::Server(_))); + assert!(matches!(command.command, Some(super::Command::Server(_)))); } #[test] @@ -396,7 +531,7 @@ mod tests { Some(std::path::PathBuf::from("/srv/node")), "{arguments:?}" ); - let super::Command::Server(server) = command.command else { + let Some(super::Command::Server(server)) = command.command else { panic!("server command"); }; assert!(matches!( @@ -441,6 +576,10 @@ mod tests { words(&["dotc", "node", "--site-dir", "/a", "list"]), ["node", "list"] ); + assert_eq!( + words(&["dotc", "--yaml", "model", "--verbose", "list"]), + ["model", "list"] + ); assert_eq!(words(&["dotc"]), Vec::::new()); } @@ -503,7 +642,7 @@ mod tests { "simulated", ]) .expect("site init"); - assert!(matches!(command.command, super::Command::Site(_))); + assert!(matches!(command.command, Some(super::Command::Site(_)))); } #[test] @@ -516,12 +655,32 @@ mod tests { ] { let command = Cli::try_parse_from(arguments).expect("synonym parses"); match (command.command, is_model) { - (super::Command::Model(_), true) | (super::Command::Application(_), false) => {} + (Some(super::Command::Model(_)), true) + | (Some(super::Command::Application(_)), false) => {} (other, _) => panic!("{arguments:?} parsed as {other:?}"), } } } + #[test] + fn yaml_cannot_start_the_guided_site_flow() { + for (arguments, message) in [ + ( + &["dotc", "--yaml", "site", "init", "--interactive"][..], + "--interactive cannot be combined with --yaml, which never asks", + ), + ( + &["dotc", "--yaml", "site", "reset"][..], + "missing workload choices; --yaml never asks, so pass --inference and --applications", + ), + ] { + let error = Cli::try_parse_from(arguments).expect_err("guided flow under --yaml"); + + assert_eq!(error.kind(), ErrorKind::ArgumentConflict, "{arguments:?}"); + assert!(error.to_string().contains(message), "{error}"); + } + } + #[test] fn plain_cli_shows_help_as_invalid_usage() { assert_help_error(["dotc"]); @@ -544,6 +703,78 @@ mod tests { assert_eq!(error.exit_code(), 2); } + #[test] + fn every_leaf_command_has_a_one_line_about_in_one_style() { + let mut leaves = Vec::new(); + collect_leaves(&Cli::command(), "dotc", &mut leaves); + + assert_eq!(leaves.join("\n"), EXPECTED_LEAF_ABOUTS.join("\n")); + for leaf in &leaves { + let about = leaf.split_once(": ").expect("path and about").1; + assert!(!about.contains('\n'), "{leaf}"); + assert!(!about.ends_with('.'), "{leaf}"); + } + } + + /// Lists `path: about` for every command without subcommands. + fn collect_leaves(command: &clap::Command, path: &str, leaves: &mut Vec) { + let mut subcommands = command + .get_subcommands() + .filter(|subcommand| subcommand.get_name() != "help") + .peekable(); + if subcommands.peek().is_none() { + let about = command + .get_about() + .map(ToString::to_string) + .unwrap_or_default(); + leaves.push(format!("{path}: {about}")); + return; + } + for subcommand in subcommands { + let path = format!("{path} {}", subcommand.get_name()); + collect_leaves(subcommand, &path, leaves); + } + } + + const EXPECTED_LEAF_ABOUTS: &[&str] = &[ + "dotc config show: Show the effective process paths and this site folder's role", + "dotc server start: Run the bare backend server process for a site folder", + "dotc site init: Create a site with its signing key and this machine's node identity", + "dotc site reset: Start a fresh site, replacing the current one after confirmation", + "dotc site delete: Delete a stopped site, its runtime resources and its caches", + "dotc site validate: Validate the site's input bundle without starting services", + "dotc node add: Allow one new machine to join the site", + "dotc node join: Join this machine to a site with the token `dotc node add` printed", + "dotc node remove: Remove a worker node from the site", + "dotc node leave: Leave the site: stop this node's workloads and delete its node folder", + "dotc node list: List the site's nodes with their addresses and deployments", + "dotc model list: List the model deployments with their state and node", + "dotc model show: Show one model deployment by name or ID", + "dotc model catalog: List the catalog models you can deploy, with whether each profile fits each target", + "dotc model deploy: Deploy a catalog model step by step on a terminal, or from its starting values and `--set`", + "dotc model pause: Pause a model deployment, without waiting for it to pause", + "dotc model resume: Resume a paused model deployment, without waiting for it to resume", + "dotc model teardown: Remove a model deployment and its workload after confirmation", + "dotc model logs: Print the recent log lines of a model deployment", + "dotc application list: List the application deployments with their state and node", + "dotc application show: Show one application deployment by name or ID", + "dotc application pause: Pause an application deployment, without waiting for it to pause", + "dotc application resume: Resume a paused application deployment, without waiting for it to resume", + "dotc application teardown: Remove an application deployment and its workloads after confirmation", + "dotc application logs: Print the recent log lines of an application deployment", + "dotc code: Start a coding agent on a site's inference API", + "dotc dev workload launch: Resolve and launch a workload", + "dotc dev workload inspect: Inspect an ownership handle and its runtime namespace", + "dotc dev workload logs: Read workload diagnostics", + "dotc dev workload vram: Observe the exact-process NVIDIA VRAM of a workload", + "dotc dev workload teardown: Stop and remove the owned workload", + "dotc dev telemetry fit: Fit a model binding's sizing constants from recorded workload resources", + "dotc dev telemetry check: Check a model binding's sizing constants against recorded workload resources", + "dotc gc: Remove unused Docker image names from this machine after confirmation", + "dotc hardware show: Show this machine's hardware and the hardware class of each model target", + "dotc hardware recommend: Rank the master catalog's models for each use case on this machine", + ]; + #[test] fn help_and_version_succeed() { for arguments in [["dotc", "--help"], ["dotc", "--version"]] { @@ -559,6 +790,25 @@ mod tests { assert!(error.to_string().contains(env!("CARGO_PKG_VERSION"))); } + #[test] + fn help_offers_yaml_only_where_the_command_takes_it() { + let help = |arguments: &[&str]| { + let mut all = vec!["dotc"]; + all.extend(arguments); + all.push("--help"); + Cli::try_parse_from(all).expect_err("help").to_string() + }; + + for arguments in [ + &["dev", "workload", "launch"][..], + &["server", "start"], + &["code"], + ] { + assert!(!help(arguments).contains("--yaml"), "{arguments:?}"); + } + assert!(help(&["model", "list"]).contains("--yaml")); + } + #[test] fn help_output_names_the_nested_server_start_command() { let error = Cli::try_parse_from(["dotc", "--help"]).expect_err("help"); diff --git a/backend/cli/src/management/deployment.rs b/backend/cli/src/management/deployment.rs index 521bf119..c5d5fc47 100644 --- a/backend/cli/src/management/deployment.rs +++ b/backend/cli/src/management/deployment.rs @@ -4,32 +4,39 @@ //! //! The manager decides whether a change is allowed and carries it out later, so a request returns //! once it is accepted and never waits for the workloads. A teardown asks on the terminal first -//! and cancels by default; without a terminal it needs explicit consent. +//! and cancels by default; without a terminal, or asked for YAML, it needs explicit consent. -use tonic::Status; +use dotcore_proto::dotcore::deployment::v1::ExactPlacement; +use serde::Serialize; +use tonic::{Code, Status}; use super::{ - Addressable, DeploymentGroup, ManagementError, Manager, ManagerArgs, call_failed, resolve, + DeploymentDocument, DeploymentGroup, ManagementError, Manager, ManagerArgs, call_failed, single_line, }; use crate::{ - node::write_records, - terminal::{ - ConfirmPrompt, Message, NextStep, PromptError, TerminalCondition, - controlling_terminal_condition, open_terminal, - }, + output::{OutputFormat, present, require_consent, write_yaml}, + reference::{Referable, ReferenceKind, resolve}, + terminal::{ConfirmPrompt, Message, PromptError, open_terminal}, }; /// A kind of deployment the management commands handle alike, implemented by the model and the /// application deployment messages. The steps are generic over it rather than taking a trait /// object because each kind's calls return its own message type. -pub(crate) trait ManagedDeployment: Addressable + Clone { +pub(crate) trait ManagedDeployment: Referable + Clone + Serialize { /// The command group the kind belongs to. const GROUP: DeploymentGroup; /// Reads every deployment of this kind the manager knows. async fn list(manager: &Manager) -> Result, Status>; + /// Reads the deployment with this exact id, or `None` when the manager has no single read for + /// the kind. A manager failing with `NotFound` or `InvalidArgument` means the text is not the + /// id of a deployment. + async fn get(_manager: &Manager, _id: &str) -> Result, Status> { + Ok(None) + } + /// Asks the manager for a lifecycle change of the deployment with this id and returns the /// deployment as the manager now holds it. async fn request( @@ -38,18 +45,23 @@ pub(crate) trait ManagedDeployment: Addressable + Clone { lifecycle: Lifecycle, ) -> Result, Status>; + /// Where the deployment runs; absent for one without a placement, such as an upstream model + /// deployment. + fn placement(&self) -> Option<&ExactPlacement>; + /// Whether the deployment's desired state is the one the lifecycle change asks for. fn accepts(&self, lifecycle: Lifecycle) -> bool; - /// The console's word for the deployment's effective state, for example `Pausing`. - fn state_label(&self) -> &'static str; - /// The word for the desired state the manager drives the deployment toward. fn desired_state_label(&self) -> &'static str; /// What tearing the deployment down removes and keeps, asked after its name in the /// confirmation. fn teardown_consequence(&self) -> String; + + /// Replaces the secret values the deployment carries, which a printed document must not + /// reveal. + fn mask_secrets(&mut self); } /// The lifecycle change an operator asks for. @@ -92,12 +104,25 @@ pub(crate) async fn list_deployments( } /// Finds the one deployment an operator reference names, failing when it names none or several. +/// An exact id is the resolver's first step, so a single read of it decides without the list; any +/// other reference resolves against the list. pub(crate) async fn find_deployment( manager: &Manager, reference: &str, ) -> anyhow::Result { + match T::get(manager, reference).await { + Ok(Some(deployment)) => return Ok(deployment), + Ok(None) => {} + Err(status) if matches!(status.code(), Code::NotFound | Code::InvalidArgument) => {} + Err(status) => { + return Err( + call_failed(T::GROUP, format!("read the {}", T::GROUP.noun()))(status).into(), + ); + } + } + let deployments = list_deployments::(manager).await?; - Ok(resolve(T::GROUP, reference, &deployments)?.clone()) + Ok(resolve(ReferenceKind::Deployment(T::GROUP), reference, &deployments)?.clone()) } /// Pauses or resumes the referenced deployment and reports the accepted state. @@ -105,21 +130,23 @@ pub(crate) async fn change_lifecycle( manager: &ManagerArgs, reference: &str, lifecycle: Lifecycle, + format: OutputFormat, ) -> anyhow::Result<()> { let manager = manager.connect().await?; let deployment = find_deployment::(&manager, reference).await?; let accepted = request(&manager, &deployment, lifecycle).await?; - report(lifecycle, &accepted) + report(&manager, lifecycle, accepted, format).await } /// Tears down the referenced deployment after the operator confirms, or right away with `yes`, -/// and reports the accepted state. +/// and reports the accepted state. Asked for YAML, it never asks, so it needs `yes`. pub(crate) async fn teardown( manager: &ManagerArgs, reference: &str, yes: bool, + format: OutputFormat, ) -> anyhow::Result<()> { - require_teardown_approval(T::GROUP, yes)?; + require_teardown_approval(T::GROUP, yes, format)?; let manager = manager.connect().await?; let deployment = find_deployment::(&manager, reference).await?; @@ -132,7 +159,7 @@ pub(crate) async fn teardown( } let accepted = request(&manager, &deployment, Lifecycle::Teardown).await?; - report(Lifecycle::Teardown, &accepted) + report(&manager, Lifecycle::Teardown, accepted, format).await } /// Sends the request for the deployment and returns the deployment as the manager now holds it, @@ -160,46 +187,46 @@ async fn request( } } -/// Reports the accepted request: a success line and the next step on the terminal, else one -/// record block on stdout and a notice on stderr. -fn report(lifecycle: Lifecycle, accepted: &T) -> anyhow::Result<()> { - let name = single_line(accepted.name()); - let list = T::GROUP.list_command(); - - if controlling_terminal_condition() == TerminalCondition::Interactive { - let mut terminal = open_terminal(); - terminal.message(&Message::Success(format!( - "{} {name}", - lifecycle.progressive() - )))?; - terminal.message(&Message::Next(vec![ - NextStep::new("Follow its progress:").with_command(list), - ]))?; - return Ok(()); +/// Reports the accepted request: the deployment as the manager holds it as YAML when asked, else +/// a success line. +async fn report( + manager: &Manager, + lifecycle: Lifecycle, + mut accepted: T, + format: OutputFormat, +) -> anyhow::Result<()> { + if format == OutputFormat::Yaml { + accepted.mask_secrets(); + let nodes = manager.node_names().await; + return write_yaml(&DeploymentDocument::new(accepted, &nodes)); } + let name = single_line(accepted.name()); - let prefix = T::GROUP.record_prefix(); - write_records(&format!( - "{}\n{prefix}_ID={}\n{prefix}_NAME={name}\n{prefix}_STATE={}\n{prefix}_DESIRED_STATE={}\n", - T::GROUP.record_title(), - single_line(accepted.id()), - accepted.state_label(), - accepted.desired_state_label(), - ))?; - eprintln!("Notice: Run `{list}` to follow its progress."); - Ok(()) + present(&[Message::Success(format!( + "{} {name}", + lifecycle.progressive() + ))]) } /// Fails when a teardown has neither a terminal to ask on nor `--yes`, before any call to the -/// manager. -fn require_teardown_approval(group: DeploymentGroup, yes: bool) -> anyhow::Result<()> { - if !yes && controlling_terminal_condition() != TerminalCondition::Interactive { - anyhow::bail!( +/// manager. YAML output never asks, so it needs `--yes` too. +fn require_teardown_approval( + group: DeploymentGroup, + yes: bool, + format: OutputFormat, +) -> anyhow::Result<()> { + require_consent( + yes, + format, + &format!( "tearing down {} needs a terminal; run in a terminal or pass --yes to tear it down without confirmation", group.indefinite_noun() - ); - } - Ok(()) + ), + &format!( + "tearing down {} needs confirmation, which --yaml never asks for; pass --yes to tear it down", + group.indefinite_noun() + ), + ) } /// Asks the operator on the terminal to confirm a teardown, cancelling by default. diff --git a/backend/cli/src/management/document.rs b/backend/cli/src/management/document.rs new file mode 100644 index 00000000..90a1b77f --- /dev/null +++ b/backend/cli/src/management/document.rs @@ -0,0 +1,55 @@ +//! The YAML documents of the deployment read commands: each deployment as the manager returns it, +//! plus the names of the node and execution target it runs on. +//! +//! A document never reshapes the manager's message: it keeps the message's protobuf JSON mapping +//! and only adds the display names the CLI resolves, so a script reads the API's own fields. + +use serde::Serialize; + +use super::{ManagedDeployment, NodeNames}; + +/// One deployment message with the display names of where it runs, when the manager named them. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct DeploymentDocument { + #[serde(flatten)] + deployment: T, + + #[serde(skip_serializing_if = "Option::is_none")] + site_node_display_name: Option, + + #[serde(skip_serializing_if = "Option::is_none")] + execution_target_display_name: Option, +} + +impl DeploymentDocument { + /// Wraps a deployment with the names of its placement, if it has one. + pub(crate) fn new(deployment: T, nodes: &NodeNames) -> Self { + let placement = deployment.placement(); + Self { + site_node_display_name: placement + .and_then(|placement| nodes.name(&placement.site_node_id)) + .map(str::to_owned), + execution_target_display_name: placement + .and_then(|placement| { + nodes.target_name(&placement.site_node_id, &placement.execution_target_id) + }) + .map(str::to_owned), + deployment, + } + } +} + +/// The deployments of one kind, shaped as the manager's list response. +#[derive(Debug, Serialize)] +pub(crate) struct DeploymentListDocument { + #[serde(skip_serializing_if = "Vec::is_empty")] + deployments: Vec>, +} + +impl DeploymentListDocument { + /// Lists the documents in the manager's order. + pub(crate) fn new(deployments: Vec>) -> Self { + Self { deployments } + } +} diff --git a/backend/cli/src/management/logs.rs b/backend/cli/src/management/logs.rs index 52dfc57b..94911731 100644 --- a/backend/cli/src/management/logs.rs +++ b/backend/cli/src/management/logs.rs @@ -1,10 +1,11 @@ //! Reads and follows the logs of one deployment through the manager's public logs API, the same //! one the web console uses, so it works for a deployment on any node of the site. //! -//! Log lines go to stdout and nothing else does, so they can be piped. Source availability, -//! truncation notices and the end of a follow go to stderr. A read whose every source is -//! unavailable fails, so an empty result always has a reason; a follow keeps going while sources -//! come and go, and ends when the deployment is removed. +//! Log lines go to stdout and nothing else does, so they can be piped; asked for YAML, each line is +//! one document holding the manager's log entry plus its text as UTF-8. Source availability, truncation notices and the +//! end of a follow go to stderr. A read whose every source is unavailable fails, so an empty result +//! always has a reason; a follow keeps going while sources come and go, and ends when the +//! deployment is removed. use std::{ io::{self, IsTerminal, Write}, @@ -15,13 +16,17 @@ use anyhow::Context; use clap::Args; use dotcore_proto::google::protobuf::Timestamp; use futures_util::{Stream, StreamExt}; +use serde::Serialize; use time::{OffsetDateTime, format_description::well_known::Rfc3339}; use tonic::{Code, Status}; use super::{ ManagedDeployment, ManagementError, Manager, ManagerArgs, call_failed, find_deployment, }; -use crate::terminal::PromptError; +use crate::{ + output::{OutputFormat, YamlDocuments}, + terminal::PromptError, +}; /// Most recent lines one read returns, the manager's page limit. const MAX_LINES: u32 = 200; @@ -29,7 +34,7 @@ const MAX_LINES: u32 = 200; /// Arguments of a deployment's logs command. #[derive(Debug, Args)] pub(crate) struct LogsArgs { - /// Name or id of the deployment. + /// Name or ID of the deployment. #[arg(value_name = "DEPLOYMENT")] reference: String, @@ -62,6 +67,7 @@ pub(crate) struct LogsArgs { /// Prints the referenced deployment's most recent lines, then follows new ones when asked. pub(crate) async fn deployment_logs( arguments: LogsArgs, + format: OutputFormat, ) -> anyhow::Result<()> { let manager = arguments.manager.connect().await?; let deployment = find_deployment::(&manager, &arguments.reference).await?; @@ -76,7 +82,21 @@ pub(crate) async fn deployment_logs( ) .await .map_err(|status| logs_failed(T::GROUP, &subject, &arguments.sources, status))?; - let mut output = LogOutput::new(&arguments, page.sources.len() > 1); + let unavailable = !arguments.follow + && !page.sources.is_empty() + && page + .sources + .iter() + .all(|source| source.state == LogSourceState::Unavailable); + let unavailable_failure = || { + anyhow::anyhow!("every log source of {subject} is unavailable; its node may be unreachable") + }; + // A failed YAML command leaves stdout empty. + if unavailable && format == OutputFormat::Yaml { + return Err(unavailable_failure()); + } + + let mut output = LogOutput::new(&arguments, format, page.sources.len() > 1); output .print(|output| output.page(&page)) .context("cannot write the logs to standard output")?; @@ -85,17 +105,10 @@ pub(crate) async fn deployment_logs( if output.closed { return Ok(()); } + if unavailable { + return Err(unavailable_failure()); + } if !arguments.follow { - let unavailable = !page.sources.is_empty() - && page - .sources - .iter() - .all(|source| source.state == LogSourceState::Unavailable); - if unavailable { - anyhow::bail!( - "every log source of {subject} is unavailable; its node may be unreachable" - ); - } return Ok(()); } @@ -125,13 +138,16 @@ pub(crate) async fn deployment_logs( /// A deployment kind whose logs the manager serves. Each kind's calls use its own messages, which /// the implementations convert to the shared shapes below. pub(crate) trait LoggedDeployment: ManagedDeployment { + /// The manager's message for one line of this kind, printed as it is when asked for YAML. + type Entry: Serialize + Send + 'static; + /// Reads the most recent `page_size` lines of the deployment's selected sources. async fn read_logs( manager: &Manager, id: String, sources: Vec, page_size: u32, - ) -> Result; + ) -> Result, Status>; /// Follows the deployment's selected sources from the given positions. async fn follow_logs( @@ -139,20 +155,20 @@ pub(crate) trait LoggedDeployment: ManagedDeployment { id: String, sources: Vec, positions: Vec, - ) -> Result; + ) -> Result, Status>; } /// The events of a log follow, in arrival order. -pub(crate) type LogEvents = Pin> + Send>>; +pub(crate) type LogEvents = Pin, Status>> + Send>>; /// One read of a deployment's most recent lines. #[derive(Debug)] -pub(crate) struct LogPage { +pub(crate) struct LogPage { /// The selected sources and their availability at the time of the read. pub(crate) sources: Vec, /// The lines, oldest first. - pub(crate) entries: Vec, + pub(crate) entries: Vec>, /// Whether the manager's response size limit dropped older lines of the page. pub(crate) truncated: bool, @@ -189,7 +205,7 @@ pub(crate) enum LogSourceState { /// One line of a log source. #[derive(Debug)] -pub(crate) struct LogEntry { +pub(crate) struct LogEntry { pub(crate) source_name: String, pub(crate) source_label: String, pub(crate) timestamp: Option, @@ -197,6 +213,9 @@ pub(crate) struct LogEntry { /// Whether the manager cut the line at its length limit. pub(crate) truncated: bool, + + /// The line as the manager sent it. + pub(crate) message: E, } /// The timestamp of the latest line already printed for one source. @@ -208,12 +227,12 @@ pub(crate) struct LogPosition { /// One event of a log follow. #[derive(Debug)] -pub(crate) enum LogEvent { +pub(crate) enum LogEvent { /// A source became available or unavailable, or ended. Source(LogSource), /// A new line. - Entry(LogEntry), + Entry(LogEntry), } /// Why a follow stopped early. @@ -226,9 +245,22 @@ enum FollowFailure { Output(io::Error), } +/// One log entry as the manager sent it, plus its line as text. The manager's content is bytes, +/// which the protobuf mapping renders as base64, so the text lets a reader see the line. +#[derive(Serialize)] +struct LogEntryDocument<'a, E> { + #[serde(flatten)] + message: &'a E, + + /// The line as UTF-8, with invalid bytes replaced. + text: String, +} + /// Where log lines and notices are printed, and how lines are shaped. struct LogOutput { stdout: io::Stdout, + format: OutputFormat, + documents: YamlDocuments, labeled: bool, timestamps: bool, sanitized: bool, @@ -236,12 +268,14 @@ struct LogOutput { } impl LogOutput { - fn new(arguments: &LogsArgs, labeled: bool) -> Self { + fn new(arguments: &LogsArgs, format: OutputFormat, labeled: bool) -> Self { let stdout = io::stdout(); // A terminal would act on control sequences in a line; a pipe receives the line as is. let sanitized = stdout.is_terminal(); Self { stdout, + format, + documents: YamlDocuments::default(), labeled, timestamps: arguments.timestamps, sanitized, @@ -264,7 +298,7 @@ impl LogOutput { } } - fn page(&mut self, page: &LogPage) -> io::Result<()> { + fn page(&mut self, page: &LogPage) -> io::Result<()> { for entry in &page.entries { self.entry(entry)?; } @@ -282,7 +316,10 @@ impl LogOutput { } /// Prints events until the follow ends, returning the failure that ended it, if any. - async fn follow(&mut self, mut events: LogEvents) -> Result<(), FollowFailure> { + async fn follow( + &mut self, + mut events: LogEvents, + ) -> Result<(), FollowFailure> { while let Some(event) = events.next().await { match event.map_err(FollowFailure::Manager)? { LogEvent::Source(source) => source_notice(&source), @@ -298,7 +335,15 @@ impl LogOutput { Ok(()) } - fn entry(&mut self, entry: &LogEntry) -> io::Result<()> { + fn entry(&mut self, entry: &LogEntry) -> io::Result<()> { + if self.format == OutputFormat::Yaml { + let document = LogEntryDocument { + message: &entry.message, + text: String::from_utf8_lossy(&entry.content).into_owned(), + }; + return self.documents.write(&mut self.stdout.lock(), &document); + } + let mut line = String::new(); if self.timestamps { line.push_str(&format_timestamp(entry.timestamp.as_ref())); diff --git a/backend/cli/src/management/mod.rs b/backend/cli/src/management/mod.rs index 2e75fa78..294a7c24 100644 --- a/backend/cli/src/management/mod.rs +++ b/backend/cli/src/management/mod.rs @@ -1,12 +1,11 @@ //! The connection that commands open to the running site manager's management API, and the rules -//! deployment management shares for naming a deployment and reporting what the manager refused. +//! deployment management shares for reporting what the manager refused. //! //! The address comes from a flag or the environment and takes an optional `http://` scheme; this //! is the only place that decides the transport, so TLS and credentials can be added here alone. -//! A deployment is named by its id or its name. Names are not unique, so a name matching several -//! deployments fails with their ids instead of picking one. mod deployment; +mod document; mod logs; use std::{collections::HashMap, fmt, str::FromStr, time::Duration}; @@ -15,6 +14,7 @@ use clap::Args; use dotcore::composition::{DEFAULT_MANAGEMENT_ADDR, MANAGEMENT_ADDR_ENV}; use dotcore_proto::dotcore::{ application::v1::application_deployment_service_client::ApplicationDeploymentServiceClient, + catalog::v1::catalog_service_client::CatalogServiceClient, model::v1::model_deployment_service_client::ModelDeploymentServiceClient, site::v1::{ ConfiguredExecutionTarget, ListConfiguredExecutionTargetsRequest, @@ -31,6 +31,7 @@ use tonic::{ pub(crate) use deployment::{ Lifecycle, ManagedDeployment, change_lifecycle, find_deployment, list_deployments, teardown, }; +pub(crate) use document::{DeploymentDocument, DeploymentListDocument}; pub(crate) use logs::{ LogEntry, LogEvent, LogEvents, LogPage, LogPosition, LogSource, LogSourceState, LoggedDeployment, LogsArgs, deployment_logs, @@ -47,7 +48,9 @@ pub(crate) struct ManagerArgs { long = "manager", env = MANAGEMENT_ADDR_ENV, value_name = "ADDRESS", - default_value = DEFAULT_MANAGEMENT_ADDR + default_value = DEFAULT_MANAGEMENT_ADDR, + // Last in every command's option list, after the root options. + display_order = 1000 )] pub(crate) manager: ManagerAddress, } @@ -150,6 +153,11 @@ impl Manager { SiteServiceClient::new(self.channel.clone()) } + /// Returns a client of the catalog service, which lists what the site can deploy. + pub(crate) fn catalog(&self) -> CatalogServiceClient { + CatalogServiceClient::new(self.channel.clone()) + } + /// Returns a client of the model deployment service. pub(crate) fn models(&self) -> ModelDeploymentServiceClient { ModelDeploymentServiceClient::new(self.channel.clone()) @@ -190,15 +198,25 @@ pub(crate) struct NodeNames { impl NodeNames { /// Returns the node's display name, or its id when the manager did not name it. pub(crate) fn display<'a>(&'a self, node_id: &'a str) -> &'a str { - self.names.get(node_id).map_or(node_id, String::as_str) + self.name(node_id).unwrap_or(node_id) } /// Returns the execution target's display name, or its id when the target is no longer /// configured or the manager did not name it. pub(crate) fn target_display<'a>(&'a self, node_id: &str, target_id: &'a str) -> &'a str { + self.target_name(node_id, target_id).unwrap_or(target_id) + } + + /// Returns the node's display name, if the manager named it. + pub(crate) fn name(&self, node_id: &str) -> Option<&str> { + self.names.get(node_id).map(String::as_str) + } + + /// Returns the execution target's display name, if the target is configured and named. + pub(crate) fn target_name(&self, node_id: &str, target_id: &str) -> Option<&str> { self.targets .get(&(node_id.to_owned(), target_id.to_owned())) - .map_or(target_id, String::as_str) + .map(String::as_str) } fn from_targets(configured: &[ConfiguredExecutionTarget]) -> Self { @@ -227,6 +245,12 @@ impl NodeNames { .collect(); Self { names, targets } } + + /// The names the given configured targets carry. + #[cfg(test)] + pub(crate) fn of_targets(configured: &[ConfiguredExecutionTarget]) -> Self { + Self::from_targets(configured) + } } /// Which deployment command group a reference or request belongs to, which picks its wording and @@ -262,72 +286,6 @@ impl DeploymentGroup { Self::Application => "dotc application list", } } - - /// The title line of a deployment's result record block, for example `Model deployment`. - pub(crate) fn record_title(self) -> &'static str { - match self { - Self::Model => "Model deployment", - Self::Application => "Application deployment", - } - } - - /// The prefix of a deployment's result record keys, for example `DOTCORE_MODEL_DEPLOYMENT`. - pub(crate) fn record_prefix(self) -> &'static str { - match self { - Self::Model => "DOTCORE_MODEL_DEPLOYMENT", - Self::Application => "DOTCORE_APPLICATION_DEPLOYMENT", - } - } -} - -/// A deployment the operator can name by its id or its name. -pub(crate) trait Addressable { - /// The stable deployment id. - fn id(&self) -> &str; - - /// The name shown to the operator, which need not be unique. - fn name(&self) -> &str; - - /// The name as the manager stores it, empty when none; it also names the deployment. - fn stored_name(&self) -> &str; -} - -/// Finds the deployment an operator reference names: an exact id first, else the one deployment -/// whose shown or stored name is exactly the reference. -pub(crate) fn resolve<'a, T: Addressable>( - group: DeploymentGroup, - reference: &str, - deployments: &'a [T], -) -> Result<&'a T, ReferenceError> { - if let Some(deployment) = deployments - .iter() - .find(|deployment| deployment.id() == reference) - { - return Ok(deployment); - } - - let named = deployments - .iter() - .filter(|deployment| { - deployment.name() == reference - || (!deployment.stored_name().is_empty() && deployment.stored_name() == reference) - }) - .collect::>(); - match named.as_slice() { - [] => Err(ReferenceError::Unknown { - group, - reference: reference.to_owned(), - }), - [deployment] => Ok(deployment), - several => Err(ReferenceError::Ambiguous { - group, - reference: reference.to_owned(), - ids: several - .iter() - .map(|deployment| deployment.id().to_owned()) - .collect(), - }), - } } /// Builds the mapping of a failed management call to the error shown to the operator, naming @@ -405,23 +363,6 @@ pub(crate) enum ManagementError { }, } -/// An operator reference that names no deployment, or several. -#[derive(Debug, thiserror::Error)] -pub(crate) enum ReferenceError { - #[error("no {} is named or has id {reference:?}", .group.noun())] - Unknown { - group: DeploymentGroup, - reference: String, - }, - - #[error("{} {}s are named {reference:?}: {}", .ids.len(), .group.noun(), .ids.join(", "))] - Ambiguous { - group: DeploymentGroup, - reference: String, - ids: Vec, - }, -} - #[cfg(test)] mod tests { use clap::{CommandFactory, Parser}; @@ -435,62 +376,12 @@ mod tests { manager: ManagerArgs, } - struct Named { - id: &'static str, - name: &'static str, - stored: &'static str, - } - - impl Addressable for Named { - fn id(&self) -> &str { - self.id - } - - fn name(&self) -> &str { - self.name - } - - fn stored_name(&self) -> &str { - self.stored - } - } - fn address(text: &str) -> Result { text.parse::() .map(|address| address.to_string()) .map_err(|error| error.to_string()) } - fn deployments() -> Vec { - vec![ - Named { - id: "model-1", - name: "Gemma", - stored: "", - }, - Named { - id: "model-2", - name: "Qwen", - stored: "", - }, - Named { - id: "model-3", - name: "Qwen", - stored: "", - }, - Named { - id: "model-4", - name: "model-1", - stored: "", - }, - Named { - id: "app-1", - name: "Open WebUI", - stored: "open-webui-1", - }, - ] - } - #[test] fn addresses_take_an_optional_http_scheme_and_normalize_to_it() { assert_eq!( @@ -579,78 +470,6 @@ mod tests { assert_eq!(error.exit_code(), 2); } - #[test] - fn references_match_an_id_before_a_name() { - let deployments = deployments(); - - assert_eq!( - resolve(DeploymentGroup::Model, "model-2", &deployments) - .map(|deployment| deployment.id) - .ok(), - Some("model-2") - ); - assert_eq!( - resolve(DeploymentGroup::Model, "Gemma", &deployments) - .map(|deployment| deployment.id) - .ok(), - Some("model-1") - ); - assert_eq!( - resolve(DeploymentGroup::Model, "model-1", &deployments) - .map(|deployment| deployment.id) - .ok(), - Some("model-1"), - "an id wins over another deployment named like it" - ); - } - - #[test] - fn references_match_the_stored_name_as_well_as_the_shown_name() { - let deployments = deployments(); - - for reference in ["open-webui-1", "Open WebUI", "app-1"] { - assert_eq!( - resolve(DeploymentGroup::Application, reference, &deployments) - .map(|deployment| deployment.id) - .ok(), - Some("app-1"), - "{reference}" - ); - } - assert_eq!( - resolve(DeploymentGroup::Application, "", &deployments) - .err() - .expect("an empty stored name never matches") - .to_string(), - "no application deployment is named or has id \"\"" - ); - } - - #[test] - fn unknown_and_ambiguous_references_fail_with_the_matching_ids() { - let deployments = deployments(); - - let unknown = resolve(DeploymentGroup::Model, "gemma", &deployments) - .err() - .expect("names match exactly"); - assert_eq!( - unknown.to_string(), - "no model deployment is named or has id \"gemma\"" - ); - - let ambiguous = resolve(DeploymentGroup::Application, "Qwen", &deployments) - .err() - .expect("two deployments share the name"); - assert!(matches!( - &ambiguous, - ReferenceError::Ambiguous { ids, .. } if ids == &["model-2", "model-3"] - )); - assert_eq!( - ambiguous.to_string(), - "2 application deployments are named \"Qwen\": model-2, model-3" - ); - } - #[test] fn single_line_collapses_whitespace_and_control_characters() { assert_eq!(single_line(" a\n\tb \u{1b}[2J c\r\n"), "a b [2J c"); diff --git a/backend/cli/src/management/route.rs b/backend/cli/src/management/route.rs deleted file mode 100644 index 5a4ff528..00000000 --- a/backend/cli/src/management/route.rs +++ /dev/null @@ -1,105 +0,0 @@ -//! Reads the inference routes of the running site as an inference client sees them. -//! -//! Only enabled routes are returned, since a disabled route refuses every request. Each keeps its -//! callable name and whether a ready model deployment currently serves it, in the manager's -//! name order. - -use dotcore_proto::dotcore::inference::v1::{ - InferenceRouteView, ListRoutesRequest, route_service_client::RouteServiceClient, -}; - -use super::{ManagementError, Manager}; - -/// An enabled inference route as an inference client sees it. -#[derive(Clone, Debug, Eq, PartialEq)] -pub(crate) struct InferenceRoute { - /// The callable name, which inference requests pass as their model. - pub(crate) name: String, - - /// Whether a ready model deployment serves the route right now. - pub(crate) available: bool, -} - -/// Reads the enabled inference routes in the manager's order. -pub(crate) async fn list_enabled_routes( - manager: &Manager, -) -> Result, ManagementError> { - let response = RouteServiceClient::new(manager.channel.clone()) - .list_routes(ListRoutesRequest {}) - .await - .map_err(|status| ManagementError::RouteList { - code: status.code(), - message: status.message().to_owned(), - })?; - Ok(enabled_routes(response.into_inner().routes)) -} - -/// Keeps the enabled routes with their name and availability. -fn enabled_routes(views: Vec) -> Vec { - views - .into_iter() - .filter_map(|view| { - let route = view.route.filter(|route| route.enabled)?; - Some(InferenceRoute { - name: route.name, - available: view - .availability - .is_some_and(|availability| availability.available), - }) - }) - .collect() -} - -#[cfg(test)] -mod tests { - use dotcore_proto::dotcore::inference::v1::{ - InferenceRoute as RouteDeclaration, InferenceRouteAvailability, - }; - - use super::*; - - fn view(name: &str, enabled: bool, available: Option) -> InferenceRouteView { - InferenceRouteView { - route: Some(RouteDeclaration { - inference_route_id: format!("route-{name}"), - name: name.to_owned(), - enabled, - ..Default::default() - }), - availability: available.map(|available| InferenceRouteAvailability { - available, - ..Default::default() - }), - request_kinds: Vec::new(), - } - } - - #[test] - fn only_enabled_routes_are_kept_with_their_availability_in_order() { - let routes = enabled_routes(vec![ - view("chat", true, Some(true)), - view("disabled", false, Some(false)), - view("embed", true, Some(false)), - view("unknown", true, None), - InferenceRouteView::default(), - ]); - - assert_eq!( - routes, - vec![ - InferenceRoute { - name: "chat".to_owned(), - available: true, - }, - InferenceRoute { - name: "embed".to_owned(), - available: false, - }, - InferenceRoute { - name: "unknown".to_owned(), - available: false, - }, - ] - ); - } -} diff --git a/backend/cli/src/model/catalog.rs b/backend/cli/src/model/catalog.rs new file mode 100644 index 00000000..2c047ec7 --- /dev/null +++ b/backend/cli/src/model/catalog.rs @@ -0,0 +1,255 @@ +//! Lists the catalog models the running site can deploy, with whether each profile fits each +//! model target. +//! +//! Fit comes from the site's profile compatibility read, which estimates each profile's defaults +//! against every configured target: it fits now, needs memory freed, is too large, or can't run. +//! Asked for YAML, it prints the catalog models and the compatibility response as returned. + +use clap::Args; +use dotcore_proto::dotcore::{ + catalog::v1::Model, + deployment::v1::MemoryFit, + model::v1::{ + ListModelProfileCompatibilityRequest, ListModelProfileCompatibilityResponse, + ModelCompatibilityStatus, ModelProfileCompatibility, + }, +}; +use serde::Serialize; + +use super::site::DeploySite; +use crate::{ + management::{DeploymentGroup, ManagerArgs, NodeNames, call_failed, single_line}, + output::{OutputFormat, present, write_yaml}, + reference::{Referable, ReferenceKind, resolve}, + terminal::Message, +}; + +/// Arguments for listing the deployable catalog models. +#[derive(Debug, Args)] +pub struct ModelCatalogArgs { + /// Catalog model to show alone: its ID, name, or a unique part of either. + #[arg(value_name = "MODEL")] + model: Option, + + #[command(flatten)] + manager: ManagerArgs, +} + +/// Lists the catalog models and their profiles' fit, as YAML when asked, else as a table. +pub(crate) async fn model_catalog( + arguments: ModelCatalogArgs, + format: OutputFormat, +) -> anyhow::Result<()> { + let manager = arguments.manager.connect().await?; + let catalog = SiteCatalog::read(&manager, arguments.model.as_deref()).await?; + + if format == OutputFormat::Yaml { + return write_yaml(&CatalogDocument { + models: &catalog.models, + compatibility: &catalog.compatibility, + }); + } + + if catalog.models.is_empty() { + return present(&[Message::Info("No catalog models".to_owned())]); + } + present(&[table(&catalog)]) +} + +/// The catalog models the site can deploy, with their profiles' compatibility on every model +/// target, read together so every model command decides from one view. +pub(super) struct SiteCatalog { + /// Local catalog models, one when a model was named. + pub(super) models: Vec, + + /// Each profile's compatibility on each configured model target. + pub(super) compatibility: ListModelProfileCompatibilityResponse, + + /// Display names of the nodes and their targets. + pub(super) nodes: NodeNames, +} + +impl SiteCatalog { + /// Reads the catalog and the compatibility of every profile, narrowed to the model `reference` + /// names when given. + pub(super) async fn read( + site: &dyn DeploySite, + reference: Option<&str>, + ) -> anyhow::Result { + let mut models = site.list_models().await.map_err(call_failed( + DeploymentGroup::Model, + "read the model catalog", + ))?; + if let Some(reference) = reference { + let model = resolve(ReferenceKind::CatalogModel, reference, &models)?.clone(); + models = vec![model]; + } + let model_id = reference + .and(models.first()) + .map(|model| model.model_id.clone()); + let compatibility = site + .compatibility(ListModelProfileCompatibilityRequest { + model_id, + target: None, + scenario: None, + }) + .await + .map_err(call_failed( + DeploymentGroup::Model, + "read where the catalog models fit", + ))?; + Ok(Self { + models, + compatibility, + nodes: site.node_names().await, + }) + } + + /// The compatibility entries of one profile, one per target that runs models, in node then + /// target order. + pub(super) fn entries( + &self, + model_id: &str, + profile_id: &str, + ) -> impl Iterator { + let (model_id, profile_id) = (model_id.to_owned(), profile_id.to_owned()); + self.compatibility + .entries + .iter() + .filter(move |entry| entry.model_id == model_id && entry.profile_id == profile_id) + } +} + +/// The YAML document of the catalog: the models and the compatibility response, as returned. +#[derive(Serialize)] +struct CatalogDocument<'a> { + models: &'a [Model], + + compatibility: &'a ListModelProfileCompatibilityResponse, +} + +/// The operator words for whether a profile fits a target now. +pub(super) fn fit_label(entry: &ModelProfileCompatibility) -> &'static str { + match entry.status() { + ModelCompatibilityStatus::Runs => match (entry.memory_fit(), entry.free_memory_fit()) { + (_, MemoryFit::Fits) => "fits now", + (MemoryFit::Fits, MemoryFit::Exceeds) => "needs memory freed", + (MemoryFit::Exceeds, _) => "too large", + (MemoryFit::Unspecified, _) => "unsupported sizing", + _ => "fit unknown", + }, + ModelCompatibilityStatus::CannotRun => "can't run", + ModelCompatibilityStatus::Unknown | ModelCompatibilityStatus::Unspecified => "unknown", + } +} + +/// Why a profile can't run on a target, or can't be judged there, in operator words; `machine` is +/// the target's node as the operator knows it. +pub(super) fn reason_words(entry: &ModelProfileCompatibility, machine: &str) -> String { + use dotcore_proto::dotcore::model::v1::ModelCompatibilityReasonCode as Code; + + let reason = entry.reason.clone().unwrap_or_default(); + match reason.code() { + Code::TargetNotReporting => format!("{machine} isn't reporting"), + Code::NvidiaDriverUnknown => format!("{machine}'s NVIDIA driver version is unknown"), + Code::AcceleratorMemoryUnknown => format!("{machine}'s GPU memory type is unknown"), + Code::TargetPlatformInvalid => format!("{machine} has no supported platform configured"), + Code::PlatformMismatch => { + format!("{machine} reports another platform than the configured one") + } + Code::NoAccelerator => format!("{machine} reports no usable GPU"), + Code::NoMatchingEngineArtifact => { + format!("no engine build of this profile runs on {machine}") + } + Code::NoSupportedHardwareClass => format!("not supported on {machine}'s hardware"), + Code::NvidiaDriverBelowMinimum => format!( + "needs NVIDIA driver {} or later (has {})", + reason.minimum_nvidia_driver_major_version, reason.observed_nvidia_driver_major_version + ), + Code::AcceleratorDeviceCountMismatch => format!( + "needs {} GPUs, the target has {}", + reason.required_accelerator_device_count, reason.accelerator_device_count + ), + Code::ProfileUnresolvable => format!("its launch settings don't resolve on {machine}"), + Code::Unspecified => match entry.status() { + ModelCompatibilityStatus::CannotRun => format!("can't run on {machine}"), + _ => format!("can't check {machine} right now"), + }, + } +} + +/// The best fit among compatibility entries, in the words of [`fit_label`]: fitting now first, +/// then needing memory freed, too large, and any other word; none without an entry. +pub(super) fn best_fit<'a>( + entries: impl IntoIterator, +) -> Option<&'static str> { + const ORDER: [&str; 7] = [ + "fits now", + "needs memory freed", + "too large", + "unsupported sizing", + "fit unknown", + "can't run", + "unknown", + ]; + entries + .into_iter() + .map(fit_label) + .min_by_key(|label| ORDER.iter().position(|word| word == label)) +} + +fn table(catalog: &SiteCatalog) -> Message { + let mut rows = Vec::new(); + for model in &catalog.models { + for profile in &model.profiles { + let row = |target: String, fit: &str| { + vec![ + single_line(&model.display_name), + single_line(&model.model_id), + single_line(&profile.profile_id), + target, + fit.to_owned(), + ] + }; + let mut entries = catalog + .entries(&model.model_id, &profile.profile_id) + .peekable(); + if entries.peek().is_none() { + rows.push(row("-".to_owned(), "no model target")); + } + for entry in entries { + let target = entry.target.as_ref().map_or_else( + || "-".to_owned(), + |target| { + single_line(&format!( + "{} {}", + catalog.nodes.display(&target.site_node_id), + catalog + .nodes + .target_display(&target.site_node_id, &target.execution_target_id) + )) + }, + ); + rows.push(row(target, fit_label(entry))); + } + } + } + + Message::Table { + header: ["MODEL", "ID", "PROFILE", "TARGET", "FIT"] + .into_iter() + .map(str::to_owned) + .collect(), + rows, + } +} + +impl Referable for Model { + fn id(&self) -> &str { + &self.model_id + } + + fn name(&self) -> &str { + &self.display_name + } +} diff --git a/backend/cli/src/model/context.rs b/backend/cli/src/model/context.rs new file mode 100644 index 00000000..158e7a0b --- /dev/null +++ b/backend/cli/src/model/context.rs @@ -0,0 +1,205 @@ +//! The server's answers about a deployment's context, in the operator's words. +//! +//! An estimate says how far each context field may go and why, what the engine does when an +//! overcommitted total context fills up, and which value a launch would reject. This module only +//! words those answers; it never works out a bound, a total or a check itself. + +use dotcore_catalog::launch_rejection::{LaunchRejection as Rejection, LaunchRejectionKind}; +use dotcore_proto::dotcore::model::v1::{ + ContextBound, ContextBoundReason, ContextOvercommit, ContextOvercommitConsequence, + EstimateLocalModelResourcesResponse, LaunchRejection, LaunchRejectionReason, +}; + +use super::view::{CONTEXT_PER_REQUEST, TOTAL_CONTEXT}; + +/// A value a launch would reject: the parameter that fixes it and why, as one sentence. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(super) struct Rejected { + pub(super) parameter_id: String, + pub(super) text: String, +} + +/// The first value a launch of the estimated configuration would reject, if any. +pub(super) fn rejected(estimate: &EstimateLocalModelResourcesResponse) -> Option { + estimate + .hardware_class_estimates + .iter() + .find_map(|entry| entry.launch_rejection.as_ref()) + .map(rejection) +} + +/// One rejection in words, with the catalog's sentence for its reason. +pub(super) fn rejection(rejection: &LaunchRejection) -> Rejected { + let (value, limit) = (rejection.value, rejection.limit); + let kind = match rejection.reason() { + LaunchRejectionReason::AboveModelMaximum => Some(LaunchRejectionKind::AboveModelMaximum { + value, + maximum: limit, + }), + LaunchRejectionReason::AboveTotalContext => Some(LaunchRejectionKind::AboveTotalContext { + value, + share: limit, + }), + LaunchRejectionReason::AboveDerivedTotal => Some(LaunchRejectionKind::AboveDerivedTotal { + value, + derived_total: limit, + }), + LaunchRejectionReason::NotStepMultiple => { + Some(LaunchRejectionKind::NotStepMultiple { value, step: limit }) + } + LaunchRejectionReason::Unspecified => None, + }; + let text = match kind { + Some(kind) => sentence(&Rejection::new(&rejection.parameter_id, kind).to_string()), + None => format!("A launch rejects {} {value}", rejection.parameter_id), + }; + Rejected { + parameter_id: rejection.parameter_id.clone(), + text, + } +} + +/// How far a context field may go and why, for the field's accepted range; none when nothing +/// bounds it. +pub(super) fn bound_text( + estimate: &EstimateLocalModelResourcesResponse, + key: &str, +) -> Option { + bound(estimate, key).map(|(tokens, reason)| format!("up to {tokens} · {reason}")) +} + +/// A context field's upper bound in tokens and its reason in words. +pub(super) fn bound( + estimate: &EstimateLocalModelResourcesResponse, + key: &str, +) -> Option<(u64, &'static str)> { + let bound = match key { + TOTAL_CONTEXT => estimate.total_context_bound.as_ref(), + CONTEXT_PER_REQUEST => estimate.context_per_request_bound.as_ref(), + _ => None, + }?; + Some((bound.tokens, bound_reason(bound))) +} + +/// A note on total context when it is set above what the engine can use, from its bound's reason. +pub(super) fn unused_total( + estimate: &EstimateLocalModelResourcesResponse, + total: Option, +) -> Option { + let bound = estimate.total_context_bound.as_ref()?; + (bound.reason() == ContextBoundReason::EngineCannotUseMore + && total.is_some_and(|total| total > bound.tokens)) + .then(|| format!("The engine uses only {} of it", bound.tokens)) +} + +/// What happens once an overcommitted total context fills up, as a warning; none when the +/// estimate isn't overcommitted or the engine copes without a word, by moving requests to host +/// memory. +pub(super) fn overcommit_warning(estimate: &EstimateLocalModelResourcesResponse) -> Option { + overcommit_label(estimate.overcommit.as_ref()?) + .map(|label| format!("Overcommitted: once the total context is full, {label}")) +} + +/// What an overcommitted total context's engine does once its requests fill it; none when it +/// moves them to host memory and resumes them. +pub(super) fn overcommit_label(overcommit: &ContextOvercommit) -> Option<&'static str> { + match overcommit.consequence() { + ContextOvercommitConsequence::ActiveRequestsFail => Some("active requests fail"), + ContextOvercommitConsequence::RequestsRecomputed => Some("requests are recomputed"), + ContextOvercommitConsequence::RequestsSwapToHost + | ContextOvercommitConsequence::Unspecified => None, + } +} + +fn bound_reason(bound: &ContextBound) -> &'static str { + match bound.reason() { + ContextBoundReason::ModelMaximum => "the model's maximum", + ContextBoundReason::EngineMaximum => "the engine's maximum", + ContextBoundReason::EngineCannotUseMore => "the engine can't use more", + ContextBoundReason::LargestFit => "the largest that fits", + ContextBoundReason::Unspecified => "the server's limit", + } +} + +/// A text starting with a capital letter. +fn sentence(text: &str) -> String { + let mut chars = text.chars(); + chars.next().map_or_else(String::new, |first| { + first.to_uppercase().chain(chars).collect() + }) +} + +#[cfg(test)] +mod tests { + use dotcore_proto::dotcore::model::v1::{ + ContextBound, ContextBoundReason, ContextOvercommit, ContextOvercommitConsequence, + EstimateLocalModelResourcesResponse, LaunchRejection, LaunchRejectionReason, + }; + + use super::{Rejected, bound_text, overcommit_warning, rejection, unused_total}; + + #[test] + fn a_rejection_reads_as_the_catalog_sentence_for_its_reason() { + let above = LaunchRejection { + parameter_id: "total-context".to_owned(), + reason: LaunchRejectionReason::AboveDerivedTotal as i32, + value: 40_000, + limit: 32_768, + }; + assert_eq!( + rejection(&above), + Rejected { + parameter_id: "total-context".to_owned(), + text: "Total context of 40000 tokens is above the 32768 tokens the parallel \ + requests use at this context per request; lower the total context, or \ + raise the parallel requests or the context per request" + .to_owned(), + } + ); + } + + #[test] + fn bounds_overcommit_and_unused_total_read_from_the_estimate() { + let estimate = EstimateLocalModelResourcesResponse { + total_context_bound: Some(ContextBound { + tokens: 32_768, + reason: ContextBoundReason::EngineCannotUseMore as i32, + }), + context_per_request_bound: Some(ContextBound { + tokens: 262_144, + reason: ContextBoundReason::ModelMaximum as i32, + }), + overcommit: Some(ContextOvercommit { + consequence: ContextOvercommitConsequence::ActiveRequestsFail as i32, + }), + ..EstimateLocalModelResourcesResponse::default() + }; + + assert_eq!( + bound_text(&estimate, "context-per-request").as_deref(), + Some("up to 262144 · the model's maximum") + ); + assert_eq!( + bound_text(&estimate, "total-context").as_deref(), + Some("up to 32768 · the engine can't use more") + ); + assert_eq!(bound_text(&estimate, "parallel-requests"), None); + assert_eq!( + unused_total(&estimate, Some(65_536)).as_deref(), + Some("The engine uses only 32768 of it") + ); + assert_eq!(unused_total(&estimate, Some(32_768)), None); + assert_eq!( + overcommit_warning(&estimate).as_deref(), + Some("Overcommitted: once the total context is full, active requests fail") + ); + + let swaps = EstimateLocalModelResourcesResponse { + overcommit: Some(ContextOvercommit { + consequence: ContextOvercommitConsequence::RequestsSwapToHost as i32, + }), + ..EstimateLocalModelResourcesResponse::default() + }; + assert_eq!(overcommit_warning(&swaps), None); + } +} diff --git a/backend/cli/src/model/deploy.rs b/backend/cli/src/model/deploy.rs new file mode 100644 index 00000000..09e5e845 --- /dev/null +++ b/backend/cli/src/model/deploy.rs @@ -0,0 +1,448 @@ +//! Deploys one local model step by step on a terminal, or from its starting values after +//! confirmation. +//! +//! On a terminal without an agreement beforehand, a guided flow asks for each choice. Otherwise +//! the model's starting values are deployed, with the choices and overrides named on the command +//! line applied on top. Both ways build the same payload and send the same request. A dry run has +//! the server estimate the result and creates nothing: it reports the fit, how full each memory +//! would be, the bounds and largest fits, the values sizing derives, every parameter an override +//! can set with its value and what it accepts, and any reason a launch would reject the values. +//! Only an invalid override or a launch rejection fails it. + +use clap::Args; +use dotcore_proto::dotcore::{ + catalog::v1::ParameterValues, + model::v1::{ + CreateLocalModelDeploymentRequest, CreateModelDeploymentRequest, + EstimateLocalModelResourcesResponse, LocalModelDeploymentAdvisory, ModelDeployment, + create_model_deployment_request, + }, +}; +use serde::Serialize; + +use super::{ + context::rejected, + document, + estimate::estimate, + memory::memory_block, + payload::{ModelPayload, PayloadError}, + selection::{Choices, Selection, select}, + site::DeploySite, + view::{ParameterView, ViewParameter}, + wizard::{self, WizardDefaults}, +}; +use crate::{ + deploy::{PlainValue, Setting}, + management::{DeploymentGroup, Manager, ManagerArgs, call_failed}, + output::{OutputFormat, present, require_consent, write_yaml}, + terminal::{ + ConfirmPrompt, Message, PromptError, TerminalCondition, controlling_terminal_condition, + open_terminal, + }, +}; + +/// Arguments for deploying a model. +#[derive(Debug, Args)] +pub struct ModelDeployArgs { + /// Catalog model: its ID, name, or a unique part of either. Chosen on a terminal when left + /// out. + #[arg(value_name = "MODEL")] + model: Option, + + /// Profile ID or name; the first that fits the target by default. + #[arg(long)] + profile: Option, + + /// Node to deploy on; the first where a profile fits by default. + #[arg(long)] + node: Option, + + /// Execution target on the node, when it has several. + #[arg(long)] + target: Option, + + /// Set a parameter, or an option parameter as `option..`; a dry run + /// lists them. + #[arg(long = "set", value_name = "ID=VALUE", value_parser = Setting::parse)] + settings: Vec, + + /// Display name of the deployment. + #[arg(long)] + name: Option, + + /// Name of the route created with the deployment. + #[arg(long)] + route: Option, + + /// Estimate the deployment, list its parameters and report its fit without creating it. + #[arg(long)] + dry_run: bool, + + /// Deploy without asking for confirmation. + #[arg(long)] + yes: bool, + + #[command(flatten)] + manager: ManagerArgs, +} + +/// Deploys step by step on a terminal, else the starting values, or reports their estimate on a +/// dry run. +pub(crate) async fn model_deploy( + arguments: ModelDeployArgs, + format: OutputFormat, +) -> anyhow::Result<()> { + if guided(&arguments, format, controlling_terminal_condition())? { + let manager = arguments.manager.connect().await?; + let deployed = wizard::run( + &manager, + open_terminal().as_mut(), + WizardDefaults { + model: arguments.model, + profile: arguments.profile, + node: arguments.node, + target: arguments.target, + name: arguments.name, + route: arguments.route, + settings: arguments.settings, + }, + ) + .await?; + let name = deployed.payload.name.clone().unwrap_or_default(); + return report_deployed(&manager, deployed.deployment, &name, format).await; + } + + let manager = arguments.manager.connect().await?; + let (selection, payload) = starting_selection(&manager, &arguments).await?; + + if arguments.dry_run { + let estimate = estimate(&manager, &selection, &payload).await?; + return report_dry_run(&selection, &payload, estimate, format); + } + + require_consent( + arguments.yes, + format, + "deploying needs a terminal to confirm; run in a terminal or pass --yes", + "deploying needs confirmation, which --yaml never asks for; pass --yes to deploy", + )?; + let name = deployment_name(&selection, &payload); + if !arguments.yes { + let question = format!( + "Deploy {name} ({}) on {} {}?", + selection.profile.profile_id, selection.node_name, selection.target_name + ); + if !open_terminal().confirm(&ConfirmPrompt::new(question, true))? { + return Err(PromptError::Cancelled.into()); + } + } + + let deployment = manager + .create(create_request(&selection, &payload)?) + .await + .map_err(call_failed( + DeploymentGroup::Model, + format!("deploy {name}"), + ))?; + report_deployed(&manager, deployment, &name, format).await +} + +/// The payload of an untouched deployment of the selection: its model, profile, target, name and +/// a route named after the model, with no parameter changed. +pub(super) fn starting_payload(selection: &Selection) -> ModelPayload { + ModelPayload { + model: selection.model.model_id.clone(), + profile: Some(selection.profile.profile_id.clone()), + node: Some(selection.node_name.clone()), + target: selection + .shared_node + .then(|| selection.placement.execution_target_id.clone()), + name: Some(selection.model.display_name.clone()), + route: Some(selection.model.model_id.clone()), + ..ModelPayload::default() + } +} + +/// The request creating the payload's deployment of the selection; every deploy sends this one. +pub(super) fn create_request( + selection: &Selection, + payload: &ModelPayload, +) -> Result { + Ok(CreateModelDeploymentRequest { + source: Some(create_model_deployment_request::Source::Local( + CreateLocalModelDeploymentRequest { + model_id: selection.model.model_id.clone(), + profile_id: selection.profile.profile_id.clone(), + placement: Some(selection.placement.clone()), + configuration: Some(payload.configuration(&selection.schema())?), + }, + )), + exposure: Some(payload.exposure()), + model_deployment_name: payload.name.clone(), + }) +} + +/// The name a deployment is shown by: the payload's, else the model's. +pub(super) fn deployment_name(selection: &Selection, payload: &ModelPayload) -> String { + payload + .name + .clone() + .unwrap_or_else(|| selection.model.display_name.clone()) +} + +/// The operator words of the preview's advisories that need them. +pub(super) fn advisories_words(selection: &Selection) -> Vec<&'static str> { + selection + .advisories + .iter() + .filter_map(|advisory| match advisory { + LocalModelDeploymentAdvisory::HostKvOffloadSharesMemory => { + Some("Host KV cache offload adds no memory on a target that shares host memory") + } + LocalModelDeploymentAdvisory::UnifiedMemoryPoolBelowDeviceMinimum => { + Some("The target's shared memory is below the model's per-device memory minimum") + } + LocalModelDeploymentAdvisory::Unspecified => None, + }) + .collect() +} + +/// Resolves the command line's choices on the site, then applies its name, route and overrides +/// to the selection's starting payload. +async fn starting_selection( + site: &dyn DeploySite, + arguments: &ModelDeployArgs, +) -> anyhow::Result<(Selection, ModelPayload)> { + let selection = select( + site, + &Choices { + model: arguments.model.as_deref().unwrap_or_default(), + profile: arguments.profile.as_deref(), + node: arguments.node.as_deref(), + target: arguments.target.as_deref(), + }, + ) + .await?; + let mut payload = starting_payload(&selection); + if arguments.name.is_some() { + payload.name.clone_from(&arguments.name); + } + if arguments.route.is_some() { + payload.route.clone_from(&arguments.route); + } + payload.apply(&arguments.settings)?; + payload.configuration(&selection.schema())?; + Ok((selection, payload)) +} + +/// Whether the deploy is asked for step by step: on a terminal, without `--yes` or a dry run. +/// Fails, never prompting, when nothing else says what to deploy. +fn guided( + arguments: &ModelDeployArgs, + format: OutputFormat, + condition: TerminalCondition, +) -> anyhow::Result { + let named = arguments.model.is_some(); + if arguments.yes || arguments.dry_run { + if !named { + anyhow::bail!("deploying needs a model; pass "); + } + return Ok(false); + } + match (format, condition, named) { + (OutputFormat::Yaml, _, true) => anyhow::bail!( + "deploying needs confirmation, which --yaml never asks for; pass --yes to deploy the \ + starting values" + ), + (OutputFormat::Yaml, _, false) => anyhow::bail!( + "deploying needs a model, which --yaml never asks for; pass with --yes" + ), + (_, TerminalCondition::NonInteractive, true) => anyhow::bail!( + "deploying needs a terminal to ask for each choice; pass --yes to deploy the starting \ + values" + ), + (_, TerminalCondition::NonInteractive, false) => anyhow::bail!( + "deploying needs a model; pass with --yes, or run in a terminal to choose one" + ), + (_, TerminalCondition::Interactive, _) => Ok(true), + } +} + +/// Prints the created deployment: its YAML document, or one line with its name, `name` when the +/// manager returned none, and its ID. +async fn report_deployed( + manager: &Manager, + deployment: ModelDeployment, + name: &str, + format: OutputFormat, +) -> anyhow::Result<()> { + if format == OutputFormat::Yaml { + let nodes = manager.node_names().await; + return write_yaml(&document(deployment, &nodes, false)); + } + present(&[Message::Success(format!( + "Deploying {} ({})", + if deployment.model_deployment_name.is_empty() { + name + } else { + &deployment.model_deployment_name + }, + deployment.model_deployment_id + ))]) +} + +/// The YAML document of a dry run: the request a deploy would send, with every choice resolved, +/// the values sizing derived, the estimate as returned and the preview's advisories. +#[derive(Serialize)] +struct DryRunDocument<'a> { + request: CreateModelDeploymentRequest, + + derived: Vec, + + estimate: &'a EstimateLocalModelResourcesResponse, + + advisories: Vec, +} + +/// Prints the dry run's report, failing when a launch would reject the values. +fn report_dry_run( + selection: &Selection, + payload: &ModelPayload, + estimate: EstimateLocalModelResourcesResponse, + format: OutputFormat, +) -> anyhow::Result<()> { + let derived = estimate + .hardware_class_estimates + .iter() + .flat_map(|entry| entry.derived_engine_parameter_values.iter()) + .flat_map(|values: &ParameterValues| values.values.iter()) + .map(|value| value.parameter_id.clone()) + .collect::>(); + let advisories = selection + .advisories + .iter() + .map(|advisory| advisory.as_str_name().to_owned()) + .collect::>(); + let rejection = rejected(&estimate); + + if format == OutputFormat::Yaml { + write_yaml(&DryRunDocument { + request: create_request(selection, payload)?, + derived, + estimate: &estimate, + advisories, + })?; + } else { + let mut messages = dry_run_messages(selection, &estimate, &advisories_words(selection)); + messages.extend(parameter_table(selection, payload)); + present(&messages)?; + } + match rejection { + Some(rejected) => anyhow::bail!("a launch would reject these values: {}", rejected.text), + None => Ok(()), + } +} + +/// The parameters an override can set, each with the value the deployment would take and what it +/// accepts. +fn parameter_table(selection: &Selection, payload: &ModelPayload) -> Vec { + let view = ParameterView::new( + &selection.model, + &selection.snapshot, + selection.compatibility.as_ref(), + ); + if view.parameters.is_empty() { + return Vec::new(); + } + let rows = view + .parameters + .iter() + .map(|parameter| { + let (key, set) = match parameter.key.split_once('.').filter(|_| parameter.option) { + Some((option, name)) => ( + format!("option.{}", parameter.key), + payload + .options + .get(option) + .and_then(|values| values.get(name)), + ), + None => ( + parameter.key.clone(), + payload.parameters.get(¶meter.key), + ), + }; + vec![ + key, + parameter_value(parameter, set), + parameter_accepts(parameter), + ] + }) + .collect(); + vec![ + Message::Heading("Parameters, set with --set =".to_owned()), + Message::Table { + header: vec![ + "Parameter".to_owned(), + "Value".to_owned(), + "Accepts".to_owned(), + ], + rows, + }, + ] +} + +/// The value a parameter would take: the override, else its starting value. +fn parameter_value(parameter: &ViewParameter, set: Option<&PlainValue>) -> String { + match set { + Some(PlainValue::Boolean(value)) => value.to_string(), + Some(PlainValue::Number(value)) => value.to_string(), + Some(PlainValue::Text(text)) => text.clone(), + None if parameter.secret => "secret".to_owned(), + None if parameter.follows => "follows".to_owned(), + None => parameter + .starting + .clone() + .unwrap_or_else(|| "unset".to_owned()), + } +} + +/// What a parameter accepts, marking the advanced ones. +fn parameter_accepts(parameter: &ViewParameter) -> String { + if parameter.advanced { + format!("{}, advanced", parameter.accepts) + } else { + parameter.accepts.clone() + } +} + +fn dry_run_messages( + selection: &Selection, + estimate: &EstimateLocalModelResourcesResponse, + advisories: &[&str], +) -> Vec { + use dotcore_proto::dotcore::deployment::v1::MemoryFit; + + let place = format!( + "{} ({}) on {} {}", + selection.model.display_name, + selection.profile.profile_id, + selection.node_name, + selection.target_name + ); + let mut messages = vec![match estimate + .placement_preview + .as_ref() + .map(|preview| preview.free_memory_fit()) + { + Some(MemoryFit::Fits) => Message::Success(format!("{place} fits now")), + Some(MemoryFit::Exceeds) => Message::Warning(format!("{place} exceeds the free memory")), + _ => Message::Info(format!("{place}: fit unknown")), + }]; + messages.extend(memory_block(estimate)); + messages.extend( + advisories + .iter() + .map(|advisory| Message::Warning((*advisory).to_owned())), + ); + messages +} diff --git a/backend/cli/src/model/estimate.rs b/backend/cli/src/model/estimate.rs new file mode 100644 index 00000000..3a40938f --- /dev/null +++ b/backend/cli/src/model/estimate.rs @@ -0,0 +1,70 @@ +//! Asks the server how one payload would fit its selected target, and words what fits. +//! +//! The estimate is the server's answer: memory per pool, bounds on the context values, the largest +//! value that fits for memory parameters and the values sizing derives. Every deploy path, the dry +//! run and the step-by-step prompts, reads it the same way and decides no fit itself. + +use std::collections::BTreeMap; + +use dotcore_proto::dotcore::model::v1::{ + EstimateLocalModelResourcesRequest, EstimateLocalModelResourcesResponse, +}; + +use super::{ + payload::{ModelPayload, PayloadError}, + selection::Selection, + site::DeploySite, +}; +use crate::{ + management::{DeploymentGroup, call_failed}, + terminal::FieldHint, +}; + +/// Has the server estimate the payload's configuration on the selected target. +pub(super) async fn estimate( + site: &dyn DeploySite, + selection: &Selection, + payload: &ModelPayload, +) -> anyhow::Result { + Ok(site + .estimate(estimate_request(selection, payload)?) + .await + .map_err(call_failed( + DeploymentGroup::Model, + format!("estimate the memory of {}", selection.model.display_name), + ))?) +} + +/// The request estimating the payload's configuration on the selected target. +pub(super) fn estimate_request( + selection: &Selection, + payload: &ModelPayload, +) -> Result { + Ok(EstimateLocalModelResourcesRequest { + model_id: selection.model.model_id.clone(), + profile_id: selection.profile.profile_id.clone(), + configuration: Some(payload.configuration(&selection.schema())?), + placement: Some(selection.placement.clone()), + }) +} + +/// What the estimate says fits for each parameter it bounds, by parameter ID: the value it +/// suggests and the words the dry run and the guided deploy show. +pub(super) fn fit_hints( + estimate: &EstimateLocalModelResourcesResponse, +) -> BTreeMap<&str, FieldHint> { + let hint = |words: String, value: String| FieldHint { + text: format!("{words}: {value}"), + value, + }; + estimate + .memory_parameter_fits + .iter() + .map(|fit| { + ( + fit.parameter_id.as_str(), + hint("Largest fit".to_owned(), fit.largest_fit.to_string()), + ) + }) + .collect() +} diff --git a/backend/cli/src/model/list.rs b/backend/cli/src/model/list.rs index 67e55e08..1b4a3422 100644 --- a/backend/cli/src/model/list.rs +++ b/backend/cli/src/model/list.rs @@ -1,20 +1,20 @@ //! Shows the model deployments of the running site with their state, node and model, for //! example one ready Gemma on a GPU node and one paused. //! -//! On a terminal it prints a table; without one it prints one record block per deployment on -//! stdout, each carrying the id, name, state, node and model. +//! It prints a table, on the terminal or as plain text without one. Asked for YAML, it prints the +//! deployments as the manager returns them, with secret values masked. use clap::Args; use dotcore_proto::dotcore::model::v1::ModelDeployment; use super::{ - node_of, + document, node_of, projection::{model_display_name, presentation_name, state_label}, }; use crate::{ - management::{ManagerArgs, NodeNames, list_deployments, single_line}, - node::write_records, - terminal::{Message, TerminalCondition, controlling_terminal_condition, open_terminal}, + management::{DeploymentListDocument, ManagerArgs, NodeNames, list_deployments, single_line}, + output::{OutputFormat, present, write_yaml}, + terminal::Message, }; /// Arguments for listing model deployments. @@ -24,27 +24,28 @@ pub struct ModelListArgs { manager: ManagerArgs, } -/// Lists the model deployments on the terminal, else as records. -pub(crate) async fn model_list(arguments: ModelListArgs) -> anyhow::Result<()> { +/// Lists the model deployments as YAML when asked, else as a table. +pub(crate) async fn model_list( + arguments: ModelListArgs, + format: OutputFormat, +) -> anyhow::Result<()> { let manager = arguments.manager.connect().await?; let deployments = list_deployments::(&manager).await?; let nodes = manager.node_names().await; - if controlling_terminal_condition() == TerminalCondition::Interactive { - let mut terminal = open_terminal(); - if deployments.is_empty() { - terminal.message(&Message::Info("No model deployments".to_owned()))?; - } else { - terminal.message(&table(&deployments, &nodes))?; - } - return Ok(()); + if format == OutputFormat::Yaml { + return write_yaml(&DeploymentListDocument::new( + deployments + .into_iter() + .map(|deployment| document(deployment, &nodes, false)) + .collect(), + )); } - let blocks = deployments - .iter() - .map(|deployment| record_block(deployment, &nodes)) - .collect::>(); - write_records(&blocks.join("\n")) + if deployments.is_empty() { + return present(&[Message::Info("No model deployments".to_owned())]); + } + present(&[table(&deployments, &nodes)]) } /// Builds the deployments table, header first. @@ -71,18 +72,6 @@ fn table(deployments: &[ModelDeployment], nodes: &NodeNames) -> Message { } } -/// Renders one deployment as a record block ending in a newline. -fn record_block(deployment: &ModelDeployment, nodes: &NodeNames) -> String { - format!( - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID={}\nDOTCORE_MODEL_DEPLOYMENT_NAME={}\nDOTCORE_MODEL_DEPLOYMENT_STATE={}\nDOTCORE_MODEL_DEPLOYMENT_NODE={}\nDOTCORE_MODEL_DEPLOYMENT_MODEL={}\n", - single_line(&deployment.model_deployment_id), - single_line(presentation_name(deployment)), - state_label(deployment), - single_line(node_of(deployment, nodes).unwrap_or("")), - single_line(model_display_name(deployment)), - ) -} - #[cfg(test)] mod tests { use dotcore_proto::dotcore::model::v1::ModelDeployment; diff --git a/backend/cli/src/model/memory.rs b/backend/cli/src/model/memory.rs new file mode 100644 index 00000000..76b59df6 --- /dev/null +++ b/backend/cli/src/model/memory.rs @@ -0,0 +1,493 @@ +//! The memory block of a deployment estimate: how full each memory pool of the target would be, +//! and what the server says fits. +//! +//! Each pool the target draws from becomes one bar: what already occupies it, this deployment's +//! demand and the fit line, with the server's verdict and, past the line, by how much. The largest +//! fits and the values sizing derived follow. Every number comes from the estimate; nothing is +//! computed here beyond adding up a pool's segments. + +use dotcore_catalog::typed_parameters::canonical_text; +use dotcore_proto::dotcore::{ + capacity::v1::{MemoryPoolKind, MemoryPoolPreview, MemorySegmentSource}, + deployment::v1::MemoryFit, + model::v1::EstimateLocalModelResourcesResponse, +}; + +use super::{ + context::{bound, overcommit_warning, rejected}, + view::{CONTEXT_PER_REQUEST, TOTAL_CONTEXT}, +}; +use crate::{ + hardware::gib, + terminal::{BarChart, BarFill, BarRow, BarSegment, BarTone, Message}, +}; + +/// The estimate's overall verdict on one line. +pub(super) fn verdict(estimate: &EstimateLocalModelResourcesResponse) -> Message { + match estimate + .placement_preview + .as_ref() + .map(|preview| preview.free_memory_fit()) + { + Some(MemoryFit::Fits) => Message::Success("Memory: fits now".to_owned()), + Some(MemoryFit::Exceeds) => Message::Warning("Memory: exceeds the free memory".to_owned()), + _ => Message::Info("Memory: fit unknown".to_owned()), + } +} + +/// The pools' bars, then the context bounds, the largest fits and the derived values, then the +/// overcommit warning. +pub(super) fn memory_block(estimate: &EstimateLocalModelResourcesResponse) -> Vec { + let mut messages = Vec::new(); + let pools = estimate + .placement_preview + .as_ref() + .map_or(&[][..], |preview| &preview.pools); + if !pools.is_empty() { + messages.push(Message::Bars(BarChart { + rows: pools.iter().map(pool_row).collect(), + legend: vec![ + (BarFill::Used, "in use".to_owned()), + (BarFill::Added, "this deployment".to_owned()), + ], + marker_legend: Some("fit line".to_owned()), + })); + } + if let Some(facts) = fit_facts(estimate) { + messages.push(facts); + } + messages.extend(overcommit_warning(estimate).map(Message::Warning)); + messages +} + +/// The footer of a guided deploy: one bar per memory pool, then the verdict, or a launch +/// rejection in its place, then the overcommit warning. +pub(super) fn footer_lines(estimate: &EstimateLocalModelResourcesResponse) -> Vec { + let mut lines = Vec::new(); + let pools = estimate + .placement_preview + .as_ref() + .map_or(&[][..], |preview| &preview.pools); + if !pools.is_empty() { + lines.push(Message::Bars(BarChart { + rows: pools.iter().map(pool_row).collect(), + legend: Vec::new(), + marker_legend: None, + })); + } + if let Some(rejected) = rejected(estimate) { + lines.push(Message::Error(format!( + "A launch would reject these values: {}", + rejected.text + ))); + return lines; + } + + lines.push(verdict(estimate)); + lines.extend(overcommit_warning(estimate).map(Message::Warning)); + lines +} + +/// The memory the deployment was estimated to take on `machine`, on one line: each pool's use +/// against its total, with the verdict's tone. +pub(super) fn memory_line( + estimate: &EstimateLocalModelResourcesResponse, + machine: &str, +) -> Message { + let pools = estimate + .placement_preview + .as_ref() + .map_or(&[][..], |preview| &preview.pools); + let notes = pools + .iter() + .map(|pool| { + let row = pool_row(pool); + format!("{} {}", row.label, row.note) + }) + .collect::>(); + let text = if notes.is_empty() { + format!("Memory on {machine}: fit unknown") + } else { + format!("Memory on {machine}: {}", notes.join(" · ")) + }; + match verdict(estimate) { + Message::Success(_) => Message::Success(text), + Message::Warning(_) => Message::Warning(text), + _ => Message::Info(text), + } +} + +/// One pool's bar: other use, then this deployment's demand, against its total and fit line. +fn pool_row(preview: &MemoryPoolPreview) -> BarRow { + let pool = preview.pool.clone().unwrap_or_default(); + let label = match pool.kind() { + MemoryPoolKind::Device => { + let mut label = pool + .device_index + .map_or_else(|| "GPU".to_owned(), |index| format!("GPU {index}")); + if !pool.device_name.is_empty() { + label.push(' '); + label.push_str(&pool.device_name); + } + label + } + MemoryPoolKind::Host => "Host memory".to_owned(), + MemoryPoolKind::Unspecified => "Memory".to_owned(), + }; + + let (demand, used) = pool + .segments + .iter() + .fold((0, 0), |(demand, used), segment| { + if segment.source() == MemorySegmentSource::Previewed { + (demand + segment.bytes, used) + } else { + (demand, used + segment.bytes) + } + }); + let drawn = match pool.total_bytes { + Some(total) => format!("{} of {}", gib(used + demand), gib(total)), + None => format!("{} in use, total unknown", gib(used + demand)), + }; + let (verdict, tone) = match preview.free_memory_fit() { + MemoryFit::Fits => ("fits".to_owned(), BarTone::Good), + MemoryFit::Exceeds if preview.beyond_total => ( + format!("over the total by {}", gib(preview.over_by_bytes)), + BarTone::Bad, + ), + MemoryFit::Exceeds => ( + format!("over the fit line by {}", gib(preview.over_by_bytes)), + BarTone::Bad, + ), + MemoryFit::Unknown | MemoryFit::Unspecified => ("fit unknown".to_owned(), BarTone::Neutral), + }; + + BarRow { + label, + segments: vec![ + BarSegment { + fill: BarFill::Used, + amount: used, + }, + BarSegment { + fill: BarFill::Added, + amount: demand, + }, + ], + capacity: pool.total_bytes, + marker: preview.fit_line_bytes, + note: format!("{drawn} · {verdict}"), + tone, + } +} + +/// The largest values that fit and the values sizing derived, as aligned facts; none when the +/// estimate gives neither. +pub(super) fn fit_facts(estimate: &EstimateLocalModelResourcesResponse) -> Option { + let mut facts = Vec::new(); + for (key, label) in [ + (TOTAL_CONTEXT, "Total context up to"), + (CONTEXT_PER_REQUEST, "Context per request up to"), + ] { + if let Some((tokens, reason)) = bound(estimate, key) { + facts.push((label.to_owned(), format!("{tokens}, {reason}"))); + } + } + for fit in &estimate.memory_parameter_fits { + facts.push(( + format!("Largest {}", fit.parameter_id), + fit.largest_fit.to_string(), + )); + } + for value in estimate + .hardware_class_estimates + .iter() + .flat_map(|entry| entry.derived_engine_parameter_values.iter()) + .flat_map(|values| values.values.iter()) + { + if let Some(text) = value.value.as_ref().map(canonical_text) { + facts.push((format!("Derived {}", value.parameter_id), text)); + } + } + (!facts.is_empty()).then_some(Message::KeyValues(facts)) +} + +#[cfg(test)] +mod tests { + use dotcore_proto::dotcore::{ + capacity::v1::{MemoryPool, MemorySegment, PlacementPreview}, + catalog::v1::{ParameterValue, ParameterValues, parameter_value}, + model::v1::{ + ContextBound, ContextBoundReason, HardwareClassResourceEstimate, LaunchRejection, + LaunchRejectionReason, + }, + }; + + use super::*; + + const GIB: u64 = 1 << 30; + + #[test] + fn a_fitting_estimate_draws_its_pools_with_the_largest_fits() { + let estimate = estimate( + MemoryFit::Fits, + vec![ + pool(MemoryPoolKind::Device, 6, 6, MemoryFit::Fits, 0, false), + pool(MemoryPoolKind::Host, 8, 0, MemoryFit::Fits, 0, false), + ], + ); + + let block = memory_block(&estimate); + + assert_eq!(verdict(&estimate).plain_lines(), ["✔ Memory: fits now"]); + assert_eq!( + lines(&block), + [ + " GPU 0 RTX ██████▓▓▓▓▓▓░░░░░│░░░░░░░ 12.0 GiB of 24.0 GiB · fits", + " Host memory ████████░░░░░░░░│░░░░░░░░ 8.0 GiB of 24.0 GiB · fits", + " █ in use ▓ this deployment │ fit line", + " Total context up to 196608, the largest that fits", + " Derived total-context 131072", + ] + ); + } + + #[test] + fn an_exceeding_estimate_says_by_how_much_each_pool_is_over() { + let estimate = estimate( + MemoryFit::Exceeds, + vec![ + pool(MemoryPoolKind::Device, 6, 16, MemoryFit::Exceeds, 2, false), + pool(MemoryPoolKind::Host, 20, 8, MemoryFit::Exceeds, 4, true), + ], + ); + + let block = memory_block(&estimate); + + assert_eq!( + verdict(&estimate).ascii_lines(), + ["! Memory: exceeds the free memory"] + ); + assert_eq!( + ascii_lines(&block)[..3], + [ + " GPU 0 RTX ######+++++++++++|+++++.. 22.0 GiB of 24.0 GiB · over the fit line by 2.0 GiB", + " Host memory ##############|###+++++++ 28.0 GiB of 24.0 GiB · over the total by 4.0 GiB", + " # in use + this deployment | fit line", + ] + ); + assert_eq!( + ascii_lines(&block)[3], + " Total context up to 196608, the largest that fits" + ); + } + + #[test] + fn without_a_demand_the_fit_is_unknown() { + let estimate = EstimateLocalModelResourcesResponse { + placement_preview: Some(PlacementPreview { + pools: vec![pool( + MemoryPoolKind::Device, + 6, + 0, + MemoryFit::Unknown, + 0, + false, + )], + free_memory_fit: MemoryFit::Unknown.into(), + ..PlacementPreview::default() + }), + ..EstimateLocalModelResourcesResponse::default() + }; + + let block = memory_block(&estimate); + + assert_eq!(verdict(&estimate).plain_lines(), ["Memory: fit unknown"]); + assert_eq!( + lines(&block), + [ + " GPU 0 RTX ██████░░░░░░░░░░░│░░░░░░░ 6.0 GiB of 24.0 GiB · fit unknown", + " █ in use ▓ this deployment │ fit line", + ] + ); + assert_eq!( + ascii_lines(&block), + [ + " GPU 0 RTX ######...........|....... 6.0 GiB of 24.0 GiB · fit unknown", + " # in use + this deployment | fit line", + ] + ); + assert_eq!( + memory_block(&EstimateLocalModelResourcesResponse::default()), + [] + ); + } + + #[test] + fn the_footer_draws_a_bar_per_pool_then_the_verdict() { + let fits = estimate( + MemoryFit::Fits, + vec![ + pool(MemoryPoolKind::Device, 6, 6, MemoryFit::Fits, 0, false), + pool(MemoryPoolKind::Device, 2, 6, MemoryFit::Fits, 0, false), + ], + ); + let exceeds = estimate( + MemoryFit::Exceeds, + vec![pool( + MemoryPoolKind::Device, + 6, + 16, + MemoryFit::Exceeds, + 2, + false, + )], + ); + + assert_eq!( + lines(&footer_lines(&fits)), + [ + " GPU 0 RTX ██████▓▓▓▓▓▓░░░░░│░░░░░░░ 12.0 GiB of 24.0 GiB · fits", + " GPU 0 RTX ██▓▓▓▓▓▓░░░░░░░░░│░░░░░░░ 8.0 GiB of 24.0 GiB · fits", + "✔ Memory: fits now", + ] + ); + assert_eq!( + lines(&footer_lines(&exceeds)), + [ + " GPU 0 RTX ██████▓▓▓▓▓▓▓▓▓▓▓│▓▓▓▓▓░░ 22.0 GiB of 24.0 GiB · over the fit line by 2.0 GiB", + "! Memory: exceeds the free memory", + ] + ); + assert_eq!( + lines(&footer_lines( + &EstimateLocalModelResourcesResponse::default() + )), + ["Memory: fit unknown"] + ); + } + + #[test] + fn a_launch_rejection_takes_the_place_of_the_verdict() { + let mut rejected = estimate( + MemoryFit::Fits, + vec![pool(MemoryPoolKind::Host, 8, 0, MemoryFit::Fits, 0, false)], + ); + rejected.hardware_class_estimates[0].launch_rejection = Some(LaunchRejection { + parameter_id: "context-per-request".to_owned(), + reason: LaunchRejectionReason::AboveTotalContext as i32, + value: 65_536, + limit: 32_768, + }); + + assert_eq!( + lines(&footer_lines(&rejected)), + [ + " Host memory ████████░░░░░░░░│░░░░░░░░ 8.0 GiB of 24.0 GiB · fits", + "✘ A launch would reject these values: Context per request of 65536 tokens is above the 32768 \ + tokens one request can use of the total context; lower the context per request or \ + raise the total context", + ] + ); + } + + #[test] + fn the_memory_line_states_each_pool_on_the_machine_with_the_verdict() { + let fits = estimate( + MemoryFit::Fits, + vec![ + pool(MemoryPoolKind::Device, 6, 6, MemoryFit::Fits, 0, false), + pool(MemoryPoolKind::Host, 8, 0, MemoryFit::Fits, 0, false), + ], + ); + + assert_eq!( + memory_line(&fits, "gpu1 CUDA").plain_lines(), + [ + "✔ Memory on gpu1 CUDA: GPU 0 RTX 12.0 GiB of 24.0 GiB · fits · Host memory 8.0 GiB of 24.0 GiB · fits" + ] + ); + assert_eq!( + memory_line(&EstimateLocalModelResourcesResponse::default(), "gpu1 CUDA").plain_lines(), + ["Memory on gpu1 CUDA: fit unknown"] + ); + } + + fn lines(block: &[Message]) -> Vec { + block.iter().flat_map(Message::plain_lines).collect() + } + + fn ascii_lines(block: &[Message]) -> Vec { + block.iter().flat_map(Message::ascii_lines).collect() + } + + fn estimate( + fit: MemoryFit, + pools: Vec, + ) -> EstimateLocalModelResourcesResponse { + EstimateLocalModelResourcesResponse { + placement_preview: Some(PlacementPreview { + pools, + free_memory_fit: fit.into(), + ..PlacementPreview::default() + }), + hardware_class_estimates: vec![HardwareClassResourceEstimate { + derived_engine_parameter_values: Some(ParameterValues { + values: vec![ParameterValue { + parameter_id: "total-context".to_owned(), + value: Some(parameter_value::Value::UnsignedInteger(131_072)), + }], + }), + ..HardwareClassResourceEstimate::default() + }], + total_context_bound: Some(ContextBound { + tokens: 196_608, + reason: ContextBoundReason::LargestFit.into(), + }), + ..EstimateLocalModelResourcesResponse::default() + } + } + + /// A 24 GiB pool with a 17 GiB fit line holding `used` GiB of other use and `demand` GiB of + /// the previewed deployment. + fn pool( + kind: MemoryPoolKind, + used: u64, + demand: u64, + fit: MemoryFit, + over_by: u64, + beyond_total: bool, + ) -> MemoryPoolPreview { + let mut segments = vec![MemorySegment { + source: MemorySegmentSource::Other.into(), + bytes: used * GIB, + ..MemorySegment::default() + }]; + if demand > 0 { + segments.push(MemorySegment { + source: MemorySegmentSource::Previewed.into(), + bytes: demand * GIB, + ..MemorySegment::default() + }); + } + let device = kind == MemoryPoolKind::Device; + MemoryPoolPreview { + pool: Some(MemoryPool { + kind: kind.into(), + device_name: if device { + "RTX".to_owned() + } else { + String::new() + }, + device_index: device.then_some(0), + total_bytes: Some(24 * GIB), + segments, + ..MemoryPool::default() + }), + fit_line_bytes: Some(if device { 17 * GIB } else { 16 * GIB }), + free_memory_fit: fit.into(), + over_by_bytes: over_by * GIB, + beyond_total, + } + } +} diff --git a/backend/cli/src/model/mod.rs b/backend/cli/src/model/mod.rs index 5422de4d..ead77770 100644 --- a/backend/cli/src/model/mod.rs +++ b/backend/cli/src/model/mod.rs @@ -3,13 +3,24 @@ //! //! Deployments are named by id or name and shown with the same state words as the web console, //! for example "Pausing" for a deployment asked to pause whose workload still runs. On a -//! terminal the commands print tables and messages; without one they print result records on -//! stdout, for example `DOTCORE_MODEL_DEPLOYMENT_STATE=Ready`. +//! terminal the commands print tables and messages, and as plain text without one. Asked for YAML, +//! every command prints the +//! manager's own message instead. +mod catalog; +mod context; +mod deploy; +mod estimate; mod list; +mod memory; mod parameters; +mod payload; mod projection; +mod selection; mod show; +mod site; +mod view; +mod wizard; use clap::{Args, Subcommand}; use dotcore_proto::dotcore::{ @@ -24,13 +35,18 @@ use dotcore_proto::dotcore::{ use futures_util::StreamExt; use tonic::Status; -use crate::management::{ - DeploymentGroup, Lifecycle, LogEntry, LogEvent, LogEvents, LogPage, LogPosition, LogSource, - LogSourceState, LoggedDeployment, LogsArgs, ManagedDeployment, Manager, ManagerArgs, NodeNames, - change_lifecycle, deployment_logs, teardown, +use crate::{ + management::{ + DeploymentDocument, DeploymentGroup, Lifecycle, LogEntry, LogEvent, LogEvents, LogPage, + LogPosition, LogSource, LogSourceState, LoggedDeployment, LogsArgs, ManagedDeployment, + Manager, ManagerArgs, NodeNames, change_lifecycle, deployment_logs, teardown, + }, + output::OutputFormat, }; +use catalog::{ModelCatalogArgs, model_catalog}; +use deploy::{ModelDeployArgs, model_deploy}; use list::{ModelListArgs, model_list}; -use projection::{desired_state_label, state_label}; +use projection::desired_state_label; use show::{ModelShowArgs, model_show}; /// Commands that manage the model deployments of a running site. @@ -44,39 +60,56 @@ pub struct ModelCommand { /// Actions supported by the model command group. #[derive(Debug, Subcommand)] enum ModelSubcommand { - /// List the model deployments with their state, node and model; runs against the running - /// site manager (`--manager`). + /// List the model deployments with their state and node + /// + /// Runs against the running site manager. #[command(alias = "ls")] List(ModelListArgs), - /// Show one model deployment by name or id. + /// Show one model deployment by name or ID Show(ModelShowArgs), - /// Ask the manager to pause a model deployment; returns without waiting for the pause. + /// List the catalog models you can deploy, with whether each profile fits each target + Catalog(ModelCatalogArgs), + + /// Deploy a catalog model step by step on a terminal, or from its starting values and `--set` + /// + /// Without `--yes`, a terminal asks for each choice and shows the memory estimate. `--dry-run` + /// estimates the deployment, lists every parameter it can set and reports whether it fits, + /// without creating it. + Deploy(ModelDeployArgs), + + /// Pause a model deployment, without waiting for it to pause Pause(LifecycleArgs), - /// Ask the manager to resume a paused model deployment; returns without waiting. + /// Resume a paused model deployment, without waiting for it to resume Resume(LifecycleArgs), - /// Remove a model deployment and its running workload resources after confirmation. + /// Remove a model deployment and its workload after confirmation Teardown(ModelTeardownArgs), - /// Print the most recent log lines of a model deployment, on any node, and follow new ones - /// with --follow; lines go to stdout and source states to stderr. + /// Print the recent log lines of a model deployment + /// + /// Reads from any node. With `--follow`, keeps printing new lines. Lines go to stdout and + /// source states to stderr. + #[command(mut_arg("reference", |argument| argument.help("Name or ID of the model deployment")))] Logs(LogsArgs), } impl ModelCommand { /// Runs the chosen action. - pub(crate) async fn dispatch(self) -> anyhow::Result<()> { + pub(crate) async fn dispatch(self, format: OutputFormat) -> anyhow::Result<()> { match self.command { - Some(ModelSubcommand::List(arguments)) => model_list(arguments).await, - Some(ModelSubcommand::Show(arguments)) => model_show(arguments).await, + Some(ModelSubcommand::List(arguments)) => model_list(arguments, format).await, + Some(ModelSubcommand::Show(arguments)) => model_show(arguments, format).await, + Some(ModelSubcommand::Catalog(arguments)) => model_catalog(arguments, format).await, + Some(ModelSubcommand::Deploy(arguments)) => model_deploy(arguments, format).await, Some(ModelSubcommand::Pause(arguments)) => { change_lifecycle::( &arguments.manager, &arguments.reference, Lifecycle::Pause, + format, ) .await } @@ -85,15 +118,21 @@ impl ModelCommand { &arguments.manager, &arguments.reference, Lifecycle::Resume, + format, ) .await } Some(ModelSubcommand::Teardown(arguments)) => { - teardown::(&arguments.manager, &arguments.reference, arguments.yes) - .await + teardown::( + &arguments.manager, + &arguments.reference, + arguments.yes, + format, + ) + .await } Some(ModelSubcommand::Logs(arguments)) => { - deployment_logs::(arguments).await + deployment_logs::(arguments, format).await } None => anyhow::bail!("model command requires an action"), } @@ -108,7 +147,7 @@ impl ModelCommand { /// Arguments selecting the model deployment to pause or resume. #[derive(Debug, Args)] struct LifecycleArgs { - /// Name or id of the model deployment. + /// Name or ID of the model deployment. #[arg(value_name = "DEPLOYMENT")] reference: String, @@ -119,7 +158,7 @@ struct LifecycleArgs { /// Arguments selecting the model deployment to tear down. #[derive(Debug, Args)] struct ModelTeardownArgs { - /// Name or id of the model deployment. + /// Name or ID of the model deployment. #[arg(value_name = "DEPLOYMENT")] reference: String, @@ -170,6 +209,12 @@ impl ManagedDeployment for ModelDeployment { } } + fn placement(&self) -> Option<&ExactPlacement> { + self.intent + .as_ref() + .and_then(|intent| intent.placement.as_ref()) + } + fn accepts(&self, lifecycle: Lifecycle) -> bool { self.desired_state() == match lifecycle { @@ -179,26 +224,28 @@ impl ManagedDeployment for ModelDeployment { } } - fn state_label(&self) -> &'static str { - state_label(self) - } - fn desired_state_label(&self) -> &'static str { desired_state_label(self.desired_state()) } + fn mask_secrets(&mut self) { + parameters::mask_secrets(self); + } + fn teardown_consequence(&self) -> String { "This removes the deployment and its running workload resources.".to_owned() } } impl LoggedDeployment for ModelDeployment { + type Entry = DeploymentLogEntry; + async fn read_logs( manager: &Manager, id: String, sources: Vec, page_size: u32, - ) -> Result { + ) -> Result, Status> { let page = manager .models() .read_deployment_logs(ReadDeploymentLogsRequest { @@ -236,7 +283,7 @@ impl LoggedDeployment for ModelDeployment { id: String, sources: Vec, positions: Vec, - ) -> Result { + ) -> Result, Status> { let events = manager .models() .follow_deployment_logs(FollowDeploymentLogsRequest { @@ -285,26 +332,33 @@ fn log_source(name: String, label: String, state: DeploymentLogSourceState) -> L } } -fn log_entry(entry: DeploymentLogEntry) -> LogEntry { +fn log_entry(entry: DeploymentLogEntry) -> LogEntry { LogEntry { - source_name: entry.source_name, - source_label: entry.source_label, + source_name: entry.source_name.clone(), + source_label: entry.source_label.clone(), timestamp: entry.timestamp, - content: entry.content, + content: entry.content.clone(), truncated: entry.truncated, + message: entry, } } /// Where a deployment runs: the node's name (its id when unnamed), or `None` for an upstream /// deployment, which has no placement. fn node_of<'a>(deployment: &'a ModelDeployment, nodes: &'a NodeNames) -> Option<&'a str> { - placement(deployment).map(|placement| nodes.display(&placement.site_node_id)) + deployment + .placement() + .map(|placement| nodes.display(&placement.site_node_id)) } -/// The exact placement of a local deployment. -fn placement(deployment: &ModelDeployment) -> Option<&ExactPlacement> { - deployment - .intent - .as_ref() - .and_then(|intent| intent.placement.as_ref()) +/// The YAML document of a deployment, with its secret values masked unless revealed. +fn document( + mut deployment: ModelDeployment, + nodes: &NodeNames, + reveal_secrets: bool, +) -> DeploymentDocument { + if !reveal_secrets { + parameters::mask_secrets(&mut deployment); + } + DeploymentDocument::new(deployment, nodes) } diff --git a/backend/cli/src/model/parameters.rs b/backend/cli/src/model/parameters.rs index 195aba9b..1f219f1f 100644 --- a/backend/cli/src/model/parameters.rs +++ b/backend/cli/src/model/parameters.rs @@ -1,18 +1,20 @@ //! The engine parameters of one model deployment, as rows an operator can read. -use dotcore_catalog::typed_parameters::default_value; +use dotcore_catalog::typed_parameters::{default_value, is_secret}; use dotcore_proto::dotcore::{ - catalog::v1::{ParameterDefinition, ParameterVisibility}, + catalog::v1::{ParameterDefinition, ParameterVisibility, parameter_value}, model::v1::{ - ModelDeployment, ResolvedLocalModelDeploymentSnapshot, UpstreamModelDesiredConfiguration, - model_deployment_snapshot, + ModelDeployment, PortableModelLaunchPlan, ResolvedLocalModelDeploymentSnapshot, + UpstreamModelDesiredConfiguration, model_deployment_snapshot, + portable_model_launch_argument_token, }, }; -use crate::parameters::{ParameterInput, ParameterRow, retained, secret_row}; +use crate::parameters::{ + ParameterInput, ParameterRow, SECRET_MASK, mask_secret_values, masked, retained, secret_row, +}; const UPSTREAM_API_KEY_NAME: &str = "API key"; -const UPSTREAM_API_KEY_ID: &str = "api-key"; /// The deployment's parameters in engine schema order. Hidden parameters, by the profile's /// visibility override else the engine's, are left out as in the console; a parameter without a @@ -64,6 +66,92 @@ pub(super) fn rows(deployment: &ModelDeployment, reveal_secrets: bool) -> Vec Vec { + let mut secrets = [ + local.engine_parameter_values.as_ref(), + local.profile_engine_parameter_defaults.as_ref(), + ] + .into_iter() + .flatten() + .flat_map(|values| &values.values) + .filter(|value| { + definitions.iter().any(|definition| { + definition.parameter_id == value.parameter_id && is_secret(definition) + }) + }) + .filter_map(|value| match &value.value { + Some(parameter_value::Value::String(text)) if !text.is_empty() => Some(text.clone()), + _ => None, + }) + .collect::>(); + secrets.sort_by_key(|text| std::cmp::Reverse(text.len())); + secrets.dedup(); + secrets +} + +/// Masks each of `secrets` inside the launch plan's literal arguments and the custom argument +/// tokens, where an engine receives a secret parameter as part of a command line argument. +fn mask_launch_arguments( + plan: &mut Option, + custom_tokens: &mut [String], + secrets: &[String], +) { + if secrets.is_empty() { + return; + } + let mask = |text: &mut String| { + for secret in secrets { + *text = text.replace(secret.as_str(), SECRET_MASK); + } + }; + for token in plan.iter_mut().flat_map(|plan| &mut plan.arguments) { + if let Some(portable_model_launch_argument_token::Value::Literal(literal)) = + token.value.as_mut() + { + mask(literal); + } + } + custom_tokens.iter_mut().for_each(mask); +} + /// The visibility a parameter shows with: the profile's override when it has one, else the /// engine's own visibility. fn effective_visibility( @@ -85,10 +173,122 @@ fn upstream_api_key( .map(|configuration| configuration.api_key.as_str()) .filter(|key| !key.is_empty())?; - Some(secret_row( - UPSTREAM_API_KEY_ID, - UPSTREAM_API_KEY_NAME, - key, - reveal_secrets, - )) + Some(secret_row(UPSTREAM_API_KEY_NAME, key, reveal_secrets)) +} + +#[cfg(test)] +mod tests { + use dotcore_proto::dotcore::{ + catalog::v1::{ + EngineParameterSchema, ParameterValue, ParameterValues, SecretParameterSchema, + parameter_definition::ParameterType, + }, + model::v1::{ + ModelDeploymentSnapshot, PortableModelLaunchArgumentToken, PortableModelLaunchPlan, + }, + }; + + use super::*; + + fn literal(text: &str) -> PortableModelLaunchArgumentToken { + PortableModelLaunchArgumentToken { + value: Some(portable_model_launch_argument_token::Value::Literal( + text.to_owned(), + )), + } + } + + fn secret_parameter() -> ParameterValue { + ParameterValue { + parameter_id: "api-key".to_owned(), + value: Some(parameter_value::Value::String("s3cr3t-value".to_owned())), + } + } + + #[test] + fn a_secret_value_is_masked_in_launch_arguments_and_custom_tokens() { + let local = ResolvedLocalModelDeploymentSnapshot { + engine_parameter_schema: Some(EngineParameterSchema { + parameters: vec![ParameterDefinition { + parameter_id: "api-key".to_owned(), + parameter_type: Some(ParameterType::Secret(SecretParameterSchema { + generated_length: 16, + minimum_length: 1, + maximum_length: None, + })), + ..Default::default() + }], + ..Default::default() + }), + engine_parameter_values: Some(ParameterValues { + values: vec![ + secret_parameter(), + ParameterValue { + parameter_id: "threads".to_owned(), + value: Some(parameter_value::Value::UnsignedInteger(4)), + }, + ], + }), + desired_launch_plan: Some(PortableModelLaunchPlan { + arguments: vec![ + literal("--api-key"), + literal("s3cr3t-value"), + literal("--header=Bearer s3cr3t-value"), + PortableModelLaunchArgumentToken { + value: Some(portable_model_launch_argument_token::Value::ServiceHost( + "s3cr3t-value".to_owned(), + )), + }, + ], + ..Default::default() + }), + custom_argument_tokens: vec!["--key=s3cr3t-value".to_owned(), "--verbose".to_owned()], + ..Default::default() + }; + let mut deployment = ModelDeployment { + snapshot: Some(ModelDeploymentSnapshot { + source: Some(model_deployment_snapshot::Source::Local(local)), + }), + ..Default::default() + }; + + mask_secrets(&mut deployment); + + let Some(model_deployment_snapshot::Source::Local(local)) = + deployment.snapshot.and_then(|snapshot| snapshot.source) + else { + panic!("local snapshot"); + }; + let literals = local + .desired_launch_plan + .expect("plan") + .arguments + .into_iter() + .map(|token| token.value.expect("token")) + .collect::>(); + assert_eq!( + literals, + [ + portable_model_launch_argument_token::Value::Literal("--api-key".to_owned()), + portable_model_launch_argument_token::Value::Literal("********".to_owned()), + portable_model_launch_argument_token::Value::Literal( + "--header=Bearer ********".to_owned() + ), + portable_model_launch_argument_token::Value::ServiceHost("s3cr3t-value".to_owned()), + ] + ); + assert_eq!( + local.custom_argument_tokens, + ["--key=********", "--verbose"] + ); + let values = local.engine_parameter_values.expect("values").values; + assert_eq!( + values[0].value, + Some(parameter_value::Value::String("********".to_owned())) + ); + assert_eq!( + values[1].value, + Some(parameter_value::Value::UnsignedInteger(4)) + ); + } } diff --git a/backend/cli/src/model/payload.rs b/backend/cli/src/model/payload.rs new file mode 100644 index 00000000..c6fd6fc9 --- /dev/null +++ b/backend/cli/src/model/payload.rs @@ -0,0 +1,531 @@ +//! The deploy payload of one local model: what to deploy, where, under which name and route, and +//! the parameter and option values to change. +//! +//! Every way of deploying builds this payload, from flags or step by step, and sends the request +//! it becomes. It lists only the values it changes: the server fills everything left out from the +//! profile's defaults and catalog sizing, and validates the result. Values get their parameter's +//! type here, so an unknown or mistyped value fails before anything is sent. + +use std::collections::BTreeMap; + +use crate::deploy::{PlainValue, Setting, TypedValue, ValueError, ValueKind}; +use dotcore_proto::dotcore::{ + catalog::v1::{ + ModelConfigurationOption, ModelOptionParameterDefinition, ModelOptionParameterValue, + ModelOptionValues, ParameterDefinition, ParameterValue, ParameterValues, + model_option_parameter_definition, model_option_parameter_value, parameter_definition, + parameter_value, + }, + model::v1::{ + DirectRouteExposure, HiddenDeploymentExposure, LocalModelDeploymentConfiguration, + ModelDeploymentExposure, model_deployment_exposure, + }, +}; + +/// The `--set` prefix that addresses an option parameter rather than an engine parameter. +const OPTION_PREFIX: &str = "option."; + +/// One local model deployment as a payload describes it. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub(super) struct ModelPayload { + /// Catalog model reference. + pub(super) model: String, + + /// Profile ID; the first that fits the target when left out. + pub(super) profile: Option, + + /// Node reference; the first node that fits when left out. + pub(super) node: Option, + + /// Execution target ID on the node; needed only when the node has several. + pub(super) target: Option, + + /// Display name of the deployment. + pub(super) name: Option, + + /// Name of the route created with the deployment; none keeps it hidden. + pub(super) route: Option, + + /// Engine parameter values by parameter ID. + pub(super) parameters: BTreeMap, + + /// Option parameter values by option ID, then option parameter ID. + pub(super) options: BTreeMap>, + + /// Engine arguments appended to the launch as is. + pub(super) custom_arguments: Vec, +} + +impl ModelPayload { + /// Applies `--set` overrides in order: `option..` sets an option + /// parameter, any other key an engine parameter. + pub(super) fn apply(&mut self, settings: &[Setting]) -> Result<(), PayloadError> { + for setting in settings { + match setting.key.strip_prefix(OPTION_PREFIX) { + Some(rest) => { + let (option, parameter) = rest + .split_once('.') + .filter(|(option, parameter)| !option.is_empty() && !parameter.is_empty()) + .ok_or_else(|| PayloadError::OptionKey(setting.key.clone()))?; + self.options + .entry(option.to_owned()) + .or_default() + .insert(parameter.to_owned(), setting.value.clone()); + } + None => { + self.parameters + .insert(setting.key.clone(), setting.value.clone()); + } + } + } + Ok(()) + } + + /// The configuration the payload asks for, typed by the profile's schema. Values it leaves out + /// stay out, for the server to fill. + pub(super) fn configuration( + &self, + schema: &ParameterSchema<'_>, + ) -> Result { + let values = self + .parameters + .iter() + .map(|(id, value)| engine_value(schema.parameters, id, value)) + .collect::, _>>()?; + let option_overrides = self + .options + .iter() + .map(|(id, values)| option_values(schema.options, id, values)) + .collect::, _>>()?; + Ok(LocalModelDeploymentConfiguration { + model_artifact_binding_id: String::new(), + engine_parameter_values: (!values.is_empty()).then_some(ParameterValues { values }), + custom_argument_tokens: self.custom_arguments.clone(), + option_overrides, + }) + } + + /// The route the deployment is created with: a route of the payload's name, or none. + pub(super) fn exposure(&self) -> ModelDeploymentExposure { + ModelDeploymentExposure { + kind: Some(match &self.route { + Some(route_name) => model_deployment_exposure::Kind::Direct(DirectRouteExposure { + route_name: route_name.clone(), + }), + None => model_deployment_exposure::Kind::Hidden(HiddenDeploymentExposure {}), + }), + } + } +} + +/// The parameters a payload's values are typed against: the profile's engine parameters and its +/// configuration's options. +pub(super) struct ParameterSchema<'a> { + /// Engine parameters of the profile's engine configuration. + pub(super) parameters: &'a [ParameterDefinition], + + /// Options of the profile's engine configuration. + pub(super) options: &'a [ModelConfigurationOption], +} + +/// Why a payload can't become a deployment request. +#[derive(Debug, thiserror::Error)] +pub(super) enum PayloadError { + /// An option override doesn't name an option and one of its parameters. + #[error("option override {0:?} must be option..")] + OptionKey(String), + + /// The profile has no engine parameter with this ID. + #[error("unknown parameter {id:?}; this profile's parameters are: {known}")] + UnknownParameter { id: String, known: String }, + + /// The configuration has no option with this ID. + #[error("unknown option {id:?}; this profile's options are: {known}")] + UnknownOption { id: String, known: String }, + + /// The option has no parameter with this ID. + #[error("unknown parameter {id:?} of option {option:?}; its parameters are: {known}")] + UnknownOptionParameter { + option: String, + id: String, + known: String, + }, + + /// A value doesn't have its parameter's type. + #[error("parameter {id:?} {source}")] + Mistyped { + id: String, + #[source] + source: ValueError, + }, +} + +fn engine_value( + definitions: &[ParameterDefinition], + id: &str, + value: &PlainValue, +) -> Result { + let definition = definitions + .iter() + .find(|definition| definition.parameter_id == id) + .ok_or_else(|| PayloadError::UnknownParameter { + id: id.to_owned(), + known: known( + definitions + .iter() + .map(|definition| &definition.parameter_id), + ), + })?; + let typed = typed(id, value, engine_kind(definition))?; + Ok(ParameterValue { + parameter_id: id.to_owned(), + value: Some(match typed { + TypedValue::Boolean(value) => parameter_value::Value::Boolean(value), + TypedValue::UnsignedInteger(value) => parameter_value::Value::UnsignedInteger(value), + TypedValue::Text(value) => parameter_value::Value::String(value), + }), + }) +} + +fn option_values( + options: &[ModelConfigurationOption], + id: &str, + values: &BTreeMap, +) -> Result { + let option = options + .iter() + .find(|option| option.option_id == id) + .ok_or_else(|| PayloadError::UnknownOption { + id: id.to_owned(), + known: known(options.iter().map(|option| &option.option_id)), + })?; + let values = values + .iter() + .map(|(parameter_id, value)| option_value(option, parameter_id, value)) + .collect::, _>>()?; + Ok(ModelOptionValues { + option_id: id.to_owned(), + values, + }) +} + +fn option_value( + option: &ModelConfigurationOption, + id: &str, + value: &PlainValue, +) -> Result { + let definition = option + .parameters + .iter() + .find(|definition| definition.parameter_id == id) + .ok_or_else(|| PayloadError::UnknownOptionParameter { + option: option.option_id.clone(), + id: id.to_owned(), + known: known( + option + .parameters + .iter() + .map(|parameter| ¶meter.parameter_id), + ), + })?; + let typed = typed( + &format!("{}.{id}", option.option_id), + value, + option_kind(definition), + )?; + Ok(ModelOptionParameterValue { + parameter_id: id.to_owned(), + value: Some(match typed { + TypedValue::Boolean(value) => model_option_parameter_value::Value::Boolean(value), + TypedValue::UnsignedInteger(value) => { + model_option_parameter_value::Value::UnsignedInteger(value) + } + TypedValue::Text(value) => model_option_parameter_value::Value::String(value), + }), + }) +} + +fn typed(id: &str, value: &PlainValue, kind: ValueKind) -> Result { + value.typed(kind).map_err(|source| PayloadError::Mistyped { + id: id.to_owned(), + source, + }) +} + +/// The value type of an engine parameter; a definition without a type takes text, for the +/// server to reject. +pub(super) fn engine_kind(definition: &ParameterDefinition) -> ValueKind { + match definition.parameter_type { + Some(parameter_definition::ParameterType::Boolean(_)) => ValueKind::Boolean, + Some(parameter_definition::ParameterType::UnsignedInteger(_)) => ValueKind::UnsignedInteger, + Some( + parameter_definition::ParameterType::StringEnum(_) + | parameter_definition::ParameterType::Text(_) + | parameter_definition::ParameterType::Secret(_), + ) + | None => ValueKind::Text, + } +} + +/// The value type of an option parameter; a definition without a type takes text, for the +/// server to reject. +pub(super) fn option_kind(definition: &ModelOptionParameterDefinition) -> ValueKind { + match definition.parameter_type { + Some(model_option_parameter_definition::ParameterType::Boolean(_)) => ValueKind::Boolean, + Some(model_option_parameter_definition::ParameterType::UnsignedInteger(_)) => { + ValueKind::UnsignedInteger + } + Some(model_option_parameter_definition::ParameterType::StringEnum(_)) | None => { + ValueKind::Text + } + } +} + +fn known<'a>(ids: impl Iterator) -> String { + ids.map(String::as_str).collect::>().join(", ") +} + +#[cfg(test)] +mod tests { + use dotcore_proto::dotcore::catalog::v1::{ + BooleanParameterSchema, StringEnumModelOptionParameterSchema, StringEnumParameterSchema, + UnsignedIntegerModelOptionParameterSchema, UnsignedIntegerParameterSchema, + }; + + use super::*; + + #[test] + fn a_payload_becomes_the_sparse_configuration_it_lists() { + let mut payload = ModelPayload { + model: "qwen".into(), + route: Some("qwen".into()), + custom_arguments: vec!["--verbose".into()], + ..ModelPayload::default() + }; + payload + .apply(&[ + Setting::parse("context-per-request=32768").expect("setting"), + Setting::parse("flash-attention=true").expect("setting"), + Setting::parse("cache-type=q8_0").expect("setting"), + Setting::parse("option.kv-cache-precision.precision=f16").expect("setting"), + ]) + .expect("apply"); + + assert_eq!( + payload.configuration(&schema()).expect("configuration"), + LocalModelDeploymentConfiguration { + model_artifact_binding_id: String::new(), + engine_parameter_values: Some(ParameterValues { + values: vec![ + engine("cache-type", parameter_value::Value::String("q8_0".into())), + engine( + "context-per-request", + parameter_value::Value::UnsignedInteger(32768) + ), + engine("flash-attention", parameter_value::Value::Boolean(true)), + ], + }), + custom_argument_tokens: vec!["--verbose".into()], + option_overrides: vec![ModelOptionValues { + option_id: "kv-cache-precision".into(), + values: vec![ModelOptionParameterValue { + parameter_id: "precision".into(), + value: Some(model_option_parameter_value::Value::String("f16".into())), + }], + }], + } + ); + assert_eq!( + payload.exposure(), + ModelDeploymentExposure { + kind: Some(model_deployment_exposure::Kind::Direct( + DirectRouteExposure { + route_name: "qwen".into(), + } + )), + } + ); + } + + #[test] + fn a_payload_without_values_or_route_leaves_them_to_the_server_and_stays_hidden() { + let payload = ModelPayload { + model: "qwen".into(), + ..ModelPayload::default() + }; + + assert_eq!( + payload.configuration(&schema()).expect("configuration"), + LocalModelDeploymentConfiguration::default() + ); + assert_eq!( + payload.exposure(), + ModelDeploymentExposure { + kind: Some(model_deployment_exposure::Kind::Hidden( + HiddenDeploymentExposure {} + )), + } + ); + } + + #[test] + fn later_settings_override_earlier_ones_and_reach_option_parameters() { + let mut payload = ModelPayload::default(); + payload + .apply(&[ + Setting::parse("context-per-request=8192").expect("setting"), + Setting::parse("context-per-request=65536").expect("setting"), + Setting::parse("option.speculative.token-count=3").expect("setting"), + ]) + .expect("apply"); + + let configuration = payload.configuration(&schema()).expect("configuration"); + assert_eq!( + configuration.engine_parameter_values, + Some(ParameterValues { + values: vec![engine( + "context-per-request", + parameter_value::Value::UnsignedInteger(65536) + )], + }) + ); + assert_eq!( + configuration.option_overrides, + vec![ModelOptionValues { + option_id: "speculative".into(), + values: vec![ModelOptionParameterValue { + parameter_id: "token-count".into(), + value: Some(model_option_parameter_value::Value::UnsignedInteger(3)), + }], + }] + ); + } + + #[test] + fn unknown_or_mistyped_values_fail_naming_the_parameter() { + let cases = [ + ( + "total=1", + "unknown parameter \"total\"; this profile's parameters are: \ + context-per-request, flash-attention, cache-type", + ), + ( + "flash-attention=yes", + "parameter \"flash-attention\" expects true or false", + ), + ( + "option.vision.enabled=true", + "unknown option \"vision\"; this profile's options are: kv-cache-precision, speculative", + ), + ( + "option.speculative.depth=1", + "unknown parameter \"depth\" of option \"speculative\"; its parameters are: token-count", + ), + ( + "option.speculative.token-count=many", + "parameter \"speculative.token-count\" expects a whole number", + ), + ]; + for (setting, message) in cases { + let mut payload = ModelPayload { + model: "qwen".into(), + ..ModelPayload::default() + }; + payload + .apply(&[Setting::parse(setting).expect("setting")]) + .expect("apply"); + let error = payload.configuration(&schema()).expect_err(setting); + assert_eq!(error.to_string(), message, "{setting}"); + } + } + + #[test] + fn an_option_override_must_name_its_parameter() { + let mut payload = ModelPayload::default(); + let error = payload + .apply(&[Setting::parse("option.speculative=3").expect("setting")]) + .expect_err("no parameter"); + assert_eq!( + error.to_string(), + "option override \"option.speculative\" must be option.." + ); + } + + fn schema() -> ParameterSchema<'static> { + use std::sync::LazyLock; + + static PARAMETERS: LazyLock> = LazyLock::new(|| { + vec![ + definition( + "context-per-request", + parameter_definition::ParameterType::UnsignedInteger( + UnsignedIntegerParameterSchema::default(), + ), + ), + definition( + "flash-attention", + parameter_definition::ParameterType::Boolean(BooleanParameterSchema::default()), + ), + definition( + "cache-type", + parameter_definition::ParameterType::StringEnum( + StringEnumParameterSchema::default(), + ), + ), + ] + }); + static OPTIONS: LazyLock> = LazyLock::new(|| { + vec![ + option( + "kv-cache-precision", + "precision", + model_option_parameter_definition::ParameterType::StringEnum( + StringEnumModelOptionParameterSchema::default(), + ), + ), + option( + "speculative", + "token-count", + model_option_parameter_definition::ParameterType::UnsignedInteger( + UnsignedIntegerModelOptionParameterSchema::default(), + ), + ), + ] + }); + ParameterSchema { + parameters: &PARAMETERS, + options: &OPTIONS, + } + } + + fn definition(id: &str, kind: parameter_definition::ParameterType) -> ParameterDefinition { + ParameterDefinition { + parameter_id: id.into(), + parameter_type: Some(kind), + ..ParameterDefinition::default() + } + } + + fn option( + id: &str, + parameter: &str, + kind: model_option_parameter_definition::ParameterType, + ) -> ModelConfigurationOption { + ModelConfigurationOption { + option_id: id.into(), + parameters: vec![ModelOptionParameterDefinition { + parameter_id: parameter.into(), + parameter_type: Some(kind), + ..ModelOptionParameterDefinition::default() + }], + ..ModelConfigurationOption::default() + } + } + + fn engine(id: &str, value: parameter_value::Value) -> ParameterValue { + ParameterValue { + parameter_id: id.into(), + value: Some(value), + } + } +} diff --git a/backend/cli/src/model/projection.rs b/backend/cli/src/model/projection.rs index 737cd48f..c4298cf6 100644 --- a/backend/cli/src/model/projection.rs +++ b/backend/cli/src/model/projection.rs @@ -9,7 +9,7 @@ use dotcore_proto::dotcore::model::v1::{ ModelDeployment, ModelDeploymentDesiredState, ModelDeploymentStatus, model_deployment_snapshot, }; -use crate::management::Addressable; +use crate::reference::Referable; /// The status the operator sees: a requested teardown reads as unloading, and a requested pause /// reads as pausing until the workload is paused or unavailable. @@ -100,7 +100,7 @@ pub(crate) fn model_display_name(deployment: &ModelDeployment) -> &str { } } -impl Addressable for ModelDeployment { +impl Referable for ModelDeployment { fn id(&self) -> &str { &self.model_deployment_id } @@ -109,8 +109,8 @@ impl Addressable for ModelDeployment { presentation_name(self) } - fn stored_name(&self) -> &str { - &self.model_deployment_name + fn aliases(&self) -> Vec<&str> { + vec![&self.model_deployment_name] } } diff --git a/backend/cli/src/model/selection.rs b/backend/cli/src/model/selection.rs new file mode 100644 index 00000000..221b6c22 --- /dev/null +++ b/backend/cli/src/model/selection.rs @@ -0,0 +1,336 @@ +//! Picks what one local model deployment uses: the catalog model, the execution target and the +//! profile, then has the server preview the result. +//! +//! The operator may name each choice; otherwise the target is the first where a profile fits now +//! (else the first that runs one), and the profile is the first that fits now on that target +//! (else the first that runs). Fit is the site's compatibility read; the CLI judges none itself. + +use anyhow::bail; +use dotcore_proto::dotcore::{ + catalog::v1::{Model, ModelConfigurationOption, ModelProfile}, + deployment::v1::{ExactPlacement, MemoryFit}, + model::v1::{ + CreateLocalModelDeploymentRequest, LocalModelDeploymentAdvisory, + LocalModelDeploymentConfiguration, ModelCompatibilityStatus, ModelProfileCompatibility, + PreviewLocalModelDeploymentRequest, ResolvedLocalModelDeploymentSnapshot, + }, +}; + +use super::{catalog::SiteCatalog, payload::ParameterSchema, site::DeploySite}; +use crate::{ + management::{DeploymentGroup, call_failed}, + reference::{Referable, ReferenceKind, resolve}, +}; + +/// What the operator named for one deployment; anything left out takes the default. +pub(super) struct Choices<'a> { + /// Catalog model reference. + pub(super) model: &'a str, + + /// Profile reference. + pub(super) profile: Option<&'a str>, + + /// Node reference. + pub(super) node: Option<&'a str>, + + /// Execution target reference on the node. + pub(super) target: Option<&'a str>, +} + +/// The model, target and profile of one deployment, with the server's preview of it. +#[derive(Clone, Debug)] +pub(super) struct Selection { + /// The catalog model. + pub(super) model: Model, + + /// The chosen profile. + pub(super) profile: ModelProfile, + + /// The chosen execution target. + pub(super) placement: ExactPlacement, + + /// The node's name, or its ID when unnamed. + pub(super) node_name: String, + + /// The target's name, or its ID when unnamed. + pub(super) target_name: String, + + /// Whether the node has other model targets, so a payload must name this one. + pub(super) shared_node: bool, + + /// The profile's compatibility on the target, absent when the site reported none. + pub(super) compatibility: Option, + + /// The resolved deployment the server previewed with the profile's defaults. + pub(super) snapshot: ResolvedLocalModelDeploymentSnapshot, + + /// The preview's non-blocking advisories. + pub(super) advisories: Vec, +} + +impl Selection { + /// The parameters a payload's values are typed against. + pub(super) fn schema(&self) -> ParameterSchema<'_> { + ParameterSchema { + parameters: self + .snapshot + .engine_parameter_schema + .as_ref() + .map_or(&[][..], |schema| &schema.parameters), + options: self.options(), + } + } + + fn options(&self) -> &[ModelConfigurationOption] { + self.model + .configurations + .iter() + .find(|configuration| configuration.configuration_id == self.snapshot.configuration_id) + .map_or(&[][..], |configuration| &configuration.options) + } +} + +/// Resolves the operator's choices on the site and previews the deployment they select. +pub(super) async fn select( + site: &dyn DeploySite, + choices: &Choices<'_>, +) -> anyhow::Result { + let catalog = SiteCatalog::read(site, Some(choices.model)).await?; + let Some(model) = catalog.models.first() else { + bail!("no catalog model matches {:?}", choices.model); + }; + + let targets = targets(&catalog, choices.node, choices.target)?; + let named = choices + .profile + .map(|reference| resolve(ReferenceKind::Profile, reference, &model.profiles)) + .transpose()?; + let target = default_target(&catalog, model, named, &targets); + let profile = match named { + Some(profile) => profile, + None => default_profile(&catalog, model, std::slice::from_ref(target))?, + }; + preview(site, &catalog, model, profile, target).await +} + +/// Has the server preview an untouched deployment of the profile on the target, and returns the +/// selection it makes. +pub(super) async fn preview( + site: &dyn DeploySite, + catalog: &SiteCatalog, + model: &Model, + profile: &ModelProfile, + target: &Target, +) -> anyhow::Result { + let preview = site + .preview(PreviewLocalModelDeploymentRequest { + local: Some(CreateLocalModelDeploymentRequest { + model_id: model.model_id.clone(), + profile_id: profile.profile_id.clone(), + placement: Some(target.placement.clone()), + configuration: Some(LocalModelDeploymentConfiguration::default()), + }), + }) + .await + .map_err(call_failed( + DeploymentGroup::Model, + format!("preview {} on {}", model.display_name, target.node_name), + ))?; + + let shared_node = catalog + .compatibility + .targets + .iter() + .filter_map(|compatibility| compatibility.target.as_ref()) + .filter(|placement| placement.site_node_id == target.placement.site_node_id) + .count() + > 1; + Ok(Selection { + compatibility: entry(catalog, model, profile, target).cloned(), + model: model.clone(), + profile: profile.clone(), + placement: target.placement.clone(), + node_name: target.node_name.clone(), + target_name: target.target_name.clone(), + shared_node, + advisories: preview.advisories().collect(), + snapshot: preview.resolved_snapshot.unwrap_or_default(), + }) +} + +/// The target a deployment defaults to: for a named profile, the first target where it fits now, +/// else the first where it runs; without one, the first where any profile does. Else the first. +pub(super) fn default_target<'a>( + catalog: &SiteCatalog, + model: &Model, + profile: Option<&ModelProfile>, + targets: &'a [Target], +) -> &'a Target { + let accepted = |target: &Target, accepts: fn(&ModelProfileCompatibility) -> bool| { + model + .profiles + .iter() + .filter(|candidate| profile.is_none_or(|profile| profile == *candidate)) + .any(|candidate| entry(catalog, model, candidate, target).is_some_and(accepts)) + }; + targets + .iter() + .find(|target| accepted(target, fits_now)) + .or_else(|| targets.iter().find(|target| accepted(target, runs))) + .unwrap_or(&targets[0]) +} + +/// One model target a deployment may use. +#[derive(Clone, Debug)] +pub(super) struct Target { + /// Where the target is. + pub(super) placement: ExactPlacement, + + /// The node's name, or its ID when unnamed. + pub(super) node_name: String, + + /// The target's name, or its ID when unnamed. + pub(super) target_name: String, +} + +/// The targets the references allow, in node then target order: the named target of the named +/// node, every target of the named node, or every model target. +pub(super) fn targets( + catalog: &SiteCatalog, + node: Option<&str>, + target: Option<&str>, +) -> anyhow::Result> { + let mut targets: Vec = catalog + .compatibility + .targets + .iter() + .filter_map(|compatibility| compatibility.target.clone()) + .map(|placement| Target { + node_name: catalog.nodes.display(&placement.site_node_id).to_owned(), + target_name: catalog + .nodes + .target_display(&placement.site_node_id, &placement.execution_target_id) + .to_owned(), + placement, + }) + .collect(); + if targets.is_empty() { + bail!("the site has no model target"); + } + + if let Some(reference) = node { + let mut nodes: Vec = Vec::new(); + for target in &targets { + if !nodes + .iter() + .any(|node| node.id == target.placement.site_node_id) + { + nodes.push(Node { + id: target.placement.site_node_id.clone(), + name: target.node_name.clone(), + }); + } + } + let node = resolve(ReferenceKind::Node, reference, &nodes)?.id.clone(); + targets.retain(|target| target.placement.site_node_id == node); + } + if let Some(reference) = target { + let target = resolve(ReferenceKind::ExecutionTarget, reference, &targets)? + .placement + .clone(); + targets.retain(|candidate| candidate.placement == target); + } + Ok(targets) +} + +/// The first profile that fits now on one of the targets, else the first that runs on one. +pub(super) fn default_profile<'a>( + catalog: &SiteCatalog, + model: &'a Model, + targets: &[Target], +) -> anyhow::Result<&'a ModelProfile> { + let on_targets = |profile: &ModelProfile, accepts: fn(&ModelProfileCompatibility) -> bool| { + targets + .iter() + .any(|target| entry(catalog, model, profile, target).is_some_and(accepts)) + }; + model + .profiles + .iter() + .find(|profile| on_targets(profile, fits_now)) + .or_else(|| { + model + .profiles + .iter() + .find(|profile| on_targets(profile, runs)) + }) + .ok_or_else(|| { + anyhow::anyhow!( + "no profile of {} runs on {}", + model.display_name, + targets + .iter() + .map(|target| target.node_name.as_str()) + .collect::>() + .join(", ") + ) + }) +} + +/// The profile's compatibility on the target, when the site reported one. +pub(super) fn entry<'a>( + catalog: &'a SiteCatalog, + model: &Model, + profile: &ModelProfile, + target: &Target, +) -> Option<&'a ModelProfileCompatibility> { + catalog + .entries(&model.model_id, &profile.profile_id) + .find(|entry| entry.target.as_ref() == Some(&target.placement)) +} + +/// Whether the profile runs on the entry's target. +pub(super) fn runs(entry: &ModelProfileCompatibility) -> bool { + entry.status() == ModelCompatibilityStatus::Runs +} + +/// Whether the profile runs and fits the free memory of the entry's target now. +pub(super) fn fits_now(entry: &ModelProfileCompatibility) -> bool { + runs(entry) && entry.free_memory_fit() == MemoryFit::Fits +} + +/// A node as the operator names it. +struct Node { + id: String, + name: String, +} + +impl Referable for Node { + fn id(&self) -> &str { + &self.id + } + + fn name(&self) -> &str { + &self.name + } +} + +impl Referable for Target { + fn id(&self) -> &str { + &self.placement.execution_target_id + } + + fn name(&self) -> &str { + &self.target_name + } +} + +impl Referable for ModelProfile { + fn id(&self) -> &str { + &self.profile_id + } + + fn name(&self) -> &str { + &self.display_name + } +} diff --git a/backend/cli/src/model/show.rs b/backend/cli/src/model/show.rs index a5879054..33cfe8e9 100644 --- a/backend/cli/src/model/show.rs +++ b/backend/cli/src/model/show.rs @@ -1,29 +1,29 @@ //! Shows what an operator needs to manage one model deployment, for example its state, node, //! model, download progress or failure message. //! -//! On a terminal it prints labeled values for what is known; without one it prints one record -//! block on stdout that always carries every key, empty when the value is absent. +//! It prints labeled values for what is known, on the terminal or as plain text without one. Asked +//! for YAML, it prints the deployment as the manager returns it, with secret values masked unless revealed. use clap::Args; use dotcore_proto::dotcore::model::v1::{ModelDeployment, model_deployment_snapshot}; use super::{ - node_of, parameters, placement, + document, node_of, parameters, projection::{ desired_state_label, model_display_name, presentation_name, state_label, state_overridden, }, }; use crate::{ - management::{ManagerArgs, NodeNames, find_deployment, single_line}, - node::write_records, - parameters::{ParameterRow, record_lines, write_parameters}, - terminal::{Message, TerminalCondition, controlling_terminal_condition, open_terminal}, + management::{ManagedDeployment, ManagerArgs, NodeNames, find_deployment, single_line}, + output::{OutputFormat, present, write_yaml}, + parameters::{ParameterRow, parameter_messages}, + terminal::Message, }; /// Arguments selecting the model deployment to show. #[derive(Debug, Args)] pub struct ModelShowArgs { - /// Name or id of the model deployment. + /// Name or ID of the model deployment. #[arg(value_name = "DEPLOYMENT")] reference: String, @@ -35,25 +35,27 @@ pub struct ModelShowArgs { manager: ManagerArgs, } -/// Shows the deployment on the terminal, else as a record block. -pub(crate) async fn model_show(arguments: ModelShowArgs) -> anyhow::Result<()> { +/// Shows the deployment as YAML when asked, else as labeled values. +pub(crate) async fn model_show( + arguments: ModelShowArgs, + format: OutputFormat, +) -> anyhow::Result<()> { let manager = arguments.manager.connect().await?; let deployment = find_deployment::(&manager, &arguments.reference).await?; let nodes = manager.node_names().await; - let details = Details::of(&deployment, &nodes, arguments.reveal_secrets); - if controlling_terminal_condition() == TerminalCondition::Interactive { - let mut terminal = open_terminal(); - terminal.message(&Message::Heading(format!( - "Model deployment {}", - details.name - )))?; - terminal.message(&Message::KeyValues(details.pairs()))?; - write_parameters(&mut *terminal, &details.parameters)?; - return Ok(()); + if format == OutputFormat::Yaml { + return write_yaml(&document(deployment, &nodes, arguments.reveal_secrets)); } - write_records(&details.record_block()) + let details = Details::of(&deployment, &nodes, arguments.reveal_secrets); + + let mut messages = vec![ + Message::Heading(format!("Model deployment {}", details.name)), + Message::KeyValues(details.pairs()), + ]; + messages.extend(parameter_messages(&details.parameters)); + present(&messages) } /// The shown facts of one deployment; absent facts are empty. @@ -118,14 +120,21 @@ impl Details { state, desired_state: desired_state_label(deployment.desired_state()), node: single_line(node_of(deployment, nodes).unwrap_or("")), - execution_target: placement(deployment).map_or_else(String::new, |placement| { - single_line(&placement.execution_target_id) - }), - execution_target_name: placement(deployment).map_or_else(String::new, |placement| { - single_line( - nodes.target_display(&placement.site_node_id, &placement.execution_target_id), - ) - }), + execution_target: deployment + .placement() + .map_or_else(String::new, |placement| { + single_line(&placement.execution_target_id) + }), + execution_target_name: deployment + .placement() + .map_or_else(String::new, |placement| { + single_line( + nodes.target_display( + &placement.site_node_id, + &placement.execution_target_id, + ), + ) + }), model: single_line(model_display_name(deployment)), profile: single_line(profile), engine: single_line(engine), @@ -158,27 +167,4 @@ impl Details { .map(|(label, value)| (label.to_owned(), value.to_owned())) .collect() } - - fn record_block(&self) -> String { - let mut block = format!( - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID={}\nDOTCORE_MODEL_DEPLOYMENT_NAME={}\nDOTCORE_MODEL_DEPLOYMENT_STATE={}\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE={}\nDOTCORE_MODEL_DEPLOYMENT_NODE={}\nDOTCORE_MODEL_DEPLOYMENT_EXECUTION_TARGET={}\nDOTCORE_MODEL_DEPLOYMENT_MODEL={}\nDOTCORE_MODEL_DEPLOYMENT_PROFILE={}\nDOTCORE_MODEL_DEPLOYMENT_ENGINE={}\nDOTCORE_MODEL_DEPLOYMENT_PROGRESS={}\nDOTCORE_MODEL_DEPLOYMENT_FAILURE={}\nDOTCORE_MODEL_DEPLOYMENT_MESSAGE={}\n", - self.id, - self.name, - self.state, - self.desired_state, - self.node, - self.execution_target, - self.model, - self.profile, - self.engine, - self.progress, - self.failure, - self.message, - ); - block.push_str(&record_lines( - "DOTCORE_MODEL_DEPLOYMENT_PARAMETER", - &self.parameters, - )); - block - } } diff --git a/backend/cli/src/model/site.rs b/backend/cli/src/model/site.rs new file mode 100644 index 00000000..135ba719 --- /dev/null +++ b/backend/cli/src/model/site.rs @@ -0,0 +1,124 @@ +//! The site reads and writes that deploying one local model makes, behind one seam. +//! +//! Every deploy command reaches the site manager through this seam: the catalog and where its +//! profiles fit, the names of the nodes, the server's preview and estimate of one configuration, +//! and the deployment's creation. The running manager serves them; tests drive the guided flow +//! against a fake site instead. + +use dotcore_proto::dotcore::{ + catalog::v1::{ListModelsRequest, Model}, + model::v1::{ + CreateModelDeploymentRequest, EstimateLocalModelResourcesRequest, + EstimateLocalModelResourcesResponse, ListModelProfileCompatibilityRequest, + ListModelProfileCompatibilityResponse, ModelDeployment, PreviewLocalModelDeploymentRequest, + PreviewLocalModelDeploymentResponse, + }, +}; +use futures_util::future::BoxFuture; +use tonic::Status; + +use crate::management::{Manager, NodeNames}; + +/// What a model deployment asks of the site, each call answering as the management API does. +pub(super) trait DeploySite: Sync { + /// The local catalog models. + fn list_models(&self) -> BoxFuture<'_, Result, Status>>; + + /// Where each catalog profile fits, narrowed as the request asks. + fn compatibility( + &self, + request: ListModelProfileCompatibilityRequest, + ) -> BoxFuture<'_, Result>; + + /// The display names of the nodes and their targets; a failed read names none. + fn node_names(&self) -> BoxFuture<'_, NodeNames>; + + /// The server's resolution of one deployment, with its advisories. + fn preview( + &self, + request: PreviewLocalModelDeploymentRequest, + ) -> BoxFuture<'_, Result>; + + /// The server's memory estimate of one configuration on its target. + fn estimate( + &self, + request: EstimateLocalModelResourcesRequest, + ) -> BoxFuture<'_, Result>; + + /// Creates the deployment and returns it as accepted. + fn create( + &self, + request: CreateModelDeploymentRequest, + ) -> BoxFuture<'_, Result>; +} + +impl DeploySite for Manager { + fn list_models(&self) -> BoxFuture<'_, Result, Status>> { + Box::pin(async move { + Ok(self + .catalog() + .list_models(ListModelsRequest {}) + .await? + .into_inner() + .models) + }) + } + + fn compatibility( + &self, + request: ListModelProfileCompatibilityRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + Ok(self + .models() + .list_model_profile_compatibility(request) + .await? + .into_inner()) + }) + } + + fn node_names(&self) -> BoxFuture<'_, NodeNames> { + Box::pin(Manager::node_names(self)) + } + + fn preview( + &self, + request: PreviewLocalModelDeploymentRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + Ok(self + .models() + .preview_local_model_deployment(request) + .await? + .into_inner()) + }) + } + + fn estimate( + &self, + request: EstimateLocalModelResourcesRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + Ok(self + .models() + .estimate_local_model_resources(request) + .await? + .into_inner()) + }) + } + + fn create( + &self, + request: CreateModelDeploymentRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(async move { + Ok(self + .models() + .create_model_deployment(request) + .await? + .into_inner() + .deployment + .unwrap_or_default()) + }) + } +} diff --git a/backend/cli/src/model/view.rs b/backend/cli/src/model/view.rs new file mode 100644 index 00000000..3f59e0c0 --- /dev/null +++ b/backend/cli/src/model/view.rs @@ -0,0 +1,568 @@ +//! The parameters an operator can set on one local model deployment, with what each accepts and +//! the value a deployment starts from. +//! +//! The view presents what the server resolved: the parameter schema, visibility, and starting +//! values of a deployment preview, with the context values sizing starts from on the chosen target. +//! It decides no value itself. Hidden parameters are left out, and secret values never appear. + +use dotcore_catalog::typed_parameters::{canonical_text, is_secret}; +use dotcore_proto::dotcore::{ + catalog::v1::{ + Model, ModelOptionParameterDefinition, ParameterDefinition, ParameterVisibility, + model_option_parameter_definition, model_option_parameter_value, parameter_definition, + }, + model::v1::{ + ModelProfileCompatibility, ResolvedLocalModelDeploymentSnapshot, StartingTotalContextSource, + }, +}; + +use super::payload::{engine_kind, option_kind}; +use crate::deploy::ValueKind; + +/// The engine parameter one request may use as context, in tokens. +pub(super) const CONTEXT_PER_REQUEST: &str = "context-per-request"; + +/// The engine parameter holding the context all requests share, in tokens. +pub(super) const TOTAL_CONTEXT: &str = "total-context"; + +/// The engine parameter counting the requests generated at once. +pub(super) const PARALLEL_REQUESTS: &str = "parallel-requests"; + +/// The settable parameters of one deployment, engine parameters first in schema order, then +/// option parameters in configuration order. +#[derive(Debug, Eq, PartialEq)] +pub(super) struct ParameterView { + /// The shown parameters. + pub(super) parameters: Vec, +} + +/// One parameter as the operator sees it. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(super) struct ViewParameter { + /// The key a payload and `--set` use: the engine parameter ID, or `