From 066af577d88c2f4f8bac56f0861675a154a66721 Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 11:25:23 -0500 Subject: [PATCH 01/19] feat(proto): one readable deployment identity allocator --- .../src/gen/dotcore/model/v1/deployment_pb.ts | 2 +- frontend/src/gen/dotcore/site/v1/site_pb.ts | 26 +++++++++---------- proto/dotcore/model/v1/deployment.proto | 2 +- proto/dotcore/site/v1/site.proto | 12 ++++----- 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/frontend/src/gen/dotcore/model/v1/deployment_pb.ts b/frontend/src/gen/dotcore/model/v1/deployment_pb.ts index 966bf7b6..555b81e5 100644 --- a/frontend/src/gen/dotcore/model/v1/deployment_pb.ts +++ b/frontend/src/gen/dotcore/model/v1/deployment_pb.ts @@ -834,7 +834,7 @@ export const UpstreamModelDeploymentSnapshotSchema: GenMessage & { /** - * Private model identifier sent in endpoint requests. + * Model identifier sent in endpoint requests; it also names the deployment's ID. * * @generated from field: string upstream_model_id = 1; */ diff --git a/frontend/src/gen/dotcore/site/v1/site_pb.ts b/frontend/src/gen/dotcore/site/v1/site_pb.ts index 195d9310..0500f5a9 100644 --- a/frontend/src/gen/dotcore/site/v1/site_pb.ts +++ b/frontend/src/gen/dotcore/site/v1/site_pb.ts @@ -18,7 +18,7 @@ import type { Message } from "@bufbuild/protobuf"; * Describes the file dotcore/site/v1/site.proto. */ export const file_dotcore_site_v1_site: GenFile = /*@__PURE__*/ - fileDesc("Chpkb3Rjb3JlL3NpdGUvdjEvc2l0ZS5wcm90bxIPZG90Y29yZS5zaXRlLnYxIs8ECgRTaXRlEg8KB3NpdGVfaWQYASABKAkSOwoRZXhlY3V0aW9uX3RhcmdldHMYAiADKAsyIC5kb3Rjb3JlLnNpdGUudjEuRXhlY3V0aW9uVGFyZ2V0EkcKEW1vZGVsX2RlcGxveW1lbnRzGAMgAygLMiwuZG90Y29yZS5tb2RlbC52MS5Nb2RlbERlcGxveW1lbnREZWNsYXJhdGlvbhIoCgVub2RlcxgEIAMoCzIZLmRvdGNvcmUuc2l0ZS52MS5TaXRlTm9kZRJZChdhcHBsaWNhdGlvbl9kZXBsb3ltZW50cxgFIAMoCzI4LmRvdGNvcmUuYXBwbGljYXRpb24udjEuQXBwbGljYXRpb25EZXBsb3ltZW50RGVjbGFyYXRpb24SPgoQaW5mZXJlbmNlX3JvdXRlcxgGIAMoCzIkLmRvdGNvcmUuaW5mZXJlbmNlLnYxLkluZmVyZW5jZVJvdXRlEk8KFGhhcmR3YXJlX29ic2VydmF0aW9uGAcgASgLMjEuZG90Y29yZS5zaXRlLnYxLkhhcmR3YXJlT2JzZXJ2YXRpb25Db25maWd1cmF0aW9uEl4KI21vZGVsX2RlcGxveW1lbnRfaWRlbnRpdHlfYWxsb2NhdG9yGAggASgLMjEuZG90Y29yZS5zaXRlLnYxLk1vZGVsRGVwbG95bWVudElkZW50aXR5QWxsb2NhdG9yEjoKEGNvbnNvbGVfc2V0dGluZ3MYCSABKAsyIC5kb3Rjb3JlLnNpdGUudjEuQ29uc29sZVNldHRpbmdzIi0KD0NvbnNvbGVTZXR0aW5ncxIaChJnZXRfc3RhcnRlZF9oaWRkZW4YASABKAgiTAogTW9kZWxEZXBsb3ltZW50SWRlbnRpdHlBbGxvY2F0b3ISEQoJbmFtZXNwYWNlGAEgASgJEhUKDW5leHRfc2VxdWVuY2UYAiABKAQiZgogSGFyZHdhcmVPYnNlcnZhdGlvbkNvbmZpZ3VyYXRpb24SJQoYcmVmcmVzaF9pbnRlcnZhbF9zZWNvbmRzGAEgASgNSACIAQFCGwoZX3JlZnJlc2hfaW50ZXJ2YWxfc2Vjb25kcyKNAQoIU2l0ZU5vZGUSDwoHbm9kZV9pZBgBIAEoCRIUCgxkaXNwbGF5X25hbWUYAiABKAkSNgoMc2l0ZV9tYW5hZ2VyGAMgASgLMiAuZG90Y29yZS5zaXRlLnYxLlNpdGVNYW5hZ2VyUm9sZRIMCgRob3N0GAUgASgJEhQKDG1hbmFnZXJfaG9zdBgGIAEoCSLKAgoPRXhlY3V0aW9uVGFyZ2V0EhsKE2V4ZWN1dGlvbl90YXJnZXRfaWQYASABKAkSFAoMc2l0ZV9ub2RlX2lkGAIgASgJEhQKDGRpc3BsYXlfbmFtZRgHIAEoCRIxCghwbGF0Zm9ybRgDIAEoCzIfLmRvdGNvcmUuY2F0YWxvZy52MS5PY2lQbGF0Zm9ybRIeChZhY2NlbGVyYXRvcl9kZXZpY2VfaWRzGAQgAygJEj0KDW1vZGVsX3J1bnRpbWUYBSABKAsyJC5kb3Rjb3JlLnNpdGUudjEuTW9kZWxSdW50aW1lQmluZGluZ0gAEkkKE2FwcGxpY2F0aW9uX3J1bnRpbWUYBiABKAsyKi5kb3Rjb3JlLnNpdGUudjEuQXBwbGljYXRpb25SdW50aW1lQmluZGluZ0gAQhEKD3J1bnRpbWVfYmluZGluZyLpAQoTTW9kZWxSdW50aW1lQmluZGluZxJFChFzaW11bGF0ZWRfcnVudGltZRgBIAEoCzIoLmRvdGNvcmUuc2l0ZS52MS5TaW11bGF0ZWRSdW50aW1lQWRhcHRlckgAEj8KDmRvY2tlcl9ydW50aW1lGAIgASgLMiUuZG90Y29yZS5zaXRlLnYxLkRvY2tlclJ1bnRpbWVBZGFwdGVySAASPwoObmF0aXZlX3J1bnRpbWUYAyABKAsyJS5kb3Rjb3JlLnNpdGUudjEuTmF0aXZlUnVudGltZUFkYXB0ZXJIAEIJCgdhZGFwdGVyIsQBChlBcHBsaWNhdGlvblJ1bnRpbWVCaW5kaW5nEkoKDmRvY2tlcl9ydW50aW1lGAEgASgLMjAuZG90Y29yZS5zaXRlLnYxLkRvY2tlckFwcGxpY2F0aW9uUnVudGltZUFkYXB0ZXJIABJQChFzaW11bGF0ZWRfcnVudGltZRgCIAEoCzIzLmRvdGNvcmUuc2l0ZS52MS5TaW11bGF0ZWRBcHBsaWNhdGlvblJ1bnRpbWVBZGFwdGVySABCCQoHYWRhcHRlciIRCg9TaXRlTWFuYWdlclJvbGUiIQofRG9ja2VyQXBwbGljYXRpb25SdW50aW1lQWRhcHRlciIkCiJTaW11bGF0ZWRBcHBsaWNhdGlvblJ1bnRpbWVBZGFwdGVyIrEBChdTaW11bGF0ZWRSdW50aW1lQWRhcHRlchJDChBkZWZhdWx0X3NjZW5hcmlvGAEgASgLMikuZG90Y29yZS5zaXRlLnYxLlNpbXVsYXRlZFJ1bnRpbWVTY2VuYXJpbxJRChRkZXBsb3ltZW50X3NjZW5hcmlvcxgCIAMoCzIzLmRvdGNvcmUuc2l0ZS52MS5TaW11bGF0ZWRSdW50aW1lRGVwbG95bWVudFNjZW5hcmlvIn4KIlNpbXVsYXRlZFJ1bnRpbWVEZXBsb3ltZW50U2NlbmFyaW8SGwoTbW9kZWxfZGVwbG95bWVudF9pZBgBIAEoCRI7CghzY2VuYXJpbxgCIAEoCzIpLmRvdGNvcmUuc2l0ZS52MS5TaW11bGF0ZWRSdW50aW1lU2NlbmFyaW8iUQoYU2ltdWxhdGVkUnVudGltZVNjZW5hcmlvEhoKEnJlYWR5X2RlbGF5X21pbGxpcxgBIAEoBBIZChFzdG9wX2RlbGF5X21pbGxpcxgCIAEoBCJaChROYXRpdmVSdW50aW1lQWRhcHRlchJCChF3b3JrbG9hZF9saWZldGltZRgBIAEoDjInLmRvdGNvcmUuc2l0ZS52MS5OYXRpdmVXb3JrbG9hZExpZmV0aW1lImIKFERvY2tlclJ1bnRpbWVBZGFwdGVyEkoKFWFjY2VsZXJhdG9yX3RyYW5zcG9ydBgBIAEoDjIrLmRvdGNvcmUuc2l0ZS52MS5Eb2NrZXJBY2NlbGVyYXRvclRyYW5zcG9ydCqgAQoaRG9ja2VyQWNjZWxlcmF0b3JUcmFuc3BvcnQSLAooRE9DS0VSX0FDQ0VMRVJBVE9SX1RSQU5TUE9SVF9VTlNQRUNJRklFRBAAEiQKIERPQ0tFUl9BQ0NFTEVSQVRPUl9UUkFOU1BPUlRfQ0RJEAESLgoqRE9DS0VSX0FDQ0VMRVJBVE9SX1RSQU5TUE9SVF9MRUdBQ1lfTlZJRElBEAIqkwEKFk5hdGl2ZVdvcmtsb2FkTGlmZXRpbWUSKAokTkFUSVZFX1dPUktMT0FEX0xJRkVUSU1FX1VOU1BFQ0lGSUVEEAASJwojTkFUSVZFX1dPUktMT0FEX0xJRkVUSU1FX1BFUlNJU1RFTlQQARImCiJOQVRJVkVfV09SS0xPQURfTElGRVRJTUVfRVBIRU1FUkFMEAJiBnByb3RvMw", [file_dotcore_application_v1_deployment, file_dotcore_catalog_v1_oci, file_dotcore_inference_v1_routes, file_dotcore_model_v1_deployment]); + fileDesc("Chpkb3Rjb3JlL3NpdGUvdjEvc2l0ZS5wcm90bxIPZG90Y29yZS5zaXRlLnYxIsQECgRTaXRlEg8KB3NpdGVfaWQYASABKAkSOwoRZXhlY3V0aW9uX3RhcmdldHMYAiADKAsyIC5kb3Rjb3JlLnNpdGUudjEuRXhlY3V0aW9uVGFyZ2V0EkcKEW1vZGVsX2RlcGxveW1lbnRzGAMgAygLMiwuZG90Y29yZS5tb2RlbC52MS5Nb2RlbERlcGxveW1lbnREZWNsYXJhdGlvbhIoCgVub2RlcxgEIAMoCzIZLmRvdGNvcmUuc2l0ZS52MS5TaXRlTm9kZRJZChdhcHBsaWNhdGlvbl9kZXBsb3ltZW50cxgFIAMoCzI4LmRvdGNvcmUuYXBwbGljYXRpb24udjEuQXBwbGljYXRpb25EZXBsb3ltZW50RGVjbGFyYXRpb24SPgoQaW5mZXJlbmNlX3JvdXRlcxgGIAMoCzIkLmRvdGNvcmUuaW5mZXJlbmNlLnYxLkluZmVyZW5jZVJvdXRlEk8KFGhhcmR3YXJlX29ic2VydmF0aW9uGAcgASgLMjEuZG90Y29yZS5zaXRlLnYxLkhhcmR3YXJlT2JzZXJ2YXRpb25Db25maWd1cmF0aW9uElMKHWRlcGxveW1lbnRfaWRlbnRpdHlfYWxsb2NhdG9yGAggASgLMiwuZG90Y29yZS5zaXRlLnYxLkRlcGxveW1lbnRJZGVudGl0eUFsbG9jYXRvchI6ChBjb25zb2xlX3NldHRpbmdzGAkgASgLMiAuZG90Y29yZS5zaXRlLnYxLkNvbnNvbGVTZXR0aW5ncyItCg9Db25zb2xlU2V0dGluZ3MSGgoSZ2V0X3N0YXJ0ZWRfaGlkZGVuGAEgASgIIkgKG0RlcGxveW1lbnRJZGVudGl0eUFsbG9jYXRvchISCgpzdWZmaXhfa2V5GAEgASgJEhUKDW5leHRfc2VxdWVuY2UYAiABKAQiZgogSGFyZHdhcmVPYnNlcnZhdGlvbkNvbmZpZ3VyYXRpb24SJQoYcmVmcmVzaF9pbnRlcnZhbF9zZWNvbmRzGAEgASgNSACIAQFCGwoZX3JlZnJlc2hfaW50ZXJ2YWxfc2Vjb25kcyKNAQoIU2l0ZU5vZGUSDwoHbm9kZV9pZBgBIAEoCRIUCgxkaXNwbGF5X25hbWUYAiABKAkSNgoMc2l0ZV9tYW5hZ2VyGAMgASgLMiAuZG90Y29yZS5zaXRlLnYxLlNpdGVNYW5hZ2VyUm9sZRIMCgRob3N0GAUgASgJEhQKDG1hbmFnZXJfaG9zdBgGIAEoCSLKAgoPRXhlY3V0aW9uVGFyZ2V0EhsKE2V4ZWN1dGlvbl90YXJnZXRfaWQYASABKAkSFAoMc2l0ZV9ub2RlX2lkGAIgASgJEhQKDGRpc3BsYXlfbmFtZRgHIAEoCRIxCghwbGF0Zm9ybRgDIAEoCzIfLmRvdGNvcmUuY2F0YWxvZy52MS5PY2lQbGF0Zm9ybRIeChZhY2NlbGVyYXRvcl9kZXZpY2VfaWRzGAQgAygJEj0KDW1vZGVsX3J1bnRpbWUYBSABKAsyJC5kb3Rjb3JlLnNpdGUudjEuTW9kZWxSdW50aW1lQmluZGluZ0gAEkkKE2FwcGxpY2F0aW9uX3J1bnRpbWUYBiABKAsyKi5kb3Rjb3JlLnNpdGUudjEuQXBwbGljYXRpb25SdW50aW1lQmluZGluZ0gAQhEKD3J1bnRpbWVfYmluZGluZyLpAQoTTW9kZWxSdW50aW1lQmluZGluZxJFChFzaW11bGF0ZWRfcnVudGltZRgBIAEoCzIoLmRvdGNvcmUuc2l0ZS52MS5TaW11bGF0ZWRSdW50aW1lQWRhcHRlckgAEj8KDmRvY2tlcl9ydW50aW1lGAIgASgLMiUuZG90Y29yZS5zaXRlLnYxLkRvY2tlclJ1bnRpbWVBZGFwdGVySAASPwoObmF0aXZlX3J1bnRpbWUYAyABKAsyJS5kb3Rjb3JlLnNpdGUudjEuTmF0aXZlUnVudGltZUFkYXB0ZXJIAEIJCgdhZGFwdGVyIsQBChlBcHBsaWNhdGlvblJ1bnRpbWVCaW5kaW5nEkoKDmRvY2tlcl9ydW50aW1lGAEgASgLMjAuZG90Y29yZS5zaXRlLnYxLkRvY2tlckFwcGxpY2F0aW9uUnVudGltZUFkYXB0ZXJIABJQChFzaW11bGF0ZWRfcnVudGltZRgCIAEoCzIzLmRvdGNvcmUuc2l0ZS52MS5TaW11bGF0ZWRBcHBsaWNhdGlvblJ1bnRpbWVBZGFwdGVySABCCQoHYWRhcHRlciIRCg9TaXRlTWFuYWdlclJvbGUiIQofRG9ja2VyQXBwbGljYXRpb25SdW50aW1lQWRhcHRlciIkCiJTaW11bGF0ZWRBcHBsaWNhdGlvblJ1bnRpbWVBZGFwdGVyIrEBChdTaW11bGF0ZWRSdW50aW1lQWRhcHRlchJDChBkZWZhdWx0X3NjZW5hcmlvGAEgASgLMikuZG90Y29yZS5zaXRlLnYxLlNpbXVsYXRlZFJ1bnRpbWVTY2VuYXJpbxJRChRkZXBsb3ltZW50X3NjZW5hcmlvcxgCIAMoCzIzLmRvdGNvcmUuc2l0ZS52MS5TaW11bGF0ZWRSdW50aW1lRGVwbG95bWVudFNjZW5hcmlvIn4KIlNpbXVsYXRlZFJ1bnRpbWVEZXBsb3ltZW50U2NlbmFyaW8SGwoTbW9kZWxfZGVwbG95bWVudF9pZBgBIAEoCRI7CghzY2VuYXJpbxgCIAEoCzIpLmRvdGNvcmUuc2l0ZS52MS5TaW11bGF0ZWRSdW50aW1lU2NlbmFyaW8iUQoYU2ltdWxhdGVkUnVudGltZVNjZW5hcmlvEhoKEnJlYWR5X2RlbGF5X21pbGxpcxgBIAEoBBIZChFzdG9wX2RlbGF5X21pbGxpcxgCIAEoBCJaChROYXRpdmVSdW50aW1lQWRhcHRlchJCChF3b3JrbG9hZF9saWZldGltZRgBIAEoDjInLmRvdGNvcmUuc2l0ZS52MS5OYXRpdmVXb3JrbG9hZExpZmV0aW1lImIKFERvY2tlclJ1bnRpbWVBZGFwdGVyEkoKFWFjY2VsZXJhdG9yX3RyYW5zcG9ydBgBIAEoDjIrLmRvdGNvcmUuc2l0ZS52MS5Eb2NrZXJBY2NlbGVyYXRvclRyYW5zcG9ydCqgAQoaRG9ja2VyQWNjZWxlcmF0b3JUcmFuc3BvcnQSLAooRE9DS0VSX0FDQ0VMRVJBVE9SX1RSQU5TUE9SVF9VTlNQRUNJRklFRBAAEiQKIERPQ0tFUl9BQ0NFTEVSQVRPUl9UUkFOU1BPUlRfQ0RJEAESLgoqRE9DS0VSX0FDQ0VMRVJBVE9SX1RSQU5TUE9SVF9MRUdBQ1lfTlZJRElBEAIqkwEKFk5hdGl2ZVdvcmtsb2FkTGlmZXRpbWUSKAokTkFUSVZFX1dPUktMT0FEX0xJRkVUSU1FX1VOU1BFQ0lGSUVEEAASJwojTkFUSVZFX1dPUktMT0FEX0xJRkVUSU1FX1BFUlNJU1RFTlQQARImCiJOQVRJVkVfV09SS0xPQURfTElGRVRJTUVfRVBIRU1FUkFMEAJiBnByb3RvMw", [file_dotcore_application_v1_deployment, file_dotcore_catalog_v1_oci, file_dotcore_inference_v1_routes, file_dotcore_model_v1_deployment]); /** * Complete desired site configuration stored in site.yaml. Catalog records, @@ -77,11 +77,11 @@ export type Site = Message<"dotcore.site.v1.Site"> & { hardwareObservation?: HardwareObservationConfiguration; /** - * Inference-controller-owned allocation state for never-reused model deployment IDs. + * Site-owned allocation state for never-reused model and application deployment IDs. * - * @generated from field: dotcore.site.v1.ModelDeploymentIdentityAllocator model_deployment_identity_allocator = 8; + * @generated from field: dotcore.site.v1.DeploymentIdentityAllocator deployment_identity_allocator = 8; */ - modelDeploymentIdentityAllocator?: ModelDeploymentIdentityAllocator; + deploymentIdentityAllocator?: DeploymentIdentityAllocator; /** * Site-wide console settings shared by every browser; never part of node desired views. @@ -120,17 +120,17 @@ export const ConsoleSettingsSchema: GenMessage = /*@__PURE__*/ messageDesc(file_dotcore_site_v1_site, 1); /** - * Durable allocator for model deployment identities within this site. + * Durable allocator for the deployment IDs of every kind within this site. * - * @generated from message dotcore.site.v1.ModelDeploymentIdentityAllocator + * @generated from message dotcore.site.v1.DeploymentIdentityAllocator */ -export type ModelDeploymentIdentityAllocator = Message<"dotcore.site.v1.ModelDeploymentIdentityAllocator"> & { +export type DeploymentIdentityAllocator = Message<"dotcore.site.v1.DeploymentIdentityAllocator"> & { /** - * Fixed lowercase hexadecimal namespace separating new IDs from legacy IDs. + * Random 16-digit lowercase hexadecimal key, chosen at site creation, scrambling ID suffixes. * - * @generated from field: string namespace = 1; + * @generated from field: string suffix_key = 1; */ - namespace: string; + suffixKey: string; /** * Next sequence to reserve; values below it are never reused. @@ -141,10 +141,10 @@ export type ModelDeploymentIdentityAllocator = Message<"dotcore.site.v1.ModelDep }; /** - * Describes the message dotcore.site.v1.ModelDeploymentIdentityAllocator. - * Use `create(ModelDeploymentIdentityAllocatorSchema)` to create a new message. + * Describes the message dotcore.site.v1.DeploymentIdentityAllocator. + * Use `create(DeploymentIdentityAllocatorSchema)` to create a new message. */ -export const ModelDeploymentIdentityAllocatorSchema: GenMessage = /*@__PURE__*/ +export const DeploymentIdentityAllocatorSchema: GenMessage = /*@__PURE__*/ messageDesc(file_dotcore_site_v1_site, 2); /** diff --git a/proto/dotcore/model/v1/deployment.proto b/proto/dotcore/model/v1/deployment.proto index f10bc87b..55095ddf 100644 --- a/proto/dotcore/model/v1/deployment.proto +++ b/proto/dotcore/model/v1/deployment.proto @@ -315,7 +315,7 @@ message UpstreamModelDeploymentSnapshot { // Generation-scoped configuration of one OpenAI-compatible upstream model. message UpstreamModelDesiredConfiguration { - // Private model identifier sent in endpoint requests. + // Model identifier sent in endpoint requests; it also names the deployment's ID. string upstream_model_id = 1; // Optional POC credential retained in desired site configuration. diff --git a/proto/dotcore/site/v1/site.proto b/proto/dotcore/site/v1/site.proto index 6bf38115..e347a806 100644 --- a/proto/dotcore/site/v1/site.proto +++ b/proto/dotcore/site/v1/site.proto @@ -31,8 +31,8 @@ message Site { // Site-wide current hardware observation policy. HardwareObservationConfiguration hardware_observation = 7; - // Inference-controller-owned allocation state for never-reused model deployment IDs. - ModelDeploymentIdentityAllocator model_deployment_identity_allocator = 8; + // Site-owned allocation state for never-reused model and application deployment IDs. + DeploymentIdentityAllocator deployment_identity_allocator = 8; // Site-wide console settings shared by every browser; never part of node desired views. ConsoleSettings console_settings = 9; @@ -44,10 +44,10 @@ message ConsoleSettings { bool get_started_hidden = 1; } -// Durable allocator for model deployment identities within this site. -message ModelDeploymentIdentityAllocator { - // Fixed lowercase hexadecimal namespace separating new IDs from legacy IDs. - string namespace = 1; +// Durable allocator for the deployment IDs of every kind within this site. +message DeploymentIdentityAllocator { + // Random 16-digit lowercase hexadecimal key, chosen at site creation, scrambling ID suffixes. + string suffix_key = 1; // Next sequence to reserve; values below it are never reused. uint64 next_sequence = 2; From b5a3a85ce4c51535234ff22ca72511cb090f1dbf Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 11:25:23 -0500 Subject: [PATCH 02/19] test(frontend): follow the deployment identity allocator rename --- frontend/src/test/catalog-model-site-contract.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/test/catalog-model-site-contract.test.ts b/frontend/src/test/catalog-model-site-contract.test.ts index 5ae9ece4..81c62a55 100644 --- a/frontend/src/test/catalog-model-site-contract.test.ts +++ b/frontend/src/test/catalog-model-site-contract.test.ts @@ -397,7 +397,7 @@ describe("desired site and current-state contracts", () => { "application_deployments", "inference_routes", "hardware_observation", - "model_deployment_identity_allocator", + "deployment_identity_allocator", "console_settings", ]); expect(fieldNames(executionTarget)).toEqual([ From d1994b8e2d521a7f9adf8edaea9a9daa7d1715e0 Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 11:25:23 -0500 Subject: [PATCH 03/19] feat(backend): readable never-reused deployment ids --- .../src/application/controller/identity.rs | 170 ------------ .../core/src/application/controller/mod.rs | 1 - .../src/application/controller/operations.rs | 15 +- .../application/controller/test_support.rs | 25 +- .../core/src/application/controller/tests.rs | 34 --- backend/core/src/application/repository.rs | 15 ++ .../core/src/model/controller/node_targets.rs | 4 +- .../src/model/controller/remote_status.rs | 4 +- .../core/src/model/controller/test_support.rs | 6 +- backend/core/src/model/repository.rs | 34 +-- backend/core/src/route_manager/repository.rs | 2 +- backend/core/src/test_support/mod.rs | 6 +- .../core/tests/backend/backend_integration.rs | 25 +- .../tests/backend/route_exposure_integrity.rs | 2 +- .../tests/backend/upstream_integration.rs | 5 +- .../tests/transport/openai_compatibility.rs | 14 +- backend/fixtures/docker-apps-site/site.yaml | 4 +- .../fixtures/llama-cpp-nvidia-site/site.yaml | 4 +- backend/fixtures/ninfer-nvidia-site/site.yaml | 4 +- backend/fixtures/nvidia-site/site.yaml | 4 +- .../fixtures/simulated-docker-site/site.yaml | 4 +- backend/fixtures/simulated-site/site.yaml | 4 +- backend/fixtures/two-node-site/site.yaml | 4 +- backend/fixtures/vllm-nvidia-site/site.yaml | 4 +- backend/proto/tests/application_contract.rs | 2 +- backend/proto/tests/site_contract.rs | 2 +- backend/site/src/deployment_identity.rs | 252 ++++++++++++++++++ backend/site/src/initial/inputs.rs | 10 +- backend/site/src/initial/request.rs | 85 +++++- backend/site/src/initial/validation.rs | 2 +- backend/site/src/lib.rs | 1 + backend/site/src/membership/removal.rs | 7 +- backend/site/src/node/stream/tests.rs | 4 +- backend/site/src/repository/mod.rs | 43 +-- backend/site/src/repository/tests.rs | 70 ++++- backend/site/src/store/mod.rs | 14 - backend/site/src/store/site/mod.rs | 10 +- backend/site/src/test_support/mod.rs | 6 +- backend/site/src/validation.rs | 18 +- backend/site/src/view/desired/tests.rs | 10 +- backend/site/src/worker_channels.rs | 4 +- docs/specs/inference.md | 6 +- docs/specs/models.md | 2 +- 43 files changed, 542 insertions(+), 400 deletions(-) delete mode 100644 backend/core/src/application/controller/identity.rs create mode 100644 backend/site/src/deployment_identity.rs diff --git a/backend/core/src/application/controller/identity.rs b/backend/core/src/application/controller/identity.rs deleted file mode 100644 index 247b11d0..00000000 --- a/backend/core/src/application/controller/identity.rs +++ /dev/null @@ -1,170 +0,0 @@ -//! Apps-controller immutable deployment identity allocation. - -use std::time::{SystemTime, UNIX_EPOCH}; - -use dotcore_domain::valid_id; - -use super::{ApplicationLifecycleError, configuration, configuration_with_source}; - -/// Produces a cryptographically random bounded deployment-ID suffix. -pub(super) fn random_collision_suffix() -> Result { - let mut bytes = [0_u8; 5]; - getrandom::fill(&mut bytes).map_err(|source| { - configuration_with_source("Application identity entropy failed", EntropyError(source)) - })?; - Ok(bytes - .into_iter() - .fold(0_u64, |value, byte| (value << 8) | u64::from(byte))) -} - -/// Allocates an immutable deployment identity that no declaration uses. The hosting node fails -/// closed on application data it holds under an identity without ownership evidence. -pub(super) fn allocate_deployment_id<'a>( - application_id: &str, - now: SystemTime, - existing_ids: impl IntoIterator, - suffixes: impl IntoIterator>, -) -> Result { - let duration = now.duration_since(UNIX_EPOCH).map_err(|source| { - configuration_with_source("System clock is before the Unix epoch", source) - })?; - let timestamp = deployment_id_timestamp(duration)?; - let association = deployment_id_association(application_id); - let existing_ids = existing_ids - .into_iter() - .collect::>(); - for suffix in suffixes { - let id = format!( - "{association}-{timestamp}-{:010x}", - suffix? & 0xff_ffff_ffff - ); - if id.len() <= 40 && valid_id(&id) && !existing_ids.contains(id.as_str()) { - return Ok(id); - } - } - Err(configuration( - "Application deployment ID allocation exhausted collision retries", - )) -} - -#[derive(Debug, thiserror::Error)] -#[error("{0}")] -struct EntropyError(getrandom::Error); - -fn deployment_id_timestamp( - duration: std::time::Duration, -) -> Result { - let seconds = i64::try_from(duration.as_secs()).map_err(|_| { - configuration("System clock timestamp exceeds the supported signed Unix timestamp range") - })?; - let timestamp = time::OffsetDateTime::from_unix_timestamp(seconds).map_err(|source| { - configuration_with_source("System clock is after the supported UTC date range", source) - })?; - Ok(format!( - "{:02}{:02}{:02}t{:02}{:02}{:02}z", - timestamp.year().rem_euclid(100), - u8::from(timestamp.month()), - timestamp.day(), - timestamp.hour(), - timestamp.minute(), - timestamp.second() - )) -} - -fn deployment_id_association(application_id: &str) -> String { - const MAX_ASSOCIATION_LENGTH: usize = 14; - if application_id.len() <= MAX_ASSOCIATION_LENGTH { - return application_id.to_owned(); - } - let mut hash = 0x811c9dc5_u32; - for byte in application_id.bytes() { - hash ^= u32::from(byte); - hash = hash.wrapping_mul(0x01000193); - } - format!("{}-{:05x}", &application_id[..8], hash & 0x0f_ffff) -} - -#[cfg(test)] -mod tests { - use std::time::{Duration, UNIX_EPOCH}; - - use super::{allocate_deployment_id, deployment_id_timestamp}; - - #[test] - fn deployment_id_timestamp_formats_utc_calendar_boundaries() { - assert_eq!( - deployment_id_timestamp(Duration::from_secs(0)).expect("Unix epoch"), - "700101t000000z" - ); - assert_eq!( - deployment_id_timestamp(Duration::from_secs(951_782_400)).expect("leap day"), - "000229t000000z" - ); - assert_eq!( - deployment_id_timestamp(Duration::from_secs(4_107_542_400)).expect("non-leap year"), - "000301t000000z" - ); - assert_eq!( - deployment_id_timestamp(Duration::from_secs(946_684_799)).expect("year end"), - "991231t235959z" - ); - assert_eq!( - deployment_id_timestamp(Duration::from_secs(946_684_800)).expect("year rollover"), - "000101t000000z" - ); - assert_eq!( - deployment_id_timestamp(Duration::from_secs(86_399)).expect("day end"), - "700101t235959z" - ); - assert_eq!( - deployment_id_timestamp(Duration::from_secs(86_400)).expect("next day"), - "700102t000000z" - ); - assert_eq!( - deployment_id_timestamp(Duration::new(1, 999_999_999)).expect("truncate nanos"), - "700101t000001z" - ); - } - - #[test] - fn allocate_deployment_id_reports_pre_epoch_clock_context() { - let error = allocate_deployment_id( - "application", - UNIX_EPOCH - Duration::from_secs(1), - std::iter::empty(), - std::iter::empty(), - ) - .expect_err("pre-epoch clock"); - - assert_eq!( - error.to_string(), - "Application lifecycle configuration failed: System clock is before the Unix epoch" - ); - let crate::application::controller::ApplicationLifecycleError::Configuration(source) = - error - else { - panic!("expected configuration error"); - }; - assert_eq!( - source.root_cause().to_string(), - "second time provided was later than self" - ); - } - - #[test] - fn deployment_id_timestamp_rejects_unsupported_ranges() { - let seconds_overflow = deployment_id_timestamp(Duration::new(i64::MAX as u64 + 1, 0)) - .expect_err("seconds beyond signed range"); - assert_eq!( - seconds_overflow.to_string(), - "Application lifecycle configuration failed: System clock timestamp exceeds the supported signed Unix timestamp range" - ); - - let date_overflow = deployment_id_timestamp(Duration::new(i64::MAX as u64, 0)) - .expect_err("timestamp beyond UTC date range"); - assert_eq!( - date_overflow.to_string(), - "Application lifecycle configuration failed: System clock is after the supported UTC date range" - ); - } -} diff --git a/backend/core/src/application/controller/mod.rs b/backend/core/src/application/controller/mod.rs index caf6d670..1b111200 100644 --- a/backend/core/src/application/controller/mod.rs +++ b/backend/core/src/application/controller/mod.rs @@ -10,7 +10,6 @@ mod accelerator_memory; mod crash; mod errors; -mod identity; mod launch; mod logs; mod metrics; diff --git a/backend/core/src/application/controller/operations.rs b/backend/core/src/application/controller/operations.rs index 77c0a3a9..3f653523 100644 --- a/backend/core/src/application/controller/operations.rs +++ b/backend/core/src/application/controller/operations.rs @@ -2,7 +2,7 @@ use std::sync::Arc; -use dotcore_domain::{SiteNodeId, diagnostic::diagnostic_chain, real_time}; +use dotcore_domain::{SiteNodeId, diagnostic::diagnostic_chain}; use dotcore_proto::dotcore::{ application::v1::{ ApplicationDeploymentDeclaration, ApplicationDeploymentDesiredState, @@ -632,15 +632,10 @@ where ) .map_err(ApplicationLifecycleError::InferenceRoute)?; } - let deployment_id = super::identity::allocate_deployment_id( - &application.application_id, - real_time::wall_now(), - snapshot - .deployments - .iter() - .map(|deployment| deployment.application_deployment_id.as_str()), - (0..32).map(|_| super::identity::random_collision_suffix()), - )?; + let deployment_id = owner + .desired + .reserve_deployment_id(&application.application_id) + .map_err(declaration_error)?; let published_port = allocate_published_port( PUBLISHED_PORT_RANGE, deployment_start_offset(&deployment_id), diff --git a/backend/core/src/application/controller/test_support.rs b/backend/core/src/application/controller/test_support.rs index 2113657e..b0d463be 100644 --- a/backend/core/src/application/controller/test_support.rs +++ b/backend/core/src/application/controller/test_support.rs @@ -192,6 +192,7 @@ pub(super) struct TestApplicationDeclarationRepository { pub(super) resume_failure: Arc>>, pub(super) listener: Arc, pub(super) execution_targets: Arc>>, + pub(super) next_identity_sequence: Arc>, } #[derive(Clone, Copy)] @@ -223,6 +224,7 @@ impl TestApplicationDeclarationRepository { resume_failure: Arc::new(Mutex::new(None)), listener: Arc::new(Notify::new()), execution_targets: Arc::new(Mutex::new(vec![application_execution_target()])), + next_identity_sequence: Arc::new(Mutex::new(1)), }) } @@ -283,6 +285,19 @@ impl ApplicationDeclarationRepository for TestApplicationDeclarationRepository { ) } + fn reserve_deployment_id( + &self, + application_id: &str, + ) -> Result { + let mut sequence = self + .next_identity_sequence + .lock() + .map_err(|_| ApplicationRepositoryError::Unavailable)?; + let deployment_id = format!("{application_id}-{:05}", *sequence); + *sequence += 1; + Ok(deployment_id) + } + fn upsert( &self, deployment: ApplicationDeploymentDeclaration, @@ -768,9 +783,9 @@ pub(super) fn write_lifecycle_site( ) -> std::path::PathBuf { let path = directory.join("site.yaml"); let mut persisted = site(); - persisted.model_deployment_identity_allocator = Some( - dotcore_proto::dotcore::site::v1::ModelDeploymentIdentityAllocator { - namespace: "0123456789abcdef".to_owned(), + persisted.deployment_identity_allocator = Some( + dotcore_proto::dotcore::site::v1::DeploymentIdentityAllocator { + suffix_key: "0123456789abcdef".to_owned(), next_sequence: 1, }, ); @@ -3289,7 +3304,7 @@ pub(super) fn application() -> Application { pub(super) fn site() -> Site { Site { site_id: "site-one".to_owned(), - model_deployment_identity_allocator: Some(crate::test_support::identity_allocator()), + deployment_identity_allocator: Some(crate::test_support::identity_allocator()), nodes: vec![SiteNode { node_id: "node-one".to_owned(), host: "127.0.0.1".to_owned(), @@ -3341,7 +3356,7 @@ pub(super) fn node_site(deployments: Vec) -> S manager_target.site_node_id = "manager-node".to_owned(); Site { site_id: "site-one".to_owned(), - model_deployment_identity_allocator: Some(crate::test_support::identity_allocator()), + deployment_identity_allocator: Some(crate::test_support::identity_allocator()), nodes: vec![ SiteNode { node_id: "manager-node".to_owned(), diff --git a/backend/core/src/application/controller/tests.rs b/backend/core/src/application/controller/tests.rs index 338d38b7..360bc383 100644 --- a/backend/core/src/application/controller/tests.rs +++ b/backend/core/src/application/controller/tests.rs @@ -7,7 +7,6 @@ use std::{ Arc, Mutex, atomic::{AtomicUsize, Ordering}, }, - time::UNIX_EPOCH, }; use dotcore_catalog::{CatalogBuilder, OciArtifactPolicy}; @@ -74,7 +73,6 @@ use dotcore_site::{ use tokio::{io::AsyncWriteExt, sync::Notify}; use tonic::Request; -use super::identity::allocate_deployment_id; use super::launch::{configuration_attachments, secret_attachments}; use super::launch::{deployment_data, workload_group_launch}; use super::observation::{exact_owned_observation, stale_owned_group}; @@ -3787,38 +3785,6 @@ fn display_name_never_changes_runtime_identity_or_generation() { assert_eq!(first_launch.correlation, renamed_launch.correlation); } -#[test] -fn deployment_id_is_bounded_and_retries_declared_collisions() { - let now = UNIX_EPOCH + Duration::from_secs(1_786_543_445); - let active = allocate_deployment_id( - "application-with-the-longest-valid-identifier-01234567890123456789", - now, - std::iter::empty(), - [Ok(0x12_ab_cd_ef_01)], - ) - .expect("bounded deployment ID"); - let allocated = allocate_deployment_id( - "application-with-the-longest-valid-identifier-01234567890123456789", - now, - [active.as_str()], - [Ok(0x12_ab_cd_ef_01), Ok(0x12_ab_cd_ef_02)], - ) - .expect("collision retry"); - - assert_eq!(active.len(), 40); - assert!(active.starts_with("applicat-")); - let without_suffix = active.rsplit_once('-').expect("suffix").0; - assert_eq!( - without_suffix.rsplit_once('-').expect("timestamp").1.len(), - 14 - ); - assert!(active.ends_with("-12abcdef01")); - assert!( - allocated.ends_with("-12abcdef02"), - "a declared identity is never allocated again" - ); -} - #[test] fn configuration_attachments_preserve_empty_literals_and_resolve_named_values() { let mut application = application(); diff --git a/backend/core/src/application/repository.rs b/backend/core/src/application/repository.rs index 56a30391..6e95f7ed 100644 --- a/backend/core/src/application/repository.rs +++ b/backend/core/src/application/repository.rs @@ -68,6 +68,13 @@ pub struct ApplicationRepositoryMutation { pub(crate) trait ApplicationDeclarationRepository: Send + Sync { fn snapshot(&self) -> Result; + /// Durably reserves a never-reused identity for a new deployment of `application_id`. A + /// reserved identity is burned even when the deployment is never accepted. + fn reserve_deployment_id( + &self, + application_id: &str, + ) -> Result; + fn upsert( &self, deployment: ApplicationDeploymentDeclaration, @@ -206,6 +213,14 @@ impl ApplicationDeclarationRepository for SiteRepository { }) } + fn reserve_deployment_id( + &self, + application_id: &str, + ) -> Result { + SiteRepository::reserve_deployment_id(self, &[application_id]) + .map_err(site_repository_error) + } + fn upsert( &self, deployment: ApplicationDeploymentDeclaration, diff --git a/backend/core/src/model/controller/node_targets.rs b/backend/core/src/model/controller/node_targets.rs index 380e7485..07941ebf 100644 --- a/backend/core/src/model/controller/node_targets.rs +++ b/backend/core/src/model/controller/node_targets.rs @@ -1290,8 +1290,8 @@ mod tests { const MANAGER_NODE_ID: &str = "manager-node"; const MANAGER_SITE: &str = r#"siteId: site-one -modelDeploymentIdentityAllocator: - namespace: 0123456789abcdef +deploymentIdentityAllocator: + suffixKey: 0123456789abcdef nextSequence: '1' nodes: - nodeId: manager-node diff --git a/backend/core/src/model/controller/remote_status.rs b/backend/core/src/model/controller/remote_status.rs index b5e84ab4..6464f9fd 100644 --- a/backend/core/src/model/controller/remote_status.rs +++ b/backend/core/src/model/controller/remote_status.rs @@ -1815,8 +1815,8 @@ mod tests { } const MANAGER_SITE: &str = r#"siteId: site-one -modelDeploymentIdentityAllocator: - namespace: 0123456789abcdef +deploymentIdentityAllocator: + suffixKey: 0123456789abcdef nextSequence: '1' nodes: - nodeId: manager-node diff --git a/backend/core/src/model/controller/test_support.rs b/backend/core/src/model/controller/test_support.rs index c2af3228..858128fe 100644 --- a/backend/core/src/model/controller/test_support.rs +++ b/backend/core/src/model/controller/test_support.rs @@ -952,9 +952,9 @@ impl CurrentStateRepository for TestCurrent { pub(super) fn test_site() -> Site { Site { site_id: "site-one".to_owned(), - model_deployment_identity_allocator: Some( - dotcore_proto::dotcore::site::v1::ModelDeploymentIdentityAllocator { - namespace: "0123456789abcdef".to_owned(), + deployment_identity_allocator: Some( + dotcore_proto::dotcore::site::v1::DeploymentIdentityAllocator { + suffix_key: "0123456789abcdef".to_owned(), next_sequence: 1, }, ), diff --git a/backend/core/src/model/repository.rs b/backend/core/src/model/repository.rs index be5a1e21..a004f5e7 100644 --- a/backend/core/src/model/repository.rs +++ b/backend/core/src/model/repository.rs @@ -183,7 +183,7 @@ impl ModelDeclarationRepository { exposure: &ModelDeploymentExposureIntent, name: Option<&str>, ) -> Result { - let deployment_id = self.site.reserve_model_deployment_id()?; + let deployment_id = self.site.reserve_deployment_id(&[model_id])?; let snapshot = self.site.model_snapshot()?; let mut deployment = self.resolve_model_deployment( &snapshot, @@ -342,7 +342,14 @@ impl ModelDeclarationRepository { request.upstream_model_template_id.clone(), ) })?; - let deployment_id = self.site.reserve_model_deployment_id()?; + // The upstream model name reads best; the template names deployments of unnamed models. + let upstream_model_id = request + .desired_configuration + .as_ref() + .map_or("", |configuration| configuration.upstream_model_id.as_str()); + let deployment_id = self + .site + .reserve_deployment_id(&[upstream_model_id, &request.upstream_model_template_id])?; let lifecycle_generation = self.reserve_initial_generation(&deployment_id)?; let deployment = ModelDeploymentDeclaration { model_deployment_id: deployment_id, @@ -1914,14 +1921,7 @@ mod tests { Some("Preview parity"), ) .expect("created deployment"); - let allocator = before - .model_deployment_identity_allocator - .as_ref() - .expect("upgraded identity allocator"); - assert_eq!( - created.model_deployment_id, - format!("model-{}-1", allocator.namespace) - ); + assert_eq!(created.model_deployment_id, "fixture-model-e9dcf"); assert_eq!(created.lifecycle_generation, 1); assert_eq!( created.lifecycle_transition, @@ -1940,7 +1940,7 @@ mod tests { ); assert_eq!( after - .model_deployment_identity_allocator + .deployment_identity_allocator .expect("persisted identity allocator") .next_sequence, 2 @@ -2702,7 +2702,7 @@ mod tests { .expect("Site after restart"); assert_ne!( restarted_site - .reserve_model_deployment_id() + .reserve_deployment_id(&["fixture-model"]) .expect("next identity"), deployment_id ); @@ -2716,12 +2716,6 @@ mod tests { fs::copy(fixture_root.join("site.yaml"), &site_path).expect("simulated site fixture"); let site = SiteRepository::load(&site_path, crate::test_support::site_declaration_rules()) .expect("validated simulated site"); - let namespace = site - .snapshot() - .expect("Site before failed creation") - .model_deployment_identity_allocator - .expect("identity allocator") - .namespace; let catalog = Arc::new( Catalog::load_with_policy( &fixture_root.join("catalog"), @@ -2765,9 +2759,9 @@ mod tests { .expect("Site after restart"); assert_eq!( restarted - .reserve_model_deployment_id() + .reserve_deployment_id(&["fixture-model"]) .expect("next durable reservation"), - format!("model-{namespace}-2") + "fixture-model-m3ggc" ); } diff --git a/backend/core/src/route_manager/repository.rs b/backend/core/src/route_manager/repository.rs index 1937c41f..9c6dd4e1 100644 --- a/backend/core/src/route_manager/repository.rs +++ b/backend/core/src/route_manager/repository.rs @@ -482,7 +482,7 @@ mod tests { site_manager: Some(SiteManagerRole {}), manager_host: String::new(), }], - model_deployment_identity_allocator: Some(crate::test_support::identity_allocator()), + deployment_identity_allocator: Some(crate::test_support::identity_allocator()), execution_targets: vec![ ExecutionTarget { execution_target_id: "target-one".to_owned(), diff --git a/backend/core/src/test_support/mod.rs b/backend/core/src/test_support/mod.rs index 54f016c4..f3d20508 100644 --- a/backend/core/src/test_support/mod.rs +++ b/backend/core/src/test_support/mod.rs @@ -213,7 +213,7 @@ pub(crate) fn routed_site(deployment_ids: &[&str]) -> dotcore_proto::dotcore::si ModelDeploymentLifecycleTransition, }, site::v1::{ - ExecutionTarget, ModelDeploymentIdentityAllocator, ModelRuntimeBinding, + DeploymentIdentityAllocator, ExecutionTarget, ModelRuntimeBinding, SimulatedRuntimeAdapter, SimulatedRuntimeScenario, Site, SiteManagerRole, SiteNode, execution_target, model_runtime_binding, }, @@ -242,8 +242,8 @@ pub(crate) fn routed_site(deployment_ids: &[&str]) -> dotcore_proto::dotcore::si site_manager: Some(SiteManagerRole {}), manager_host: String::new(), }], - model_deployment_identity_allocator: Some(ModelDeploymentIdentityAllocator { - namespace: "0123456789abcdef".to_owned(), + deployment_identity_allocator: Some(DeploymentIdentityAllocator { + suffix_key: "0123456789abcdef".to_owned(), next_sequence: 3, }), execution_targets: vec![ExecutionTarget { diff --git a/backend/core/tests/backend/backend_integration.rs b/backend/core/tests/backend/backend_integration.rs index 24c4368f..4a1d7f9a 100644 --- a/backend/core/tests/backend/backend_integration.rs +++ b/backend/core/tests/backend/backend_integration.rs @@ -3108,7 +3108,7 @@ async fn application_service_persists_its_snapshot_name_and_logical_storage_unti } #[tokio::test] -async fn application_service_assigns_timestamped_ids_while_permitting_duplicate_display_names() { +async fn application_service_assigns_readable_ids_while_permitting_duplicate_display_names() { let root = support::temporary_fast_fixture(); let service = application_service_for(&application_lifecycle_configuration(&root)) .await @@ -3157,25 +3157,8 @@ async fn application_service_assigns_timestamped_ids_while_permitting_duplicate_ assert_eq!(first.application_deployment_name, "Open WebUI"); assert_eq!(second.application_deployment_name, "Open WebUI"); - assert_ne!( - first.application_deployment_id, - second.application_deployment_id - ); - for deployment_id in [ - &first.application_deployment_id, - &second.application_deployment_id, - ] { - assert!(deployment_id.starts_with("open-webui-")); - let (_, suffix) = deployment_id - .rsplit_once('-') - .expect("deployment ID suffix"); - assert_eq!(suffix.len(), 10); - assert!( - suffix - .chars() - .all(|character| character.is_ascii_hexdigit()) - ); - } + assert_eq!(first.application_deployment_id, "open-webui-e9dcf"); + assert_eq!(second.application_deployment_id, "open-webui-m3ggc"); let site = fs::read_to_string(root.join("site.yaml")).expect("declarative site"); assert_eq!( @@ -4176,7 +4159,7 @@ async fn simulated_stop_delay_uses_the_deployment_override() { &site_path, source.replace( FAST_TEST_SCENARIO, - "defaultScenario:\n readyDelayMillis: 0\n stopDelayMillis: 3600000\n deploymentScenarios:\n - modelDeploymentId: model-d44bc5d823b11591-1\n scenario:\n stopDelayMillis: 0", + "defaultScenario:\n readyDelayMillis: 0\n stopDelayMillis: 3600000\n deploymentScenarios:\n - modelDeploymentId: fixture-model-e9dcf\n scenario:\n stopDelayMillis: 0", ), ) .expect("stop-delay fixture"); diff --git a/backend/core/tests/backend/route_exposure_integrity.rs b/backend/core/tests/backend/route_exposure_integrity.rs index 666f95e8..d2f71778 100644 --- a/backend/core/tests/backend/route_exposure_integrity.rs +++ b/backend/core/tests/backend/route_exposure_integrity.rs @@ -205,7 +205,7 @@ async fn local_deployments_are_independent_and_a_conflicting_route_is_atomic() { ); let mut expected = accepted_site; expected - .model_deployment_identity_allocator + .deployment_identity_allocator .as_mut() .expect("deployment identity allocator") .next_sequence += 1; diff --git a/backend/core/tests/backend/upstream_integration.rs b/backend/core/tests/backend/upstream_integration.rs index 4715914c..c8b5a7d1 100644 --- a/backend/core/tests/backend/upstream_integration.rs +++ b/backend/core/tests/backend/upstream_integration.rs @@ -2212,7 +2212,10 @@ fn assert_management_deployment(deployment: &ModelDeployment) { .as_ref() .expect("trusted POC upstream configuration"); assert_eq!(configuration.api_key, CREDENTIAL); - assert_eq!(deployment.model_deployment_id, "model-d44bc5d823b11591-1"); + assert_eq!( + deployment.model_deployment_id, + "upstream-private-model-e9dcf" + ); assert!(matches!( deployment .snapshot diff --git a/backend/core/tests/transport/openai_compatibility.rs b/backend/core/tests/transport/openai_compatibility.rs index de62f252..4182c54b 100644 --- a/backend/core/tests/transport/openai_compatibility.rs +++ b/backend/core/tests/transport/openai_compatibility.rs @@ -2155,8 +2155,8 @@ impl EngineRouter { .count() } - /// Asserts that no backend log line carries a payload value, credential, private model - /// id, or private endpoint. + /// Asserts that no backend log line carries a payload value, credential, or private + /// endpoint. The upstream model ID isn't private: it names the deployment's ID. fn assert_backend_logs_private(&self, sentinels: &[&str]) { let output = trace_capture() .output @@ -2170,11 +2170,11 @@ impl EngineRouter { "the route's requests must have produced backend log lines" ); for line in output.lines().filter(|line| line.contains(self.route)) { - for private in sentinels.iter().copied().chain([ - ENGINE_MODEL, - ENGINE_CREDENTIAL, - endpoint.as_str(), - ]) { + for private in sentinels + .iter() + .copied() + .chain([ENGINE_CREDENTIAL, endpoint.as_str()]) + { assert!( !line.contains(private), "{private} leaked into a log line: {line}" diff --git a/backend/fixtures/docker-apps-site/site.yaml b/backend/fixtures/docker-apps-site/site.yaml index 3d5e6d25..523d31ed 100644 --- a/backend/fixtures/docker-apps-site/site.yaml +++ b/backend/fixtures/docker-apps-site/site.yaml @@ -12,6 +12,6 @@ executionTargets: applicationRuntime: { dockerRuntime: {} } modelDeployments: [] applicationDeployments: [] -modelDeploymentIdentityAllocator: - namespace: 7a6394dbd848c6f6 +deploymentIdentityAllocator: + suffixKey: 7a6394dbd848c6f6 nextSequence: '1' diff --git a/backend/fixtures/llama-cpp-nvidia-site/site.yaml b/backend/fixtures/llama-cpp-nvidia-site/site.yaml index 9e50f407..4b7e9b0f 100644 --- a/backend/fixtures/llama-cpp-nvidia-site/site.yaml +++ b/backend/fixtures/llama-cpp-nvidia-site/site.yaml @@ -15,6 +15,6 @@ executionTargets: acceleratorTransport: "DOCKER_ACCELERATOR_TRANSPORT_CDI" modelDeployments: [] applicationDeployments: [] -modelDeploymentIdentityAllocator: - namespace: 0123456789abcdef +deploymentIdentityAllocator: + suffixKey: 0123456789abcdef nextSequence: '1' diff --git a/backend/fixtures/ninfer-nvidia-site/site.yaml b/backend/fixtures/ninfer-nvidia-site/site.yaml index e7050a6a..b8bae420 100644 --- a/backend/fixtures/ninfer-nvidia-site/site.yaml +++ b/backend/fixtures/ninfer-nvidia-site/site.yaml @@ -15,6 +15,6 @@ executionTargets: acceleratorTransport: "DOCKER_ACCELERATOR_TRANSPORT_CDI" modelDeployments: [] applicationDeployments: [] -modelDeploymentIdentityAllocator: - namespace: b79f586d25443bdc +deploymentIdentityAllocator: + suffixKey: b79f586d25443bdc nextSequence: '1' diff --git a/backend/fixtures/nvidia-site/site.yaml b/backend/fixtures/nvidia-site/site.yaml index 179021db..908fcb93 100644 --- a/backend/fixtures/nvidia-site/site.yaml +++ b/backend/fixtures/nvidia-site/site.yaml @@ -20,6 +20,6 @@ executionTargets: applicationRuntime: { dockerRuntime: {} } modelDeployments: [] applicationDeployments: [] -modelDeploymentIdentityAllocator: - namespace: ad7f829b823ce71e +deploymentIdentityAllocator: + suffixKey: ad7f829b823ce71e nextSequence: '1' diff --git a/backend/fixtures/simulated-docker-site/site.yaml b/backend/fixtures/simulated-docker-site/site.yaml index 2c34ffbe..4b47b3e4 100644 --- a/backend/fixtures/simulated-docker-site/site.yaml +++ b/backend/fixtures/simulated-docker-site/site.yaml @@ -19,6 +19,6 @@ executionTargets: platform: { operatingSystem: linux, architecture: amd64 } applicationRuntime: { dockerRuntime: {} } applicationDeployments: [] -modelDeploymentIdentityAllocator: - namespace: 509dc0459d436713 +deploymentIdentityAllocator: + suffixKey: 509dc0459d436713 nextSequence: '1' diff --git a/backend/fixtures/simulated-site/site.yaml b/backend/fixtures/simulated-site/site.yaml index 67b91391..2d618cc3 100644 --- a/backend/fixtures/simulated-site/site.yaml +++ b/backend/fixtures/simulated-site/site.yaml @@ -23,6 +23,6 @@ executionTargets: simulatedRuntime: {} modelDeployments: [] applicationDeployments: [] -modelDeploymentIdentityAllocator: - namespace: d44bc5d823b11591 +deploymentIdentityAllocator: + suffixKey: d44bc5d823b11591 nextSequence: '1' diff --git a/backend/fixtures/two-node-site/site.yaml b/backend/fixtures/two-node-site/site.yaml index 04499e61..727c618e 100644 --- a/backend/fixtures/two-node-site/site.yaml +++ b/backend/fixtures/two-node-site/site.yaml @@ -36,6 +36,6 @@ executionTargets: applicationRuntime: { simulatedRuntime: {} } modelDeployments: [] applicationDeployments: [] -modelDeploymentIdentityAllocator: - namespace: 83e8c24d8f4e7a49 +deploymentIdentityAllocator: + suffixKey: 83e8c24d8f4e7a49 nextSequence: '1' diff --git a/backend/fixtures/vllm-nvidia-site/site.yaml b/backend/fixtures/vllm-nvidia-site/site.yaml index f328bd94..de4b2c37 100644 --- a/backend/fixtures/vllm-nvidia-site/site.yaml +++ b/backend/fixtures/vllm-nvidia-site/site.yaml @@ -15,6 +15,6 @@ executionTargets: acceleratorTransport: "DOCKER_ACCELERATOR_TRANSPORT_CDI" modelDeployments: [] applicationDeployments: [] -modelDeploymentIdentityAllocator: - namespace: 57ed05b65395e4c3 +deploymentIdentityAllocator: + suffixKey: 57ed05b65395e4c3 nextSequence: '1' diff --git a/backend/proto/tests/application_contract.rs b/backend/proto/tests/application_contract.rs index 843eda9f..64617901 100644 --- a/backend/proto/tests/application_contract.rs +++ b/backend/proto/tests/application_contract.rs @@ -436,7 +436,7 @@ fn application_descriptors_define_portable_graph_and_owner_separated_records() { "application_deployments", "inference_routes", "hardware_observation", - "model_deployment_identity_allocator", + "deployment_identity_allocator", "console_settings", ] ); diff --git a/backend/proto/tests/site_contract.rs b/backend/proto/tests/site_contract.rs index 0c0a2581..ca7f8cac 100644 --- a/backend/proto/tests/site_contract.rs +++ b/backend/proto/tests/site_contract.rs @@ -739,7 +739,7 @@ fn generated_descriptors_preserve_site_inventory_contracts() { assert_eq!(field_number(site, "Site", "inference_routes"), 6); assert_eq!(field_number(site, "Site", "hardware_observation"), 7); assert_eq!( - field_number(site, "Site", "model_deployment_identity_allocator"), + field_number(site, "Site", "deployment_identity_allocator"), 8 ); assert_eq!( diff --git a/backend/site/src/deployment_identity.rs b/backend/site/src/deployment_identity.rs new file mode 100644 index 00000000..3cec50e4 --- /dev/null +++ b/backend/site/src/deployment_identity.rs @@ -0,0 +1,252 @@ +//! Readable deployment identities, such as `qwen3-8-27b-k3f9x` or `open-webui-7tq2m`. +//! +//! An identity is a short readable name of what is deployed followed by a five-character suffix. +//! The suffix alone carries uniqueness: it scrambles the site's next deployment sequence one-to-one +//! with the site's random key, so a site never issues the same identity twice and consecutive +//! identities look unrelated. Every identity fits the shared identifier grammar with room left for +//! the names runtimes derive from it. + +use sha2::{Digest, Sha256}; + +/// Longest deployment identity, in bytes, leaving room for derived names such as `-group`. +const MAX_DEPLOYMENT_ID_BYTES: usize = 40; + +/// Number of sequences one site can reserve: one per distinct five-character suffix. +const SEQUENCE_CAPACITY: u64 = 1 << SUFFIX_BITS; + +/// Readable part used when no source yields one. +const FALLBACK_SLUG: &str = "deployment"; + +const SUFFIX_LENGTH: usize = 5; +const MAX_SLUG_BYTES: usize = MAX_DEPLOYMENT_ID_BYTES - SUFFIX_LENGTH - 1; +const SUFFIX_BITS: u32 = 25; + +/// Crockford base32 in lowercase: no `i`, `l`, `o` or `u`, so suffixes stay unambiguous to read. +const SUFFIX_ALPHABET: &[u8; 32] = b"0123456789abcdefghjkmnpqrstvwxyz"; + +/// Feistel halves span 26 bits, one more than the suffix, and walk back into the suffix range. +const HALF_BITS: u32 = 13; +const HALF_MASK: u32 = (1 << HALF_BITS) - 1; +const FEISTEL_ROUNDS: u8 = 4; + +/// Formats the identity for `sequence` under `suffix_key`, named after the first of +/// `slug_sources` that yields a readable name. Returns `None` once the sequence is beyond the +/// site's capacity. +pub(crate) fn deployment_id( + slug_sources: &[&str], + suffix_key: u64, + sequence: u64, +) -> Option { + if sequence == 0 || sequence > SEQUENCE_CAPACITY { + return None; + } + let slug = slug_sources + .iter() + .find_map(|source| slug(source)) + .unwrap_or_else(|| FALLBACK_SLUG.to_owned()); + let index = u32::try_from(sequence - 1).ok()?; + Some(format!("{slug}-{}", suffix(scramble(suffix_key, index)))) +} + +/// Parses a stored suffix key: exactly 16 lowercase hexadecimal digits. +pub(crate) fn parse_suffix_key(value: &str) -> Option { + if value.len() != 16 + || !value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + return None; + } + u64::from_str_radix(value, 16).ok() +} + +/// Formats a suffix key the way the site stores it. +pub(crate) fn format_suffix_key(key: u64) -> String { + format!("{key:016x}") +} + +/// Lowercases `source`, turns every run of other characters than ASCII letters and digits into one +/// hyphen and cuts the result at a word boundary to fit the slug budget. Returns `None` unless the +/// result starts with a letter. +fn slug(source: &str) -> Option { + let mut slug = String::new(); + for character in source + .chars() + .map(|character| character.to_ascii_lowercase()) + { + if character.is_ascii_lowercase() || character.is_ascii_digit() { + slug.push(character); + } else if !slug.is_empty() && !slug.ends_with('-') { + slug.push('-'); + } + } + if slug.ends_with('-') { + slug.pop(); + } + if !slug.starts_with(|character: char| character.is_ascii_lowercase()) { + return None; + } + if slug.len() > MAX_SLUG_BYTES { + // A hyphen right after the budget still ends a whole word, so it is part of the search. + let cut = slug[..=MAX_SLUG_BYTES].rfind('-').unwrap_or(MAX_SLUG_BYTES); + slug.truncate(cut); + } + Some(slug) +} + +/// Maps `index` one-to-one onto the suffix range: a keyed Feistel network over 26 bits, repeated +/// until the value falls inside the 25-bit range (cycle walking keeps the mapping one-to-one). +fn scramble(key: u64, index: u32) -> u32 { + let mut value = index; + loop { + value = feistel(key, value); + if u64::from(value) < SEQUENCE_CAPACITY { + return value; + } + } +} + +fn feistel(key: u64, value: u32) -> u32 { + let (mut left, mut right) = (value >> HALF_BITS, value & HALF_MASK); + for round in 0..FEISTEL_ROUNDS { + (left, right) = (right, left ^ round_value(key, round, right)); + } + (left << HALF_BITS) | right +} + +fn round_value(key: u64, round: u8, half: u32) -> u32 { + let digest = Sha256::new() + .chain_update(b"dotcore.deployment-id-suffix.v1\0") + .chain_update(key.to_be_bytes()) + .chain_update([round]) + .chain_update(half.to_be_bytes()) + .finalize(); + u32::from(u16::from_be_bytes([digest[0], digest[1]])) & HALF_MASK +} + +fn suffix(value: u32) -> String { + (0..SUFFIX_LENGTH) + .rev() + .map(|position| char::from(SUFFIX_ALPHABET[(value >> (5 * position)) as usize & 31])) + .collect() +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeSet; + + use dotcore_domain::valid_id; + + use super::*; + + const KEY: u64 = 0x0123_4567_89ab_cdef; + + #[test] + fn identity_is_the_catalog_slug_and_a_scrambled_sequence_suffix() { + let ids = (1..=3) + .map(|sequence| deployment_id(&["qwen3-8-27b"], KEY, sequence).expect("identity")) + .collect::>(); + + assert_eq!( + ids, + [ + "qwen3-8-27b-3cfmn", + "qwen3-8-27b-qfqjk", + "qwen3-8-27b-65nbt" + ] + ); + assert_eq!( + deployment_id(&["open-webui"], KEY, 1).expect("application identity"), + "open-webui-3cfmn" + ); + } + + #[test] + fn another_key_scrambles_the_same_sequences_differently() { + let first = deployment_id(&["qwen3-8-27b"], KEY, 1).expect("identity"); + let other = deployment_id(&["qwen3-8-27b"], KEY + 1, 1).expect("identity"); + + assert_eq!(first, "qwen3-8-27b-3cfmn"); + assert_eq!(other, "qwen3-8-27b-yd750"); + } + + #[test] + fn slug_comes_from_the_first_readable_source() { + assert_eq!( + deployment_id(&["GPT-5.1 Mini (preview)", "openai-compatible"], KEY, 1) + .expect("named upstream"), + "gpt-5-1-mini-preview-3cfmn" + ); + assert_eq!( + deployment_id(&["4o-mini", "openai-compatible"], KEY, 1).expect("digit start"), + "openai-compatible-3cfmn" + ); + assert_eq!( + deployment_id(&["--", "openai-compatible"], KEY, 1).expect("empty name"), + "openai-compatible-3cfmn" + ); + assert_eq!( + deployment_id(&["é"], KEY, 1).expect("nothing readable"), + "deployment-3cfmn" + ); + assert_eq!( + slug("model--with-trailing-"), + Some("model-with-trailing".to_owned()) + ); + } + + #[test] + fn long_sources_are_cut_at_a_word_boundary_within_the_budget() { + let longest = "application-with-the-longest-valid-identifier-01234567890123456"; + assert_eq!(longest.len(), 63); + assert!(valid_id(longest)); + + let id = deployment_id(&[longest], KEY, SEQUENCE_CAPACITY).expect("identity"); + + assert_eq!(id, "application-with-the-longest-valid-xrd6p"); + assert!(id.len() <= MAX_DEPLOYMENT_ID_BYTES); + for derived in [ + id.clone(), + format!("{id}-group"), + format!("{id}-realization"), + format!("workload-{id}"), + ] { + assert!(valid_id(&derived), "{derived} is a valid identifier"); + } + assert_eq!(slug(&"a".repeat(63)), Some("a".repeat(MAX_SLUG_BYTES))); + assert_eq!( + slug("abcdefghij-abcdefghij-abcdefghijkl-next"), + Some("abcdefghij-abcdefghij-abcdefghijkl".to_owned()), + "a hyphen right after the budget keeps the whole last word" + ); + } + + #[test] + fn sequences_outside_the_site_capacity_have_no_identity() { + assert_eq!(deployment_id(&["model"], KEY, 0), None); + assert_eq!(deployment_id(&["model"], KEY, SEQUENCE_CAPACITY + 1), None); + } + + #[test] + fn scrambled_suffixes_never_repeat_within_a_sample() { + let suffixes = (0..50_000_u32) + .map(|index| scramble(KEY, index)) + .collect::>(); + + assert_eq!(suffixes.len(), 50_000); + assert!( + suffixes + .iter() + .all(|value| u64::from(*value) < SEQUENCE_CAPACITY) + ); + } + + #[test] + fn suffix_keys_round_trip_and_reject_other_forms() { + assert_eq!(parse_suffix_key(&format_suffix_key(KEY)), Some(KEY)); + assert_eq!(format_suffix_key(0xab), "00000000000000ab"); + assert_eq!(parse_suffix_key("0123456789ABCDEF"), None); + assert_eq!(parse_suffix_key("0123456789abcde"), None); + assert_eq!(parse_suffix_key("0123456789abcdeg"), None); + } +} diff --git a/backend/site/src/initial/inputs.rs b/backend/site/src/initial/inputs.rs index 9abc9b66..fef54f77 100644 --- a/backend/site/src/initial/inputs.rs +++ b/backend/site/src/initial/inputs.rs @@ -20,8 +20,8 @@ use dotcore_proto::{ node::v1::{DeclaredMachine, LoggingConfig, NodeConfiguration}, observation::v1::AcceleratorFacts, site::v1::{ - ApplicationRuntimeBinding, DockerAcceleratorTransport, DockerApplicationRuntimeAdapter, - DockerRuntimeAdapter, ExecutionTarget, ModelDeploymentIdentityAllocator, + ApplicationRuntimeBinding, DeploymentIdentityAllocator, DockerAcceleratorTransport, + DockerApplicationRuntimeAdapter, DockerRuntimeAdapter, ExecutionTarget, ModelRuntimeBinding, NativeRuntimeAdapter, NativeWorkloadLifetime, SimulatedApplicationRuntimeAdapter, SimulatedRuntimeAdapter, SimulatedRuntimeScenario, Site, SiteManagerRole, SiteNode, application_runtime_binding, execution_target, @@ -100,8 +100,10 @@ impl InitialSiteInputs { inference_routes: Vec::new(), hardware_observation: None, console_settings: None, - model_deployment_identity_allocator: Some(ModelDeploymentIdentityAllocator { - namespace: crate::store::model_deployment_identity_namespace(identities.site_id()), + deployment_identity_allocator: Some(DeploymentIdentityAllocator { + suffix_key: crate::deployment_identity::format_suffix_key( + identities.deployment_suffix_key(), + ), next_sequence: 1, }), }; diff --git a/backend/site/src/initial/request.rs b/backend/site/src/initial/request.rs index 4f2850c2..c8310d54 100644 --- a/backend/site/src/initial/request.rs +++ b/backend/site/src/initial/request.rs @@ -42,6 +42,9 @@ pub enum InitialSiteIdentityKind { /// The sole SiteNode identity, when the operator overrides it. Node, + + /// The key that scrambles the site's deployment identity suffixes. + Deployment, } impl fmt::Display for InitialSiteIdentityKind { @@ -49,6 +52,7 @@ impl fmt::Display for InitialSiteIdentityKind { formatter.write_str(match self { Self::Site => "Site", Self::Node => "Node", + Self::Deployment => "Deployment", }) } } @@ -57,7 +61,8 @@ impl fmt::Display for InitialSiteIdentityKind { /// configuration. pub trait InitialSiteIdentityGenerator { /// Returns one value from which the policy derives an identity for `kind`. Only the site - /// identity is generated; node and target identities are derived from it. + /// identity and the deployment identity key are generated; node and target identities are + /// derived from the site identity. fn generate(&mut self, kind: InitialSiteIdentityKind) -> anyhow::Result; /// Returns the SiteNode display name this machine suggests, used when the operator supplied @@ -72,12 +77,17 @@ pub trait InitialSiteIdentityGenerator { pub struct RandomInitialSiteIdentityGenerator; impl InitialSiteIdentityGenerator for RandomInitialSiteIdentityGenerator { - fn generate(&mut self, _kind: InitialSiteIdentityKind) -> anyhow::Result { - let mut bytes = [0_u8; 5]; - getrandom::fill(&mut bytes).map_err(identity_entropy_error)?; - Ok(bytes - .into_iter() - .fold(0_u64, |value, byte| (value << 8) | u64::from(byte))) + fn generate(&mut self, kind: InitialSiteIdentityKind) -> anyhow::Result { + // A site identity is ten hex digits; a deployment identity key is sixteen. + let width = match kind { + InitialSiteIdentityKind::Deployment => 8, + _ => 5, + }; + let mut bytes = [0_u8; 8]; + getrandom::fill(&mut bytes[..width]).map_err(identity_entropy_error)?; + Ok(bytes[..width] + .iter() + .fold(0_u64, |value, byte| (value << 8) | u64::from(*byte))) } } @@ -282,10 +292,17 @@ impl InitialSiteRequest { None => derive_site_node_id(&site_id, &node_display_name), }; validate_identity(InitialSiteIdentityKind::Node, &node_id)?; + let deployment_suffix_key = generator + .generate(InitialSiteIdentityKind::Deployment) + .map_err(|source| InitialSiteRequestError::IdentityGeneration { + kind: InitialSiteIdentityKind::Deployment, + source, + })?; Ok(InitialSiteIdentities { site_id, node_id, node_display_name, + deployment_suffix_key, }) } } @@ -297,6 +314,7 @@ pub struct InitialSiteIdentities { site_id: String, node_id: String, node_display_name: String, + deployment_suffix_key: u64, } impl InitialSiteIdentities { @@ -316,6 +334,12 @@ impl InitialSiteIdentities { &self.node_display_name } + /// Returns the random key that scrambles the new site's deployment identity suffixes, so a + /// site created again under the same identity issues different deployment identities. + pub fn deployment_suffix_key(&self) -> u64 { + self.deployment_suffix_key + } + /// Iterates over every resolved identity in site topology order. pub fn values(&self) -> impl Iterator { [self.site_id.as_str(), self.node_id.as_str()].into_iter() @@ -439,10 +463,31 @@ mod tests { use super::{ InitialApplicationRuntime, InitialInferenceRuntime, InitialSiteIdentityGenerator, InitialSiteIdentityKind, InitialSiteRequest, InitialSiteRequestError, - derive_application_execution_target_id, derive_model_execution_target_id, - derive_site_node_id, identity_entropy_error, stable_identity_value, + RandomInitialSiteIdentityGenerator, derive_application_execution_target_id, + derive_model_execution_target_id, derive_site_node_id, identity_entropy_error, + stable_identity_value, }; + #[test] + fn random_generator_draws_the_full_width_of_each_identity() { + let mut generator = RandomInitialSiteIdentityGenerator; + + let site = generator + .generate(InitialSiteIdentityKind::Site) + .expect("site entropy"); + assert!(site < 1 << 40); + // 64 random bits land above 40 bits except with probability 2^-24 per draw. + let widest = (0..4) + .map(|_| { + generator + .generate(InitialSiteIdentityKind::Deployment) + .expect("deployment entropy") + }) + .max() + .expect("draws"); + assert!(widest >= 1 << 40, "{widest:#x} must use more than 40 bits"); + } + #[test] fn independent_workload_choices_resolve_generated_bounded_identities() { let request = InitialSiteRequest::new( @@ -453,7 +498,7 @@ mod tests { ], [InitialApplicationRuntime::Docker], ); - let mut generator = FixedIdentityGenerator::new([0x01]); + let mut generator = FixedIdentityGenerator::new([0x01, 0x02]); assert_eq!( request.inference().iter().copied().collect::>(), @@ -476,7 +521,14 @@ mod tests { identities.node_id(), derive_site_node_id("site-0000000001", "manager") ); - assert_eq!(generator.kinds, [InitialSiteIdentityKind::Site]); + assert_eq!(identities.deployment_suffix_key(), 0x02); + assert_eq!( + generator.kinds, + [ + InitialSiteIdentityKind::Site, + InitialSiteIdentityKind::Deployment + ] + ); } #[test] @@ -487,7 +539,7 @@ mod tests { ); for value in [0, u64::MAX] { let identities = request - .resolve_identities(&mut FixedIdentityGenerator::new([value])) + .resolve_identities(&mut FixedIdentityGenerator::new([value, value])) .expect("identities"); for identity in identities.values() { @@ -535,7 +587,7 @@ mod tests { ) .with_site_id_override("automation-site") .with_node_id_override("automation-node"); - let mut generator = FixedIdentityGenerator::new([]); + let mut generator = FixedIdentityGenerator::new([0x2a]); let identities = request .resolve_identities(&mut generator) @@ -543,7 +595,12 @@ mod tests { assert_eq!(identities.site_id(), "automation-site"); assert_eq!(identities.node_id(), "automation-node"); - assert!(generator.kinds.is_empty()); + assert_eq!( + identities.deployment_suffix_key(), + 0x2a, + "a site created again under the same identity draws a new deployment key" + ); + assert_eq!(generator.kinds, [InitialSiteIdentityKind::Deployment]); } #[test] diff --git a/backend/site/src/initial/validation.rs b/backend/site/src/initial/validation.rs index e6642686..449c220c 100644 --- a/backend/site/src/initial/validation.rs +++ b/backend/site/src/initial/validation.rs @@ -326,7 +326,7 @@ mod tests { assert!(!root.exists()); } - const VALID_SITE_YAML: &str = "siteId: site-test\nmodelDeploymentIdentityAllocator: { namespace: 0123456789abcdef, nextSequence: '1' }\nnodes:\n- nodeId: node-test\n host: 127.0.0.1\n displayName: Test node\n siteManager: {}\nexecutionTargets:\n- executionTargetId: target-test\n siteNodeId: node-test\n displayName: target-test\n platform: { operatingSystem: linux, architecture: amd64 }\n modelRuntime:\n simulatedRuntime:\n defaultScenario: { readyDelayMillis: '2000', stopDelayMillis: '2000' }\n- executionTargetId: application-target-test\n siteNodeId: node-test\n displayName: application-target-test\n platform: { operatingSystem: linux, architecture: amd64 }\n applicationRuntime: { simulatedRuntime: {} }\n"; + const VALID_SITE_YAML: &str = "siteId: site-test\ndeploymentIdentityAllocator: { suffixKey: 0123456789abcdef, nextSequence: '1' }\nnodes:\n- nodeId: node-test\n host: 127.0.0.1\n displayName: Test node\n siteManager: {}\nexecutionTargets:\n- executionTargetId: target-test\n siteNodeId: node-test\n displayName: target-test\n platform: { operatingSystem: linux, architecture: amd64 }\n modelRuntime:\n simulatedRuntime:\n defaultScenario: { readyDelayMillis: '2000', stopDelayMillis: '2000' }\n- executionTargetId: application-target-test\n siteNodeId: node-test\n displayName: application-target-test\n platform: { operatingSystem: linux, architecture: amd64 }\n applicationRuntime: { simulatedRuntime: {} }\n"; const APPLICATION_CATALOG: &str = "applicationId: fixture-application\ndisplayName: Fixture application\nversion: '1'\ngraph:\n services:\n - serviceName: web\n artifact:\n oci:\n repository: { registry: { host: example.invalid }, name: fixture/web }\n digest: { algorithm: sha256, encoded: '1111111111111111111111111111111111111111111111111111111111111111' }\n supportedPlatforms:\n - { operatingSystem: linux, architecture: amd64 }\n ports:\n - { portName: http, portNumber: 8080 }\n primaryEndpoint: { serviceName: web, portName: http, protocol: APPLICATION_ENDPOINT_PROTOCOL_HTTP }\n"; struct SiteFixture { diff --git a/backend/site/src/lib.rs b/backend/site/src/lib.rs index 1b9fb137..f4c212fd 100644 --- a/backend/site/src/lib.rs +++ b/backend/site/src/lib.rs @@ -12,6 +12,7 @@ compile_error!("Dotcore supports only Linux and macOS targets"); pub mod atomic; pub mod console_settings; +mod deployment_identity; pub mod initial; pub mod manager_trust; pub mod membership; diff --git a/backend/site/src/membership/removal.rs b/backend/site/src/membership/removal.rs index 0944064c..7aa865a2 100644 --- a/backend/site/src/membership/removal.rs +++ b/backend/site/src/membership/removal.rs @@ -706,7 +706,7 @@ pub(super) mod tests { "present", )); site.application_deployments[0].inference_route_id = Some("sole".to_owned()); - let before_allocator = site.model_deployment_identity_allocator.clone(); + let before_allocator = site.deployment_identity_allocator.clone(); let lock = lock(&fixture); let plan = plan_node_removal( @@ -761,10 +761,7 @@ pub(super) mod tests { .collect::>(), ["keep"] ); - assert_eq!( - written.model_deployment_identity_allocator, - before_allocator - ); + assert_eq!(written.deployment_identity_allocator, before_allocator); } #[test] diff --git a/backend/site/src/node/stream/tests.rs b/backend/site/src/node/stream/tests.rs index 9d74037d..952e5bf6 100644 --- a/backend/site/src/node/stream/tests.rs +++ b/backend/site/src/node/stream/tests.rs @@ -1256,8 +1256,8 @@ fn incarnation(character: char) -> NodeIncarnation { } const SITE: &str = r#"siteId: site-one -modelDeploymentIdentityAllocator: - namespace: 0123456789abcdef +deploymentIdentityAllocator: + suffixKey: 0123456789abcdef nextSequence: '1' nodes: - nodeId: manager-node diff --git a/backend/site/src/repository/mod.rs b/backend/site/src/repository/mod.rs index 78671671..24c9dd53 100644 --- a/backend/site/src/repository/mod.rs +++ b/backend/site/src/repository/mod.rs @@ -24,6 +24,7 @@ use dotcore_proto::{ use tracing::{error, info, warn}; use super::{ + deployment_identity, persistence::{AtomicSiteFileWriter, SiteFileWriter}, validation::{SiteDeclarationRules, load_validated_site, validate_site}, view::desired::reject_node_view_growth, @@ -599,32 +600,30 @@ impl SiteRepository { self.write_accepted(current, site, &contents) } - /// Durably reserves one never-reused model deployment identity before creation acceptance. - pub fn reserve_model_deployment_id(&self) -> Result { + /// Durably reserves one never-reused deployment identity, model or application, before + /// creation acceptance. Its readable part is named after the first of `slug_sources` that + /// yields one; its suffix comes from the site's next sequence, which this call consumes. + pub fn reserve_deployment_id( + &self, + slug_sources: &[&str], + ) -> Result { let mut current = lock(&self.state)?; let mut candidate = current.site.clone(); let allocator = candidate - .model_deployment_identity_allocator + .deployment_identity_allocator .as_mut() .ok_or_else(|| { - SiteRepositoryError::invalid_site("model deployment identity allocator is missing") + SiteRepositoryError::invalid_site("deployment identity allocator is missing") + })?; + let suffix_key = deployment_identity::parse_suffix_key(&allocator.suffix_key) + .filter(|_| allocator.next_sequence != 0) + .ok_or_else(|| { + SiteRepositoryError::invalid_site("deployment identity allocator is invalid") })?; - if allocator.namespace.len() != 16 - || !allocator - .namespace - .bytes() - .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) - || allocator.next_sequence == 0 - { - return Err(SiteRepositoryError::invalid_site( - "model deployment identity allocator is invalid", - )); - } let sequence = allocator.next_sequence; - allocator.next_sequence = sequence.checked_add(1).ok_or_else(|| { - SiteRepositoryError::invalid_site("model deployment identity sequence exhausted") - })?; - let deployment_id = format!("model-{}-{sequence}", allocator.namespace); + let deployment_id = deployment_identity::deployment_id(slug_sources, suffix_key, sequence) + .ok_or_else(|| SiteRepositoryError::DeploymentIdentitiesExhausted)?; + allocator.next_sequence = sequence + 1; validate_site(&candidate, &self.rules)?; let contents = yaml::to_string(&candidate).map_err(SiteRepositoryError::SerializeYaml)?; self.persist_mutation(&mut current, candidate, &contents)?; @@ -747,6 +746,12 @@ pub enum SiteRepositoryError { #[error("desired view for node {node_id:?} would exceed the private node-view limits")] NodeViewLimitExceeded { node_id: String }, + /// The site has handed out every deployment identity its allocator can produce. + #[error( + "this site has used all of its deployment identities; no more deployments can be created" + )] + DeploymentIdentitiesExhausted, + #[error("desired site is unavailable")] Unavailable, diff --git a/backend/site/src/repository/tests.rs b/backend/site/src/repository/tests.rs index 66ae9dab..36684aad 100644 --- a/backend/site/src/repository/tests.rs +++ b/backend/site/src/repository/tests.rs @@ -177,7 +177,45 @@ async fn assert_mutation_writes_before_notifying(fails: bool) { } #[test] -fn model_identity_reservations_preserve_uncertain_and_unused_gaps_across_restart() { +fn exhausted_deployment_identities_fail_with_their_own_error_and_change_nothing() { + let directory = test_directory(); + let path = directory.join("site.yaml"); + let mut site = valid_site(); + // One past the 2^25 sequences a site can reserve. + site.deployment_identity_allocator + .as_mut() + .expect("allocator") + .next_sequence = (1 << 25) + 1; + fs::write(&path, yaml::to_string(&site).expect("desired site YAML")).expect("fixture"); + let repository = SiteRepository::load(&path, crate::test_support::site_declaration_rules()) + .expect("exhausted site"); + + let error = repository + .reserve_deployment_id(&["qwen3-8-27b"]) + .expect_err("exhausted allocator"); + + assert!(matches!( + error, + SiteRepositoryError::DeploymentIdentitiesExhausted + )); + assert_eq!( + error.to_string(), + "this site has used all of its deployment identities; no more deployments can be created" + ); + assert_eq!( + repository + .snapshot() + .expect("site") + .deployment_identity_allocator + .expect("allocator") + .next_sequence, + (1 << 25) + 1 + ); + fs::remove_dir_all(directory).expect("fixture cleanup"); +} + +#[test] +fn deployment_identity_reservations_preserve_uncertain_and_unused_gaps_across_restart() { let directory = test_directory(); let path = directory.join("site.yaml"); fs::write( @@ -193,7 +231,7 @@ fn model_identity_reservations_preserve_uncertain_and_unused_gaps_across_restart ) .expect("failure-injected site"); assert!(matches!( - failed.reserve_model_deployment_id(), + failed.reserve_deployment_id(&["qwen3-8-27b"]), Err(SiteRepositoryError::Storage(SiteStorageError::Storage(_))) )); assert_eq!( @@ -201,7 +239,7 @@ fn model_identity_reservations_preserve_uncertain_and_unused_gaps_across_restart .expect("restart after known failure") .snapshot() .expect("known-failure site") - .model_deployment_identity_allocator + .deployment_identity_allocator .expect("allocator") .next_sequence, 1 @@ -216,7 +254,7 @@ fn model_identity_reservations_preserve_uncertain_and_unused_gaps_across_restart ) .expect("uncertain site"); assert!(matches!( - uncertain.reserve_model_deployment_id(), + uncertain.reserve_deployment_id(&["qwen3-8-27b"]), Err(SiteRepositoryError::Storage( SiteStorageError::OutcomeUncertain(_) )) @@ -224,18 +262,26 @@ fn model_identity_reservations_preserve_uncertain_and_unused_gaps_across_restart let restarted = SiteRepository::load(&path, crate::test_support::site_declaration_rules()) .expect("restart after uncertain reservation"); let second = restarted - .reserve_model_deployment_id() + .reserve_deployment_id(&["qwen3-8-27b"]) .expect("reservation after restart"); - assert_eq!(second, "model-0123456789abcdef-2"); + assert_eq!(second, "qwen3-8-27b-qfqjk"); drop(restarted); let restarted = SiteRepository::load(&path, crate::test_support::site_declaration_rules()) .expect("restart after unused reservation"); let third = restarted - .reserve_model_deployment_id() + .reserve_deployment_id(&["open-webui"]) .expect("reservation after unused gap"); - assert_eq!(third, "model-0123456789abcdef-3"); - assert_ne!(second, third); + assert_eq!(third, "open-webui-65nbt"); + assert_eq!( + restarted + .snapshot() + .expect("reserved site") + .deployment_identity_allocator + .expect("allocator") + .next_sequence, + 4 + ); fs::remove_dir_all(directory).expect("fixture cleanup"); } @@ -1364,9 +1410,9 @@ fn valid_site() -> Site { site_manager: Some(SiteManagerRole {}), manager_host: String::new(), }], - model_deployment_identity_allocator: Some( - dotcore_proto::dotcore::site::v1::ModelDeploymentIdentityAllocator { - namespace: "0123456789abcdef".to_owned(), + deployment_identity_allocator: Some( + dotcore_proto::dotcore::site::v1::DeploymentIdentityAllocator { + suffix_key: "0123456789abcdef".to_owned(), next_sequence: 1, }, ), diff --git a/backend/site/src/store/mod.rs b/backend/site/src/store/mod.rs index 335ead6a..8fa2d3ae 100644 --- a/backend/site/src/store/mod.rs +++ b/backend/site/src/store/mod.rs @@ -266,20 +266,6 @@ fn validate_lifecycle_records(state: &SiteCurrentState) -> Result<(), StoreError Ok(()) } -/// Derives the stable random-looking deployment identity namespace for one site. -/// The namespace is independent of mutable site declarations and survives ordinary rewrites. -pub fn model_deployment_identity_namespace(site_id: &str) -> String { - let mut hasher = Sha256::new(); - hasher.update(b"dotcore.model-deployment-namespace.v1\0"); - hasher.update(site_id.as_bytes()); - hasher - .finalize() - .iter() - .take(8) - .map(|byte| format!("{byte:02x}")) - .collect() -} - /// Digests one cleanup evidence identity: exactly its deployment and teardown lifecycle generation. pub fn cleanup_evidence_digest(model_deployment_id: &str, lifecycle_generation: u64) -> String { evidence_identity_digest( diff --git a/backend/site/src/store/site/mod.rs b/backend/site/src/store/site/mod.rs index 292798b9..4d87a81f 100644 --- a/backend/site/src/store/site/mod.rs +++ b/backend/site/src/store/site/mod.rs @@ -883,7 +883,7 @@ mod tests { let directory = TestDirectory::new(); let site_yaml = directory.path.join("site.yaml"); let site = Site { - model_deployment_identity_allocator: None, + deployment_identity_allocator: None, ..site_with_deployment("model-one", 5) }; let site_bytes = dotcore_proto::yaml::to_string(&site).expect("site YAML"); @@ -902,7 +902,7 @@ mod tests { }; assert_eq!( error.to_string(), - "Invalid desired site: site.yaml model deployment identity allocator is missing" + "Invalid desired site: site.yaml deployment identity allocator is missing" ); assert_eq!( fs::read_to_string(&site_yaml).expect("unchanged site"), @@ -974,15 +974,15 @@ mod tests { deployment::v1::ExactPlacement, model::v1::{ModelDeploymentDeclaration, ModelDeploymentLifecycleTransition}, site::v1::{ - ExecutionTarget, ModelDeploymentIdentityAllocator, ModelRuntimeBinding, + DeploymentIdentityAllocator, ExecutionTarget, ModelRuntimeBinding, SimulatedRuntimeAdapter, SimulatedRuntimeScenario, execution_target, model_runtime_binding, }, }; Site { - model_deployment_identity_allocator: Some(ModelDeploymentIdentityAllocator { - namespace: crate::store::model_deployment_identity_namespace("site-one"), + deployment_identity_allocator: Some(DeploymentIdentityAllocator { + suffix_key: "0123456789abcdef".to_owned(), next_sequence: 1, }), execution_targets: vec![ExecutionTarget { diff --git a/backend/site/src/test_support/mod.rs b/backend/site/src/test_support/mod.rs index dc622b8e..8da838ce 100644 --- a/backend/site/src/test_support/mod.rs +++ b/backend/site/src/test_support/mod.rs @@ -84,9 +84,9 @@ pub fn stored(store: &S) -> Result { } /// Model deployment identity allocator for sites built by tests; every valid site declares one. -pub fn identity_allocator() -> dotcore_proto::dotcore::site::v1::ModelDeploymentIdentityAllocator { - dotcore_proto::dotcore::site::v1::ModelDeploymentIdentityAllocator { - namespace: "0123456789abcdef".to_owned(), +pub fn identity_allocator() -> dotcore_proto::dotcore::site::v1::DeploymentIdentityAllocator { + dotcore_proto::dotcore::site::v1::DeploymentIdentityAllocator { + suffix_key: "0123456789abcdef".to_owned(), next_sequence: 1, } } diff --git a/backend/site/src/validation.rs b/backend/site/src/validation.rs index 80e7d707..0c9b3d42 100644 --- a/backend/site/src/validation.rs +++ b/backend/site/src/validation.rs @@ -100,7 +100,7 @@ pub fn validate_site(site: &Site, rules: &SiteDeclarationRules) -> Result<(), Si "site.yaml hardwareObservation.refreshIntervalSeconds must be between {MIN_HARDWARE_REFRESH_INTERVAL_SECONDS} and {MAX_HARDWARE_REFRESH_INTERVAL_SECONDS}; got {seconds}" )); } - validate_model_identity_allocator(site)?; + validate_deployment_identity_allocator(site)?; let node_ids = validate_nodes(&site.nodes)?; let execution_targets = validate_execution_targets(&site.execution_targets, &node_ids)?; let mut deployment_ids = BTreeSet::new(); @@ -235,18 +235,14 @@ pub fn validate_site(site: &Site, rules: &SiteDeclarationRules) -> Result<(), Si validate_application_route_bindings(&site.application_deployments, &site.inference_routes) } -fn validate_model_identity_allocator(site: &Site) -> Result<(), SiteRepositoryError> { - let Some(allocator) = &site.model_deployment_identity_allocator else { - return invalid_site("site.yaml model deployment identity allocator is missing"); +fn validate_deployment_identity_allocator(site: &Site) -> Result<(), SiteRepositoryError> { + let Some(allocator) = &site.deployment_identity_allocator else { + return invalid_site("site.yaml deployment identity allocator is missing"); }; - if allocator.namespace.len() != 16 - || !allocator - .namespace - .bytes() - .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) + if crate::deployment_identity::parse_suffix_key(&allocator.suffix_key).is_none() || allocator.next_sequence == 0 { - return invalid_site("site.yaml model deployment identity allocator is invalid"); + return invalid_site("site.yaml deployment identity allocator is invalid"); } Ok(()) } @@ -1480,7 +1476,7 @@ mod tests { }; Site { site_id: "site-one".to_owned(), - model_deployment_identity_allocator: Some(crate::test_support::identity_allocator()), + deployment_identity_allocator: Some(crate::test_support::identity_allocator()), nodes: vec![SiteNode { node_id: "manager-node".to_owned(), display_name: "Manager".to_owned(), diff --git a/backend/site/src/view/desired/tests.rs b/backend/site/src/view/desired/tests.rs index db254039..78d055bc 100644 --- a/backend/site/src/view/desired/tests.rs +++ b/backend/site/src/view/desired/tests.rs @@ -664,8 +664,8 @@ fn owner_rules() -> NodeViewOwnerRules { } const TWO_WORKER_SITE: &str = r#"siteId: site-one -modelDeploymentIdentityAllocator: - namespace: 0123456789abcdef +deploymentIdentityAllocator: + suffixKey: 0123456789abcdef nextSequence: '1' nodes: - nodeId: manager-node @@ -849,9 +849,9 @@ fn application_site_yaml() -> String { let mut target = application_target("application-target", "worker-one"); target.platform = platform.clone(); site.execution_targets.push(target); - site.model_deployment_identity_allocator = Some( - dotcore_proto::dotcore::site::v1::ModelDeploymentIdentityAllocator { - namespace: "0123456789abcdef".to_owned(), + site.deployment_identity_allocator = Some( + dotcore_proto::dotcore::site::v1::DeploymentIdentityAllocator { + suffix_key: "0123456789abcdef".to_owned(), next_sequence: 2, }, ); diff --git a/backend/site/src/worker_channels.rs b/backend/site/src/worker_channels.rs index 1a0aeb13..b01f5f47 100644 --- a/backend/site/src/worker_channels.rs +++ b/backend/site/src/worker_channels.rs @@ -501,8 +501,8 @@ mod tests { } const MANAGER_SITE: &str = r#"siteId: site-one -modelDeploymentIdentityAllocator: - namespace: 0123456789abcdef +deploymentIdentityAllocator: + suffixKey: 0123456789abcdef nextSequence: '1' nodes: - nodeId: manager-node diff --git a/docs/specs/inference.md b/docs/specs/inference.md index e2504dc6..eedf01f5 100644 --- a/docs/specs/inference.md +++ b/docs/specs/inference.md @@ -17,8 +17,8 @@ Code: `backend/core/src/route_manager/`, `backend/core/src/router/`, - Expose a deployment directly under its own route, or keep it hidden in other routes. Route membership doesn't care whether a deployment is local or upstream. - Create, inspect, rename, enable, disable and delete routes. See their membership and - availability, and why a route or member is unavailable, without exposing private provider - configuration. + availability, and why a route or member is unavailable, without exposing provider credentials. + An upstream model's ID isn't private. - Use ordered fallback groups and selection among eligible deployments, within bounded retry safety. - Get connection information and integration examples for a route. @@ -181,7 +181,7 @@ flowchart LR ## Invariants - The route manager and the inference controller stay off the live request path. -- Public route identity is preserved while source-private model, endpoint and credential details stay +- Public route identity is preserved while source-private endpoint and credential details stay isolated. - Dispatch authority and revocation are scoped to the selected deployment. Changing one target never revokes another. diff --git a/docs/specs/models.md b/docs/specs/models.md index dab42deb..70e0d304 100644 --- a/docs/specs/models.md +++ b/docs/specs/models.md @@ -242,7 +242,7 @@ never redefine it. ### Upstream deployment -- Keeps a template snapshot and a private endpoint configuration. +- Keeps a template snapshot and an endpoint configuration whose credentials stay private. - Has no local model artifact, engine, runtime workload or exact placement. Dotcore never invents local hardware, engine or placement data for it. - Local and upstream are the only kinds of serving source. From 1ae238040851cad405f943fa1038f195ffb93d82 Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 11:25:23 -0500 Subject: [PATCH 04/19] feat(backend): pipeable dotc output, --yaml and consistent commands --- backend/AGENTS.md | 17 +- backend/Cargo.lock | 1 + backend/cli/Cargo.toml | 1 + backend/cli/src/application/list.rs | 56 +- backend/cli/src/application/mod.rs | 100 +- backend/cli/src/application/parameters.rs | 14 +- backend/cli/src/application/show.rs | 97 +- backend/cli/src/config.rs | 130 +- backend/cli/src/gc/mod.rs | 273 ++-- backend/cli/src/gc/storage.rs | 173 ++- backend/cli/src/guided/capability.rs | 14 +- backend/cli/src/guided/host.rs | 8 +- backend/cli/src/guided/mod.rs | 2 +- backend/cli/src/guided/node_name.rs | 2 +- backend/cli/src/guided/summary.rs | 6 +- backend/cli/src/hardware/mod.rs | 26 +- backend/cli/src/hardware/recommend.rs | 152 ++- backend/cli/src/hardware/show.rs | 202 ++- backend/cli/src/lib.rs | 194 ++- backend/cli/src/management/deployment.rs | 104 +- backend/cli/src/management/document.rs | 55 + backend/cli/src/management/logs.rs | 103 +- backend/cli/src/management/mod.rs | 36 +- backend/cli/src/management/route.rs | 105 -- backend/cli/src/model/list.rs | 55 +- backend/cli/src/model/mod.rs | 110 +- backend/cli/src/model/parameters.rs | 224 +++- backend/cli/src/model/show.rs | 90 +- backend/cli/src/node/add.rs | 137 +- backend/cli/src/node/join.rs | 231 ++-- backend/cli/src/node/leave.rs | 52 +- backend/cli/src/node/list.rs | 187 ++- backend/cli/src/node/mod.rs | 106 +- backend/cli/src/node/remove.rs | 154 ++- backend/cli/src/output.rs | 249 ++++ backend/cli/src/parameters.rs | 82 +- backend/cli/src/runtime_confirmation.rs | 4 +- backend/cli/src/site/delete.rs | 32 +- backend/cli/src/site/init.rs | 53 +- backend/cli/src/site/mod.rs | 69 +- backend/cli/src/site/output.rs | 364 ++++-- backend/cli/src/site/reset.rs | 51 +- backend/cli/src/telemetry.rs | 4 +- backend/cli/src/terminal/line.rs | 120 +- backend/cli/src/terminal/mod.rs | 33 +- backend/cli/src/terminal/output.rs | 122 ++ backend/cli/src/terminal/rich/mod.rs | 66 +- backend/cli/src/terminal/rich/tty.rs | 4 +- backend/cli/src/terminal/scripted.rs | 7 +- backend/cli/src/workload/mod.rs | 10 +- backend/cli/src/workload/teardown_all.rs | 4 +- backend/cli/tests/application_contract.rs | 435 ++++--- .../cli/tests/application_manager_contract.rs | 110 +- backend/cli/tests/command_contract.rs | 1123 ++++++++++++++--- backend/cli/tests/model_contract.rs | 618 +++++++-- .../tests/site_reset_docker_integration.rs | 5 +- backend/cli/tests/support/mod.rs | 27 +- backend/cli/tests/support/pty.rs | 78 +- .../cli/tests/support/simulated_manager.rs | 2 +- backend/site/src/membership/management.rs | 4 +- backend/site/src/membership/mod.rs | 2 +- docs/usage.md | 5 + 62 files changed, 4930 insertions(+), 1970 deletions(-) create mode 100644 backend/cli/src/management/document.rs delete mode 100644 backend/cli/src/management/route.rs create mode 100644 backend/cli/src/output.rs create mode 100644 backend/cli/src/terminal/output.rs diff --git a/backend/AGENTS.md b/backend/AGENTS.md index b9c2bda2..83ec0062 100644 --- a/backend/AGENTS.md +++ b/backend/AGENTS.md @@ -110,8 +110,19 @@ 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`, `template`, `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 (`management::resolve`); never match names or IDs by hand. A reference matching several objects fails and lists them. - 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. 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..bbfca626 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; @@ -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, @@ -177,6 +193,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 +206,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 +244,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 +289,7 @@ impl LoggedDeployment for ApplicationDeployment { id: String, sources: Vec, positions: Vec, - ) -> Result { + ) -> Result, Status> { let events = manager .applications() .follow_deployment_logs(FollowDeploymentLogsRequest { @@ -316,13 +338,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 +357,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/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/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/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/hardware/mod.rs b/backend/cli/src/hardware/mod.rs index 165817e8..141a8800 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,7 +12,7 @@ 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}; use show::show; @@ -27,21 +27,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..6e22ccb7 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. +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/lib.rs b/backend/cli/src/lib.rs index 839d9383..3c4bb8dd 100644 --- a/backend/cli/src/lib.rs +++ b/backend/cli/src/lib.rs @@ -30,6 +30,7 @@ mod hosts; mod management; mod model; mod node; +mod output; mod parameters; mod paths; mod runtime_confirmation; @@ -56,6 +57,11 @@ pub struct Cli { #[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, + #[command(flatten)] pub paths: RootPathArgs, @@ -66,41 +72,40 @@ pub struct Cli { /// 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 +120,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 +150,18 @@ pub fn build_runtime() -> Result { /// Dispatches a parsed command to its owning capability. pub async fn dispatch(cli: Cli) -> Result<()> { let paths = &cli.paths; + let format = cli.output_format(); match cli.command { - Command::Config(command) => command.dispatch(paths), + 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 +206,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) @@ -233,8 +242,8 @@ fn without_root_paths(arguments: &[std::ffi::OsString]) -> Vec bool { matches!( ( @@ -258,6 +267,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 { @@ -356,9 +383,21 @@ 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> { + if self.yaml && !self.command.prints_yaml() { + return Some("--yaml is not available for this command"); + } match &self.command { - Command::Site(command) => command.argument_contract_error(), + 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,6 +415,8 @@ impl Cli { mod tests { use clap::error::ErrorKind; + use clap::CommandFactory; + use super::Cli; #[test] @@ -441,6 +482,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()); } @@ -522,6 +567,25 @@ mod tests { } } + #[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 +608,76 @@ 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 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"]] { diff --git a/backend/cli/src/management/deployment.rs b/backend/cli/src/management/deployment.rs index 521bf119..b1aa990e 100644 --- a/backend/cli/src/management/deployment.rs +++ b/backend/cli/src/management/deployment.rs @@ -4,26 +4,25 @@ //! //! 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 dotcore_proto::dotcore::deployment::v1::ExactPlacement; +use serde::Serialize; use tonic::Status; use super::{ - Addressable, DeploymentGroup, ManagementError, Manager, ManagerArgs, call_failed, resolve, - single_line, + Addressable, DeploymentDocument, DeploymentGroup, ManagementError, Manager, ManagerArgs, + call_failed, resolve, 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}, + 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: Addressable + Clone + Serialize { /// The command group the kind belongs to. const GROUP: DeploymentGroup; @@ -38,18 +37,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. @@ -105,21 +109,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 +138,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 +166,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..b041e8cd 100644 --- a/backend/cli/src/management/mod.rs +++ b/backend/cli/src/management/mod.rs @@ -7,6 +7,7 @@ //! deployments fails with their ids instead of picking one. mod deployment; +mod document; mod logs; use std::{collections::HashMap, fmt, str::FromStr, time::Duration}; @@ -31,6 +32,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 +49,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, } @@ -190,15 +194,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 { @@ -262,22 +276,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. 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/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/mod.rs b/backend/cli/src/model/mod.rs index 5422de4d..f1a37f8a 100644 --- a/backend/cli/src/model/mod.rs +++ b/backend/cli/src/model/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_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 list; mod parameters; @@ -24,13 +25,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, 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 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 +48,44 @@ 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. + /// 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::Pause(arguments)) => { change_lifecycle::( &arguments.manager, &arguments.reference, Lifecycle::Pause, + format, ) .await } @@ -85,15 +94,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 +123,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 +134,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 +185,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 +200,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 +259,7 @@ impl LoggedDeployment for ModelDeployment { id: String, sources: Vec, positions: Vec, - ) -> Result { + ) -> Result, Status> { let events = manager .models() .follow_deployment_logs(FollowDeploymentLogsRequest { @@ -285,26 +308,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/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/node/add.rs b/backend/cli/src/node/add.rs index 6e86fcd3..3e9a5de3 100644 --- a/backend/cli/src/node/add.rs +++ b/backend/cli/src/node/add.rs @@ -3,7 +3,9 @@ //! Starts a join through the site manager's management API, shows how to run `dotc node join` on //! the new machine, and follows the join. The operator allows the specific machine that arrives //! (or the command does with `--yes`), and the manager records it only after the machine has -//! installed its own folder. Ending the command before the join completes cancels the join. +//! installed its own folder. Ending the command before the join completes cancels the join. Asked +//! for YAML, the command never asks, so it needs `--yes`, reports its progress and the command +//! to run on the new machine on stderr, and prints one document once the node is recorded. use std::{ io::Write, @@ -23,15 +25,15 @@ use dotcore_proto::dotcore::site::v1::{ use dotcore_site::{membership::join::JoinToken, node::folder::CertificateFingerprint}; use tonic::{Code, Streaming, transport::Channel}; -use super::{Notices, boxed, fingerprint_facts, fingerprint_grid, record_value, write_records}; +use serde::Serialize; + +use super::{Notices, boxed, fingerprint_facts, fingerprint_grid, progress, write_stdout}; use crate::{ RootPathArgs, management::{ManagementError, ManagerArgs, single_line}, + output::{OutputFormat, plain_text, require_consent, write_yaml}, site::parse_absolute_path, - terminal::{ - ConfirmPrompt, Message, PromptError, Terminal, TerminalCondition, - controlling_terminal_condition, open_terminal, - }, + terminal::{ConfirmPrompt, Message, PromptError, Terminal, open_terminal}, }; /// Where the Dotcore installer is published. @@ -40,9 +42,6 @@ const INSTALLER_URL: &str = "https://dotcore.ai/install.sh"; /// Arguments of `dotc node add`. #[derive(Debug, Args)] pub struct NodeAddArgs { - #[command(flatten)] - manager: ManagerArgs, - /// Write the token to this new file (mode 0600, removed when the command ends) instead of /// printing it. #[arg(long, value_name = "PATH", value_parser = parse_absolute_path)] @@ -51,16 +50,24 @@ pub struct NodeAddArgs { /// Allow the node that presents the token without asking. #[arg(long)] pub yes: bool, + + #[command(flatten)] + manager: ManagerArgs, } /// Starts a join on the running manager and follows it until the machine is recorded, cancelling /// the join when the command ends any other way. -pub(crate) async fn node_add(_paths: &RootPathArgs, arguments: NodeAddArgs) -> anyhow::Result<()> { - if !arguments.yes && controlling_terminal_condition() != TerminalCondition::Interactive { - anyhow::bail!( - "allowing a node needs a terminal; run in a terminal or pass --yes to allow the node that presents the token" - ); - } +pub(crate) async fn node_add( + _paths: &RootPathArgs, + arguments: NodeAddArgs, + format: OutputFormat, +) -> anyhow::Result<()> { + require_consent( + arguments.yes, + format, + "allowing a node needs a terminal; run in a terminal or pass --yes to allow the node that presents the token", + "allowing a node needs confirmation, which --yaml never asks for; pass --yes to allow the node that presents the token", + )?; let manager = arguments .manager @@ -85,13 +92,14 @@ pub(crate) async fn node_add(_paths: &RootPathArgs, arguments: NodeAddArgs) -> a let outcome = tokio::select! { biased; _ = tokio::signal::ctrl_c() => Err(anyhow::Error::new(PromptError::Cancelled)), - added = run_join(&mut joins, started, &arguments) => added, + added = run_join(&mut joins, started, &arguments, format) => added, }; match outcome { + Ok(joined) if format == OutputFormat::Yaml => write_yaml(&AddedDocument::of(&joined)), Ok(joined) => { let mut terminal = (!arguments.yes).then(open_terminal); - if let Some(records) = report_added(boxed(&mut terminal), &joined)? { - write_records(&records)?; + if let Some(text) = report_added(boxed(&mut terminal), &joined)? { + write_stdout(&text)?; } Ok(()) } @@ -111,11 +119,33 @@ struct JoinedMachine { rejoined: bool, } +/// The YAML document of a node the manager recorded. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct AddedDocument<'a> { + outcome: &'static str, + node_id: &'a str, + display_name: &'a str, + host: &'a str, +} + +impl<'a> AddedDocument<'a> { + fn of(joined: &'a JoinedMachine) -> Self { + Self { + outcome: if joined.rejoined { "rejoined" } else { "added" }, + node_id: &joined.node_id, + display_name: &joined.name, + host: &joined.host, + } + } +} + /// Announces the join command, then answers each proposal until the join ends. async fn run_join( joins: &mut SiteMembershipServiceClient, started: dotcore_proto::dotcore::site::v1::StartJoinResponse, arguments: &NodeAddArgs, + format: OutputFormat, ) -> anyhow::Result { let token_file = match &arguments.token_file { Some(path) => Some(TokenFile::create(path, &started.token)?), @@ -140,8 +170,11 @@ async fn run_join( Notices::new(boxed(&mut terminal)).warn(¬ice)?; } drop(terminal); - if let Some(records) = ready { - write_records(&records)?; + if format == OutputFormat::Yaml { + progress(&format!("On the new machine, run: {join_command}")); + progress("Waiting for the node..."); + } else if let Some(text) = ready { + write_stdout(&text)?; } let mut watch = joins @@ -246,34 +279,34 @@ async fn follow( } } -/// Tells the operator how to join, on the terminal when interactive, else as the join command -/// record. On the terminal, the installer command for a machine without Dotcore comes first when -/// there is one. Returns the records to write when there is no terminal. +/// Tells the operator how to join, on the terminal when there is one, else as plain text to write +/// on stdout. On the terminal, the installer command for a machine without Dotcore comes first +/// when there is one. Returns the text to write when there is no terminal. fn announce_ready( terminal: Option<&mut dyn Terminal>, join_command: &str, install_command: Option<&str>, ) -> anyhow::Result> { let Some(terminal) = terminal else { - return Ok(Some(format!( - "Node join ready\nDOTCORE_JOIN_COMMAND={}\n", - record_value(join_command)? - ))); + return Ok(Some(plain_text(&[ + Message::Info("On the new machine, run:".to_owned()), + Message::Command(join_command.to_owned()), + ]))); }; match install_command { Some(install_command) => { - terminal.message(&Message::Info( + terminal.prompt_context(&Message::Info( "On a new machine, install Dotcore and join with:".to_owned(), ))?; - terminal.message(&Message::Command(install_command.to_owned()))?; - terminal.message(&Message::Info( + terminal.prompt_context(&Message::Command(install_command.to_owned()))?; + terminal.prompt_context(&Message::Info( "On a machine that has Dotcore, run:".to_owned(), ))?; } - None => terminal.message(&Message::Info("On the new machine, run:".to_owned()))?, + None => terminal.prompt_context(&Message::Info("On the new machine, run:".to_owned()))?, } - terminal.message(&Message::Command(join_command.to_owned()))?; - terminal.message(&Message::Hint("Waiting for the node...".to_owned()))?; + terminal.prompt_context(&Message::Command(join_command.to_owned()))?; + terminal.prompt_context(&Message::Hint("Waiting for the node...".to_owned()))?; Ok(None) } @@ -392,39 +425,31 @@ fn decide_with_terminal( .context("the manager sent a malformed key fingerprint")?; facts.extend(fingerprint_facts(&fingerprint)); - terminal.message(&Message::Heading(heading.to_owned()))?; - terminal.message(&Message::KeyValues(facts))?; - terminal.message(&fingerprint_grid(&fingerprint))?; + terminal.prompt_context(&Message::Heading(heading.to_owned()))?; + terminal.prompt_context(&Message::KeyValues(facts))?; + terminal.prompt_context(&fingerprint_grid(&fingerprint))?; if proposal.host_differs_from_peer { - terminal.message(&Message::Warning(host_mismatch_notice(proposal)))?; + terminal.prompt_context(&Message::Warning(host_mismatch_notice(proposal)))?; } Ok(terminal.confirm(&ConfirmPrompt::new(question, false))?) } -/// Reports the recorded node, on the terminal when interactive, else as records. Returns the -/// records to write when there is no terminal. +/// Reports the recorded node, on the terminal when there is one, else as plain text to write on +/// stdout. Returns the text to write when there is no terminal. fn report_added( terminal: Option<&mut dyn Terminal>, joined: &JoinedMachine, ) -> anyhow::Result> { - let (verb, header) = if joined.rejoined { - ("Rejoined", "Node rejoined") - } else { - ("Added", "Node added") - }; - let Some(terminal) = terminal else { - return Ok(Some(format!( - "{header}\nDOTCORE_NODE_ID={}\nDOTCORE_NODE_NAME={}\nDOTCORE_NODE_HOST={}\n", - record_value(&joined.node_id)?, - record_value(&joined.name)?, - record_value(&joined.host)?, - ))); - }; - terminal.message(&Message::Success(format!( + let verb = if joined.rejoined { "Rejoined" } else { "Added" }; + let message = Message::Success(format!( "{verb} {} at {}", single_line(&joined.name), joined.host - )))?; + )); + let Some(terminal) = terminal else { + return Ok(Some(plain_text(&[message]))); + }; + terminal.message(&message)?; Ok(None) } @@ -750,7 +775,7 @@ mod tests { } #[test] - fn without_a_terminal_only_the_join_command_record_is_written() { + fn without_a_terminal_only_the_join_command_is_written() { let records = announce_ready( None, "dotc node join --token dcjoin1.abc", @@ -760,7 +785,7 @@ mod tests { assert_eq!( records.as_deref(), - Some("Node join ready\nDOTCORE_JOIN_COMMAND=dotc node join --token dcjoin1.abc\n") + Some("On the new machine, run:\n dotc node join --token dcjoin1.abc\n") ); } diff --git a/backend/cli/src/node/join.rs b/backend/cli/src/node/join.rs index cbf475c2..b9406742 100644 --- a/backend/cli/src/node/join.rs +++ b/backend/cli/src/node/join.rs @@ -6,7 +6,9 @@ //! here and never leaves; the finished node folder is what `dotcore` runs, and on a terminal the //! command then starts it, after a countdown the operator can skip. A node whose //! intact folder of the same site already exists joins again instead, with no probe or prompt, -//! keeping its key, identity, and deployments and changing only its addresses. +//! keeping its key, identity, and deployments and changing only its addresses. Asked for YAML, +//! the command never asks, so it needs `--yes`, reports its progress on stderr, prints one +//! document once the folder is installed, and never starts the node. use std::{ collections::BTreeSet, @@ -44,9 +46,9 @@ use dotcore_site::{ }, }; -use super::{ - Notices, boxed, fingerprint_facts, fingerprint_grid, lend, record_value, write_records, -}; +use serde::Serialize; + +use super::{Notices, boxed, fingerprint_facts, fingerprint_grid, lend, progress, write_stdout}; use crate::{ RootPathArgs, failure::shell_word, @@ -54,16 +56,14 @@ use crate::{ CapabilityRecommendations, InferencePick, collect_applications, collect_inference, in_dev_env, }, + output::{OutputFormat, plain_text, require_consent, write_yaml}, paths::find_executable, site::{ ApplicationsChoice, InferenceArgument, InferenceChoice, NativeWorkloadLifetimeChoice, inference_long_help, loopback_host_warning, parse_absolute_path, parse_display_name, parse_host, parse_inference, system_initial_site_prober, }, - terminal::{ - ConfirmPrompt, CountdownPrompt, InputPrompt, Message, NextStep, Terminal, - TerminalCondition, controlling_terminal_condition, open_terminal, - }, + terminal::{ConfirmPrompt, CountdownPrompt, InputPrompt, Message, Terminal, open_terminal}, }; /// Shown after the proposal is sent, while the manager operator decides. @@ -184,16 +184,18 @@ impl NodeJoinArgs { } /// Joins this machine to the site named by the token and installs its node folder. -pub(crate) async fn node_join(paths: &RootPathArgs, arguments: NodeJoinArgs) -> anyhow::Result<()> { - let mut terminal = if arguments.yes { - None - } else if controlling_terminal_condition() == TerminalCondition::Interactive { - Some(open_terminal()) - } else { - anyhow::bail!( - "joining asks for confirmation and needs a terminal; run in a terminal or pass --yes" - ); - }; +pub(crate) async fn node_join( + paths: &RootPathArgs, + arguments: NodeJoinArgs, + format: OutputFormat, +) -> anyhow::Result<()> { + require_consent( + arguments.yes, + format, + "joining asks for confirmation and needs a terminal; run in a terminal or pass --yes", + "joining asks for confirmation, which --yaml never gives; pass --yes", + )?; + let mut terminal = (!arguments.yes).then(open_terminal); let prober = system_initial_site_prober(); let timing = Timing::for_process().join; let launcher = find_executable(LAUNCHER); @@ -204,6 +206,7 @@ pub(crate) async fn node_join(paths: &RootPathArgs, arguments: NodeJoinArgs) -> &prober, timing, launcher.as_deref(), + format, ) .await?; @@ -225,6 +228,7 @@ async fn join_site( prober: &InitialSiteProber, timing: JoinTiming, launcher: Option<&Path>, + format: OutputFormat, ) -> anyhow::Result> { let site_dir = paths.site_dir()?; let command = StartCommand::new( @@ -237,18 +241,11 @@ async fn join_site( site_dir.display() ); + let run = JoinRun { timing, format }; let token = read_token(&arguments, lend(&mut terminal))?; if std::fs::symlink_metadata(&site_dir).is_ok() { let folder = open_rejoining_folder(&site_dir, &token, arguments.name.as_deref())?; - rejoin_site( - arguments, - token, - folder, - &command, - lend(&mut terminal), - timing, - ) - .await?; + rejoin_site(arguments, token, folder, &command, lend(&mut terminal), run).await?; } else { join_new_site( arguments, @@ -257,7 +254,7 @@ async fn join_site( &command, lend(&mut terminal), prober, - timing, + run, ) .await?; } @@ -268,6 +265,13 @@ async fn join_site( } } +/// How one join runs: its real-time bounds and how it reports. +#[derive(Clone, Copy)] +struct JoinRun { + timing: JoinTiming, + format: OutputFormat, +} + async fn join_new_site( arguments: NodeJoinArgs, token: JoinToken, @@ -275,10 +279,11 @@ async fn join_new_site( command: &StartCommand, mut terminal: Option<&mut dyn Terminal>, prober: &InitialSiteProber, - timing: JoinTiming, + run: JoinRun, ) -> anyhow::Result<()> { + let JoinRun { timing, format } = run; let mut connection = connect_to_manager(&token, arguments.manager_host.clone(), timing).await?; - announce_connection(&connection, lend(&mut terminal))?; + announce_connection(&connection, lend(&mut terminal), format)?; let (inference, applications) = choose_runtimes(&arguments, lend(&mut terminal), prober).await?; @@ -299,7 +304,9 @@ async fn join_new_site( } if let Some(terminal) = lend(&mut terminal) { show_fingerprint(terminal, &proposal.display_name, &key.fingerprint())?; - terminal.message(&Message::Info(APPROVAL_NOTICE.to_owned()))?; + terminal.prompt_context(&Message::Info(APPROVAL_NOTICE.to_owned()))?; + } else if format == OutputFormat::Yaml { + progress(APPROVAL_NOTICE); } let folder = loop { @@ -307,8 +314,9 @@ async fn join_new_site( Ok(folder) => break folder, Err(NodeJoinError::DuplicateName(status)) if terminal.is_some() => { let terminal = lend(&mut terminal).expect("checked by the guard"); - terminal.message(&Message::Error(status.message().to_owned()))?; - terminal.message(&Message::Hint(replaced_node_hint(&proposal.display_name)))?; + terminal.prompt_context(&Message::Error(status.message().to_owned()))?; + terminal + .prompt_context(&Message::Hint(replaced_node_hint(&proposal.display_name)))?; proposal.display_name = prompt_name(terminal, None)?; } Err(error) => return Err(join_failure(error)), @@ -316,8 +324,16 @@ async fn join_new_site( }; warn_about_addresses(&folder, &connection, lend(&mut terminal)).await?; - if let Some(records) = report_joined(lend(&mut terminal), &proposal, &folder, command)? { - write_records(&records)?; + if format == OutputFormat::Yaml { + return write_yaml(&JoinedDocument::of( + "joined", + &folder, + &proposal.display_name, + command, + )); + } + if let Some(text) = report_joined(lend(&mut terminal), &proposal, &folder, command)? { + write_stdout(&text)?; } Ok(()) } @@ -330,10 +346,11 @@ async fn rejoin_site( folder: RejoiningNodeFolder, command: &StartCommand, mut terminal: Option<&mut dyn Terminal>, - timing: JoinTiming, + run: JoinRun, ) -> anyhow::Result<()> { + let JoinRun { timing, format } = run; let mut connection = connect_to_manager(&token, arguments.manager_host.clone(), timing).await?; - announce_connection(&connection, lend(&mut terminal))?; + announce_connection(&connection, lend(&mut terminal), format)?; if let Some(ignored) = ignored_rejoin_flags(&arguments) { Notices::new(lend(&mut terminal)).warn(&format!( "{ignored} ignored: a node that joins again keeps its capabilities and execution targets" @@ -345,14 +362,16 @@ async fn rejoin_site( private_port: arguments.private_port.unwrap_or(folder.private_port()), }; if let Some(terminal) = lend(&mut terminal) { - terminal.message(&Message::Info(format!( + terminal.prompt_context(&Message::Info(format!( "Joining again from {}", folder.root().display() )))?; // The folder holds no display name; the manager shows the one the site declares. let name = arguments.name.as_deref().unwrap_or("this node"); show_fingerprint(terminal, name, &folder.fingerprint())?; - terminal.message(&Message::Info(APPROVAL_NOTICE.to_owned()))?; + terminal.prompt_context(&Message::Info(APPROVAL_NOTICE.to_owned()))?; + } else if format == OutputFormat::Yaml { + progress(APPROVAL_NOTICE); } let joined = connection .rejoin(&proposal, &folder) @@ -361,8 +380,16 @@ async fn rejoin_site( drop(folder); warn_about_addresses(&joined, &connection, lend(&mut terminal)).await?; - if let Some(records) = report_rejoined(lend(&mut terminal), &joined, command)? { - write_records(&records)?; + if format == OutputFormat::Yaml { + return write_yaml(&JoinedDocument::of( + "rejoined", + &joined, + &joined.display_name, + command, + )); + } + if let Some(text) = report_rejoined(lend(&mut terminal), &joined, command)? { + write_stdout(&text)?; } Ok(()) } @@ -410,11 +437,17 @@ fn ignored_rejoin_flags(arguments: &NodeJoinArgs) -> Option { (!flags.is_empty()).then(|| flags.join(", ")) } -/// Shows which site and manager the token reached. +/// Shows which site and manager the token reached: next to the prompts on the terminal, and on +/// stderr when the command prints YAML. fn announce_connection( connection: &JoinConnection, terminal: Option<&mut dyn Terminal>, + format: OutputFormat, ) -> anyhow::Result<()> { + if format == OutputFormat::Yaml { + progress(&format!("Connected to site {}", connection.site_id())); + return Ok(()); + } let mut notices = Notices::new(terminal); notices.info(Message::Heading(format!( "Connected to site {}", @@ -449,8 +482,42 @@ async fn warn_about_addresses( Ok(()) } -/// Reports the installed node folder, on the terminal when interactive, else as records with the -/// command that starts it. Returns the records to write when there is no terminal. +/// The YAML document of a node folder installed by joining. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct JoinedDocument { + outcome: &'static str, + site_id: String, + node_id: String, + display_name: String, + host: String, + private_address: String, + + /// The command that starts the node. + start_command: String, +} + +impl JoinedDocument { + fn of( + outcome: &'static str, + folder: &JoinedNodeFolder, + display_name: &str, + command: &StartCommand, + ) -> Self { + Self { + outcome, + site_id: folder.site_id.clone(), + node_id: folder.node_id.clone(), + display_name: display_name.to_owned(), + host: folder.host.to_string(), + private_address: folder.private_bind_address.to_string(), + start_command: command.to_string(), + } + } +} + +/// Reports the installed node folder, on the terminal when there is one, else as plain text with +/// the command that starts it. Returns the text to write when there is no terminal. fn report_joined( terminal: Option<&mut dyn Terminal>, proposal: &JoinProposal, @@ -458,15 +525,14 @@ fn report_joined( command: &StartCommand, ) -> anyhow::Result> { let Some(terminal) = terminal else { - return Ok(Some(format!( - "Node joined\nDOTCORE_SITE_ID={}\nDOTCORE_NODE_ID={}\nDOTCORE_NODE_NAME={}\nDOTCORE_NODE_HOST={}\nDOTCORE_PRIVATE_ADDR={}\nDOTCORE_START_COMMAND={}\n", - record_value(&folder.site_id)?, - record_value(&folder.node_id)?, - record_value(&proposal.display_name)?, - folder.host, - folder.private_bind_address, - record_value(&command.to_string())?, - ))); + return Ok(Some(plain_text(&[ + Message::Success(format!( + "Joined {} as {} at {}", + folder.site_id, proposal.display_name, folder.host + )), + Message::Info("Start the node with:".to_owned()), + Message::Command(command.to_string()), + ]))); }; terminal.message(&Message::Success(format!( "Joined {} as {} at {}", @@ -475,23 +541,22 @@ fn report_joined( Ok(None) } -/// Reports the rewritten node folder, on the terminal when interactive, else as records with the -/// command that starts it. Returns the records to write when there is no terminal. +/// Reports the rewritten node folder, on the terminal when there is one, else as plain text with +/// the command that starts it. Returns the text to write when there is no terminal. fn report_rejoined( terminal: Option<&mut dyn Terminal>, folder: &JoinedNodeFolder, command: &StartCommand, ) -> anyhow::Result> { let Some(terminal) = terminal else { - return Ok(Some(format!( - "Node rejoined\nDOTCORE_SITE_ID={}\nDOTCORE_NODE_ID={}\nDOTCORE_NODE_NAME={}\nDOTCORE_NODE_HOST={}\nDOTCORE_PRIVATE_ADDR={}\nDOTCORE_START_COMMAND={}\n", - record_value(&folder.site_id)?, - record_value(&folder.node_id)?, - record_value(&folder.display_name)?, - folder.host, - folder.private_bind_address, - record_value(&command.to_string())?, - ))); + return Ok(Some(plain_text(&[ + Message::Success(format!( + "Rejoined {} at {}", + folder.display_name, folder.host + )), + Message::Info("Start the node with:".to_owned()), + Message::Command(command.to_string()), + ]))); }; terminal.message(&Message::Success(format!( "Rejoined {} at {}", @@ -501,7 +566,7 @@ fn report_rejoined( } /// Starts the joined node with `launcher` once a countdown of `countdown` runs out, unless the -/// operator skips it; without a launcher, or after a skip, shows the command that starts it. +/// operator skips it; without a launcher, or after a skip, says the node is not started. /// Returns the start to carry out. fn offer_start( terminal: &mut dyn Terminal, @@ -517,9 +582,7 @@ fn offer_start( command, })); } - terminal.message(&Message::Next(vec![ - NextStep::new("Start the node:").with_command(command.to_string()), - ]))?; + terminal.message(&Message::Info("The node is not started".to_owned()))?; Ok(None) } @@ -546,7 +609,7 @@ fn read_token( let text = terminal.secret(&InputPrompt::new("Join token (hidden)"))?; match JoinToken::parse(text.trim()) { Ok(token) => return Ok(token), - Err(error) => terminal.message(&Message::Error(format!( + Err(error) => terminal.prompt_context(&Message::Error(format!( "that is not a valid join token: {}", crate::hint::describe(&error) )))?, @@ -713,7 +776,7 @@ fn prompt_name(terminal: &mut dyn Terminal, default: Option<&str>) -> anyhow::Re loop { match parse_display_name(terminal.input(&prompt)?.trim()) { Ok(name) => return Ok(name), - Err(message) => terminal.message(&Message::Error(message))?, + Err(message) => terminal.prompt_context(&Message::Error(message))?, } } } @@ -744,8 +807,8 @@ fn confirm_proposal( ("private port".to_owned(), proposal.private_port.to_string()), ); } - terminal.message(&Message::Heading("Proposal".to_owned()))?; - terminal.message(&Message::KeyValues(facts))?; + terminal.prompt_context(&Message::Heading("Proposal".to_owned()))?; + terminal.prompt_context(&Message::KeyValues(facts))?; Ok(terminal.confirm(&ConfirmPrompt::new( "Send this proposal to the manager?", true, @@ -759,11 +822,11 @@ fn show_fingerprint( name: &str, fingerprint: &CertificateFingerprint, ) -> anyhow::Result<()> { - terminal.message(&Message::Info(format!( + terminal.prompt_context(&Message::Info(format!( "Confirm this fingerprint where you approve {name}:" )))?; - terminal.message(&fingerprint_grid(fingerprint))?; - terminal.message(&Message::KeyValues(fingerprint_facts(fingerprint).to_vec()))?; + terminal.prompt_context(&fingerprint_grid(fingerprint))?; + terminal.prompt_context(&Message::KeyValues(fingerprint_facts(fingerprint).to_vec()))?; Ok(()) } @@ -1033,7 +1096,7 @@ mod tests { } #[test] - fn an_interactive_join_report_announces_the_node_and_writes_no_records() { + fn an_interactive_join_report_announces_the_node_and_writes_nothing() { let mut terminal = ScriptedTerminal::interactive([]); let records = report_joined( @@ -1049,7 +1112,7 @@ mod tests { } #[test] - fn a_rejoin_report_names_the_node_or_records_its_start_command() { + fn a_rejoin_report_names_the_node_or_prints_its_start_command() { let mut terminal = ScriptedTerminal::interactive([]); let records = report_rejoined( @@ -1070,7 +1133,7 @@ mod tests { .expect("records") .as_deref(), Some( - "Node rejoined\nDOTCORE_SITE_ID=site-1\nDOTCORE_NODE_ID=node-7\nDOTCORE_NODE_NAME=gpu-box\nDOTCORE_NODE_HOST=10.0.0.7\nDOTCORE_PRIVATE_ADDR=10.0.0.7:50053\nDOTCORE_START_COMMAND=dotcore --site-dir /srv/node\n" + "✔ Rejoined gpu-box at 10.0.0.7\nStart the node with:\n dotcore --site-dir /srv/node\n" ) ); } @@ -1089,7 +1152,7 @@ mod tests { } #[test] - fn an_unattended_join_report_is_records_only() { + fn an_unattended_join_report_prints_the_start_command() { let records = report_joined( None, &proposal(), @@ -1101,7 +1164,7 @@ mod tests { assert_eq!( records.as_deref(), Some( - "Node joined\nDOTCORE_SITE_ID=site-1\nDOTCORE_NODE_ID=node-7\nDOTCORE_NODE_NAME=gpu-box\nDOTCORE_NODE_HOST=10.0.0.7\nDOTCORE_PRIVATE_ADDR=10.0.0.7:50053\nDOTCORE_START_COMMAND=dotcore --site-dir /srv/node\n" + "✔ Joined site-1 as gpu-box at 10.0.0.7\nStart the node with:\n dotcore --site-dir /srv/node\n" ) ); } @@ -1457,13 +1520,9 @@ mod tests { } #[test] - fn a_skipped_start_or_a_dotc_without_launcher_shows_the_start_command() { + fn a_skipped_start_or_a_dotc_without_launcher_says_the_node_is_not_started() { let command = StartCommand::new(Some(Path::new("/srv/node")), None); - let hint = [ - "Next", - " › Start the node:", - " dotcore --site-dir /srv/node", - ]; + let hint = ["The node is not started"]; let mut skipped = ScriptedTerminal::interactive([ScriptedAnswer::Countdown(false)]); let start = offer_start( diff --git a/backend/cli/src/node/leave.rs b/backend/cli/src/node/leave.rs index 2aea1911..ba5c8458 100644 --- a/backend/cli/src/node/leave.rs +++ b/backend/cli/src/node/leave.rs @@ -15,13 +15,16 @@ use dotcore_site::{ reset::persistence::SitePersistenceReset, }; -use super::{Notices, record_value, write_records}; +use serde::Serialize; + +use super::Notices; use crate::{ RootPathArgs, + output::{LazyTerminal, OutputFormat, require_consent, write_yaml}, runtime_confirmation::{ RuntimeRemovalApproval, approve_runtime_removal, site_runtime_cleanups, }, - terminal::{ConfirmPrompt, Message, PromptError, Terminal, TerminalCondition, open_terminal}, + terminal::{ConfirmPrompt, Message, PromptError, Terminal}, }; /// Arguments of `dotc node leave`. @@ -36,15 +39,17 @@ pub struct NodeLeaveArgs { pub(crate) async fn node_leave( paths: &RootPathArgs, arguments: NodeLeaveArgs, + format: OutputFormat, ) -> anyhow::Result<()> { let site_dir = paths.site_dir()?; - let mut terminal = open_terminal(); - if !arguments.yes && terminal.condition() == TerminalCondition::NonInteractive { - anyhow::bail!( - "leaving the site needs a terminal; run in a terminal or pass --yes to stop the node's workloads and delete its folder without confirmation" - ); - } + require_consent( + arguments.yes, + format, + "leaving the site needs a terminal; run in a terminal or pass --yes to stop the node's workloads and delete its folder without confirmation", + "leaving the site needs confirmation, which --yaml never asks for; pass --yes to stop the node's workloads and delete its folder", + )?; + let mut terminal = LazyTerminal::new(); let cleanups = site_runtime_cleanups(None); let leave = NodeLeave::open(&site_dir, Arc::clone(&cleanups)) .with_context(|| format!("cannot leave the site from {}", site_dir.display()))?; @@ -63,7 +68,7 @@ pub(crate) async fn node_leave( })?; if !arguments.yes { - review(terminal.as_mut(), &leave)?; + review(&mut terminal, &leave)?; } if inventory.resources.is_empty() && !arguments.yes @@ -72,7 +77,7 @@ pub(crate) async fn node_leave( return Err(PromptError::Cancelled.into()); } approve_runtime_removal( - terminal.as_mut(), + &mut terminal, &site_dir, &inventory, &RuntimeRemovalApproval { @@ -104,24 +109,33 @@ pub(crate) async fn node_leave( ) })?; - if arguments.yes { - write_records(&format!( - "Node left\nDOTCORE_SITE_ID={}\nDOTCORE_NODE_ID={}\n", - record_value(&site_id)?, - record_value(&node_id)? - )) + if format == OutputFormat::Yaml { + write_yaml(&LeftDocument { + outcome: "left", + site_id, + node_id, + }) } else { - Notices::new(Some(terminal.as_mut())).success(&format!("Left {site_id}")) + Notices::new(Some(&mut terminal)).success(&format!("Left {site_id}")) } } +/// The YAML document of a node that left its site. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct LeftDocument { + outcome: &'static str, + site_id: String, + node_id: String, +} + /// Shows which node leaves, and what leaving will stop and delete. fn review(terminal: &mut dyn Terminal, leave: &NodeLeave) -> anyhow::Result<()> { - terminal.message(&Message::Heading(format!( + terminal.prompt_context(&Message::Heading(format!( "This node leaves site {}", leave.site_id() )))?; - terminal.message(&Message::KeyValues(vec![ + terminal.prompt_context(&Message::KeyValues(vec![ ( "targets".to_owned(), leave.execution_target_ids().len().to_string(), diff --git a/backend/cli/src/node/list.rs b/backend/cli/src/node/list.rs index 703d9f3e..192508aa 100644 --- a/backend/cli/src/node/list.rs +++ b/backend/cli/src/node/list.rs @@ -1,64 +1,124 @@ //! `dotc node list`: shows the nodes a site declares, with their addresses, execution targets, //! and placed deployments, for example the manager and one GPU worker. //! -//! It reads the site without locking it, so it works while the manager runs. On a terminal it -//! prints a table, with optional detail columns and execution targets; without one it prints one -//! record block per node on stdout, always carrying every field. +//! It reads the site without locking it, so it works while the manager runs. It prints a table, +//! with optional detail columns and execution targets, on the terminal or as plain text without +//! one. Asked for YAML, it prints the site's nodes with every fact, whatever the detail flags. use anyhow::Context; use clap::Args; -use dotcore_site::membership::{ListedNode, list_site_nodes}; +use dotcore_proto::dotcore::site::v1::SiteNode; +use dotcore_site::membership::{ListedNode, ListedTarget, list_site_nodes}; +use serde::Serialize; -use super::{record_value, write_records}; use crate::{ RootPathArgs, - terminal::{Message, TerminalCondition, controlling_terminal_condition, open_terminal}, + output::{OutputFormat, present, write_yaml}, + terminal::Message, }; /// Arguments of `dotc node list`. #[derive(Debug, Args)] pub struct NodeListArgs { /// Also show the address each node uses to reach the manager and whether the manager trusts - /// the node's certificate; terminal output only. + /// the node's certificate. #[arg(long)] pub details: bool, - /// Also list each node's execution targets; terminal output only. + /// Also list each node's execution targets. #[arg(long)] pub execution_targets: bool, } -/// Lists the site's nodes on the terminal, else as records. -pub(crate) fn node_list(paths: &RootPathArgs, arguments: NodeListArgs) -> anyhow::Result<()> { +/// Lists the site's nodes as YAML when asked, else as a table. +pub(crate) fn node_list( + paths: &RootPathArgs, + arguments: NodeListArgs, + format: OutputFormat, +) -> anyhow::Result<()> { let site_dir = paths.site_dir()?; let listing = list_site_nodes(&site_dir, &dotcore::model::site_declaration_rules()) .with_context(|| format!("cannot list the nodes of {}", site_dir.display()))?; - if controlling_terminal_condition() == TerminalCondition::Interactive { - let mut terminal = open_terminal(); - terminal.message(&Message::Heading(format!( - "Nodes of site {}", - listing.site_id - )))?; - terminal.message(&table(&listing.nodes, arguments.details))?; - let targets = if arguments.execution_targets { - target_rows(&listing.nodes) - } else { - Vec::new() - }; - if !targets.is_empty() { - terminal.message(&Message::Heading("Execution targets".to_owned()))?; - terminal.message(&Message::KeyValues(targets))?; + if format == OutputFormat::Yaml { + return write_yaml(&NodeListDocument::of(&listing.site_id, &listing.nodes)); + } + + let mut messages = vec![ + Message::Heading(format!("Nodes of site {}", listing.site_id)), + table(&listing.nodes, arguments.details), + ]; + let targets = if arguments.execution_targets { + target_rows(&listing.nodes) + } else { + Vec::new() + }; + if !targets.is_empty() { + messages.push(Message::Heading("Execution targets".to_owned())); + messages.push(Message::KeyValues(targets)); + } + present(&messages) +} + +/// The site's nodes read from its folder: each declared node as the site declares it, plus what +/// the manager's folder knows about it. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct NodeListDocument<'a> { + site_id: &'a str, + nodes: Vec>, +} + +/// One declared node with its role, trust and placements. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct NodeDocument<'a> { + node: &'a SiteNode, + is_manager: bool, + + /// Whether the manager holds a pin for the node's certificate; the manager has none. + pinned: bool, + execution_targets: Vec>, + placed_models: usize, + placed_applications: usize, +} + +/// One execution target a node provides. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct TargetDocument<'a> { + id: &'a str, + display_name: &'a str, + kind: &'static str, + platform: &'a str, +} + +impl<'a> NodeListDocument<'a> { + fn of(site_id: &'a str, nodes: &'a [ListedNode]) -> Self { + Self { + site_id, + nodes: nodes + .iter() + .map(|listed| NodeDocument { + node: &listed.node, + is_manager: listed.is_manager, + pinned: listed.pinned, + execution_targets: listed.execution_targets.iter().map(target).collect(), + placed_models: listed.placed_models, + placed_applications: listed.placed_applications, + }) + .collect(), } - return Ok(()); } +} - let blocks = listing - .nodes - .iter() - .map(record_block) - .collect::>>()?; - write_records(&blocks.join("\n")) +fn target(target: &ListedTarget) -> TargetDocument<'_> { + TargetDocument { + id: &target.id, + display_name: &target.display_name, + kind: target.kind, + platform: &target.platform, + } } /// Builds the nodes table, header first. `details` adds the manager address and trust columns. @@ -113,33 +173,6 @@ fn target_rows(nodes: &[ListedNode]) -> Vec<(String, String)> { .collect() } -/// Renders one node as a record block ending in a newline. -fn record_block(listed: &ListedNode) -> anyhow::Result { - let node = &listed.node; - let mut block = format!( - "Node\nDOTCORE_NODE_ID={}\nDOTCORE_NODE_NAME={}\nDOTCORE_NODE_ROLE={}\nDOTCORE_NODE_HOST={}\nDOTCORE_NODE_MANAGER_HOST={}\nDOTCORE_NODE_PIN={}\n", - record_value(&node.node_id)?, - record_value(&node.display_name)?, - role(listed), - record_value(&node.host)?, - record_value(manager_host(listed))?, - pin(listed), - ); - for target in &listed.execution_targets { - block.push_str(&format!( - "DOTCORE_NODE_EXECUTION_TARGET={} {} {}\n", - record_value(&target.id)?, - target.kind, - record_value(&target.platform)? - )); - } - block.push_str(&format!( - "DOTCORE_NODE_MODEL_DEPLOYMENTS={}\nDOTCORE_NODE_APPLICATION_DEPLOYMENTS={}\n", - listed.placed_models, listed.placed_applications - )); - Ok(block) -} - fn role(listed: &ListedNode) -> &'static str { if listed.is_manager { "manager" @@ -148,22 +181,6 @@ fn role(listed: &ListedNode) -> &'static str { } } -fn manager_host(listed: &ListedNode) -> &str { - if listed.node.manager_host.is_empty() { - "default" - } else { - &listed.node.manager_host - } -} - -fn pin(listed: &ListedNode) -> &'static str { - match (listed.is_manager, listed.pinned) { - (true, _) => "own identity", - (false, true) => "yes", - (false, false) => "no", - } -} - /// The address the node uses to reach the manager, `-` when it uses the manager's declared host. fn manager_address(listed: &ListedNode) -> &str { if listed.node.manager_host.is_empty() { @@ -281,24 +298,4 @@ mod tests { ] ); } - - #[test] - fn target_record_keeps_the_id_kind_and_platform() { - let mut spark = listed("spark", "node-2", "spark.example", "", false, true); - spark.execution_targets = vec![ListedTarget { - id: "execution-target-0a1b".to_owned(), - display_name: "Simulated models".to_owned(), - kind: "model", - platform: "linux/arm64".to_owned(), - }]; - - let block = record_block(&spark).expect("record"); - - assert!( - block.contains( - "DOTCORE_NODE_EXECUTION_TARGET=execution-target-0a1b model linux/arm64\n" - ), - "{block}" - ); - } } diff --git a/backend/cli/src/node/mod.rs b/backend/cli/src/node/mod.rs index 8a478b82..dc70c59b 100644 --- a/backend/cli/src/node/mod.rs +++ b/backend/cli/src/node/mod.rs @@ -6,8 +6,8 @@ //! nodes. //! //! The token travels through `--token`, a file, or a hidden prompt; it is spent by one join and -//! is cancelled when `node add` exits. Operator prompts and notices use the controlling terminal; result records -//! stay on stdout, for example `DOTCORE_NODE_ID=node-0123456789`. +//! is cancelled when `node add` exits. Operator prompts and notices use the controlling terminal; +//! results stay on stdout, as plain text or, asked for YAML, one document per command. mod add; mod join; @@ -27,7 +27,8 @@ use dotcore_site::{ use crate::{ RootPathArgs, - terminal::{GridColor, Message, NextStep, Terminal}, + output::{OutputFormat, plain_text, present_on}, + terminal::{GridColor, Message, Terminal}, }; use add::{NodeAddArgs, node_add}; pub(crate) use join::RejoinNameMismatch; @@ -36,8 +37,7 @@ use leave::{NodeLeaveArgs, node_leave}; use list::{NodeListArgs, node_list}; use remove::{NodeRemoveArgs, node_remove}; -/// Commands that manage site membership: `add` and `remove` on the running manager (`remove` also -/// on a stopped one), `join` and `leave` on the node's machine, and `list` on the manager. +/// Commands that manage the nodes of a site and this machine's membership in one. #[derive(Debug, Args)] #[command(arg_required_else_help = true)] pub struct NodeCommand { @@ -48,34 +48,45 @@ pub struct NodeCommand { /// Actions supported by the node command group. #[derive(Debug, Subcommand)] enum NodeSubcommand { - /// Start a join on the running site manager and wait for one new node to join through + /// Allow one new machine to join the site + /// + /// Starts a join on the running site manager and waits for one machine to join through /// `dotc node join`. Add(NodeAddArgs), - /// Join this machine to a site using the token printed by `dotc node add`. + /// Join this machine to a site with the token `dotc node add` printed Join(NodeJoinArgs), - /// Remove a worker node from the site, through the running manager or from this stopped - /// site. Run `dotc node leave` on the removed machine afterwards. + /// Remove a worker node from the site + /// + /// Works through the running manager, or on this stopped site. Run `dotc node leave` on the + /// removed machine afterwards. Remove(NodeRemoveArgs), - /// Stop this node's workloads and delete its node folder; runs on the removed machine with - /// its server stopped. + /// Leave the site: stop this node's workloads and delete its node folder + /// + /// Runs on the removed machine with its server stopped. Leave(NodeLeaveArgs), - /// List the nodes of this site with their addresses and deployments; runs on the manager, - /// which may be running. + /// List the site's nodes with their addresses and deployments + /// + /// Runs on the manager's machine, whether or not the manager is running. + #[command(alias = "ls")] List(NodeListArgs), } impl NodeCommand { - pub(crate) async fn dispatch(self, paths: &RootPathArgs) -> anyhow::Result<()> { + pub(crate) async fn dispatch( + self, + paths: &RootPathArgs, + format: OutputFormat, + ) -> anyhow::Result<()> { match self.command { - Some(NodeSubcommand::Add(arguments)) => node_add(paths, arguments).await, - Some(NodeSubcommand::Join(arguments)) => node_join(paths, arguments).await, - Some(NodeSubcommand::Remove(arguments)) => node_remove(paths, arguments).await, - Some(NodeSubcommand::Leave(arguments)) => node_leave(paths, arguments).await, - Some(NodeSubcommand::List(arguments)) => node_list(paths, arguments), + Some(NodeSubcommand::Add(arguments)) => node_add(paths, arguments, format).await, + Some(NodeSubcommand::Join(arguments)) => node_join(paths, arguments, format).await, + Some(NodeSubcommand::Remove(arguments)) => node_remove(paths, arguments, format).await, + Some(NodeSubcommand::Leave(arguments)) => node_leave(paths, arguments, format).await, + Some(NodeSubcommand::List(arguments)) => node_list(paths, arguments, format), None => anyhow::bail!("node command requires an action"), } } @@ -94,8 +105,8 @@ impl NodeCommand { } } -/// Where operator-facing notices go: the guided terminal when there is one, else stderr, which -/// carries diagnostics when the command runs unattended. +/// Where operator-facing notices go: with a terminal, outcomes are command output and context sits +/// next to the prompts; without one, stderr carries them when the command runs unattended. struct Notices<'a> { terminal: Option<&'a mut dyn Terminal>, } @@ -105,36 +116,40 @@ impl<'a> Notices<'a> { Self { terminal } } - /// Shows context the operator can read but an unattended run does not need. + /// Shows context the operator can read but an unattended run does not need, next to the + /// prompts. fn info(&mut self, message: Message) -> anyhow::Result<()> { if let Some(terminal) = self.terminal.as_deref_mut() { - terminal.message(&message)?; + terminal.prompt_context(&message)?; } Ok(()) } - /// Reports a positive outcome on the terminal. + /// Reports a positive outcome: as command output on the terminal, else as a plain line on + /// stdout. fn success(&mut self, text: &str) -> anyhow::Result<()> { - if let Some(terminal) = self.terminal.as_deref_mut() { - terminal.message(&Message::Success(text.to_owned()))?; + let message = Message::Success(text.to_owned()); + match self.terminal.as_deref_mut() { + Some(terminal) => present_on(terminal, &[message]), + None => write_stdout(&plain_text(&[message])), } - Ok(()) } - /// Tells the operator what to do next: as next steps on the terminal, else as `plain` on - /// stderr so stdout keeps only records. - fn instruct(&mut self, steps: Vec, plain: &str) -> anyhow::Result<()> { + /// States a fact the operator still needs after an outcome: as an info line on the terminal, + /// else as a notice on stderr. + fn notice(&mut self, text: &str) -> anyhow::Result<()> { match self.terminal.as_deref_mut() { - Some(terminal) => terminal.message(&Message::Next(steps))?, - None => eprintln!("Notice: {plain}"), + Some(terminal) => terminal.message(&Message::Info(text.to_owned()))?, + None => eprintln!("Notice: {text}"), } Ok(()) } - /// Shows something the operator should double-check. + /// Shows something the operator should double-check: next to the prompts on the terminal, + /// else on stderr. fn warn(&mut self, text: &str) -> anyhow::Result<()> { match self.terminal.as_deref_mut() { - Some(terminal) => terminal.message(&Message::Warning(text.to_owned()))?, + Some(terminal) => terminal.prompt_context(&Message::Warning(text.to_owned()))?, None => eprintln!("Warning: {text}"), } Ok(()) @@ -157,22 +172,19 @@ fn lend<'a>(terminal: &'a mut Option<&mut dyn Terminal>) -> Option<&'a mut dyn T } } -/// Writes result records to stdout and flushes them so a waiting process sees them promptly. -pub(crate) fn write_records(records: &str) -> anyhow::Result<()> { +/// Reports progress of a long-running command on stderr, where a YAML run keeps what it says +/// besides its one final document. +fn progress(text: &str) { + eprintln!("{text}"); +} + +/// Writes plain text to stdout and flushes it so a waiting process sees it promptly. +pub(crate) fn write_stdout(text: &str) -> anyhow::Result<()> { let mut stdout = std::io::stdout().lock(); stdout - .write_all(records.as_bytes()) + .write_all(text.as_bytes()) .and_then(|()| stdout.flush()) - .context("write result records") -} - -/// Rejects a record value that could forge an extra record line. -pub(crate) fn record_value(value: &str) -> anyhow::Result<&str> { - anyhow::ensure!( - !value.contains(['\r', '\n']), - "result value must not contain carriage returns or newlines" - ); - Ok(value) + .context("write command output") } /// The grouped key fingerprint as two facts, the second line under the first, so the operator diff --git a/backend/cli/src/node/remove.rs b/backend/cli/src/node/remove.rs index f0c728aa..aca03fad 100644 --- a/backend/cli/src/node/remove.rs +++ b/backend/cli/src/node/remove.rs @@ -6,38 +6,41 @@ //! the write. Both show what the removal changes and ask for confirmation. A node that still has //! deployments is refused unless the operator chose to forget them, which also deletes the routes //! only those deployments serve; the running manager forgets them only for a node that is not -//! connected. +//! connected. Asked for YAML, the command never asks, so it needs `--yes`, and prints the +//! manager's removal response, which the stopped site's removal reports in the same shape. use anyhow::Context; use clap::Args; use dotcore::model::engine::declaration_validator; -use dotcore_proto::dotcore::site::v1::{ - ExecutionTarget, ListMachinesRequest, MachineRemovalDeployment, MachineRemovalDeploymentKind, - MachineRemovalPlan, MachineRemovalRefusal, RemoveMachineRequest, - execution_target::RuntimeBinding, remove_machine_response, +use dotcore_proto::{ + dotcore::site::v1::{ + ExecutionTarget, ListMachinesRequest, MachineRemovalDeployment, + MachineRemovalDeploymentKind, MachineRemovalPlan, MachineRemovalRefusal, + RemoveMachineRequest, RemoveMachineResponse, execution_target::RuntimeBinding, + remove_machine_response, + }, + google::protobuf::Empty, }; use dotcore_site::{ SITE_FILE, initial::validation::SiteInputBundleValidator, - membership::{NodeRemoval, NodeRemovalPlan, OfflineSite, OfflineSiteError, looks_like_node_id}, + membership::{ + NodeRemoval, NodeRemovalPlan, OfflineSite, OfflineSiteError, looks_like_node_id, + removal_plan, + }, }; -use super::{Notices, boxed, record_value, write_records}; +use super::{Notices, boxed}; use crate::{ RootPathArgs, management::{ManagementError, ManagerArgs, single_line}, - terminal::{ - ConfirmPrompt, Message, NextStep, PromptError, Terminal, TerminalCondition, - controlling_terminal_condition, open_terminal, - }, + output::{OutputFormat, require_consent, write_yaml}, + terminal::{ConfirmPrompt, Message, PromptError, Terminal, open_terminal}, }; /// Arguments of `dotc node remove`. #[derive(Debug, Args)] pub struct NodeRemoveArgs { - #[command(flatten)] - manager: ManagerArgs, - /// Display name or node id of the worker node to remove. #[arg(value_name = "NODE")] pub node: String, @@ -51,6 +54,9 @@ pub struct NodeRemoveArgs { /// Remove the node without asking for confirmation. #[arg(long)] pub yes: bool, + + #[command(flatten)] + manager: ManagerArgs, } /// Removes the node after the operator confirms: through the site manager when it holds the site, @@ -58,15 +64,17 @@ pub struct NodeRemoveArgs { pub(crate) async fn node_remove( paths: &RootPathArgs, arguments: NodeRemoveArgs, + format: OutputFormat, ) -> anyhow::Result<()> { - if !arguments.yes && controlling_terminal_condition() != TerminalCondition::Interactive { - anyhow::bail!( - "removing a node needs a terminal; run in a terminal or pass --yes to remove it without confirmation" - ); - } + require_consent( + arguments.yes, + format, + "removing a node needs a terminal; run in a terminal or pass --yes to remove it without confirmation", + "removing a node needs confirmation, which --yaml never asks for; pass --yes to remove it", + )?; match open_stopped_site(paths)? { - Some(site) => remove_from_stopped_site(&site, &arguments), - None => remove_from_running_site(&arguments).await, + Some(site) => remove_from_stopped_site(&site, &arguments, format), + None => remove_from_running_site(&arguments, format).await, } } @@ -94,7 +102,11 @@ fn open_stopped_site(paths: &RootPathArgs) -> anyhow::Result } /// Plans, confirms and applies the removal on the stopped site. -fn remove_from_stopped_site(site: &OfflineSite, arguments: &NodeRemoveArgs) -> anyhow::Result<()> { +fn remove_from_stopped_site( + site: &OfflineSite, + arguments: &NodeRemoveArgs, + format: OutputFormat, +) -> anyhow::Result<()> { let plan = match site .plan_node_removal(&arguments.node, arguments.forget_deployments) .with_context(|| format!("cannot remove node {:?}", arguments.node))? @@ -102,7 +114,7 @@ fn remove_from_stopped_site(site: &OfflineSite, arguments: &NodeRemoveArgs) -> a NodeRemoval::Planned(plan) => plan, NodeRemoval::AlreadyRemoved { node_id } => { let mut terminal = (!arguments.yes).then(open_terminal); - return report_already_removed(boxed(&mut terminal), &node_id); + return report_already_removed(boxed(&mut terminal), &node_id, format); } }; @@ -113,11 +125,15 @@ fn remove_from_stopped_site(site: &OfflineSite, arguments: &NodeRemoveArgs) -> a } site.remove_node(&plan) .with_context(|| format!("cannot remove node {:?}", plan.node.display_name))?; - report_removed(boxed(&mut terminal), &review, false) + let response = removed_response(removal_plan(&plan)); + report_removed(boxed(&mut terminal), &review, false, &response, format) } /// Previews, confirms and applies the removal through the running site manager. -async fn remove_from_running_site(arguments: &NodeRemoveArgs) -> anyhow::Result<()> { +async fn remove_from_running_site( + arguments: &NodeRemoveArgs, + format: OutputFormat, +) -> anyhow::Result<()> { let manager = arguments .manager .connect() @@ -145,7 +161,7 @@ async fn remove_from_running_site(arguments: &NodeRemoveArgs) -> anyhow::Result< Some(remove_machine_response::Outcome::WouldRemove(plan)) => RemovalReview::running(&plan), Some(remove_machine_response::Outcome::AlreadyRemoved(_)) => { let mut terminal = (!arguments.yes).then(open_terminal); - return report_already_removed(boxed(&mut terminal), &request.node_id); + return report_already_removed(boxed(&mut terminal), &request.node_id, format); } Some(remove_machine_response::Outcome::Refused(refusal)) => { return Err(refused(&arguments.node, &refusal)); @@ -168,10 +184,12 @@ async fn remove_from_running_site(arguments: &NodeRemoveArgs) -> anyhow::Result< .outcome; match removed { Some(remove_machine_response::Outcome::Removed(plan)) => { - report_removed(boxed(&mut terminal), &RemovalReview::running(&plan), true) + let review = RemovalReview::running(&plan); + let response = removed_response(plan); + report_removed(boxed(&mut terminal), &review, true, &response, format) } Some(remove_machine_response::Outcome::AlreadyRemoved(_)) => { - report_already_removed(boxed(&mut terminal), &request.node_id) + report_already_removed(boxed(&mut terminal), &request.node_id, format) } Some(remove_machine_response::Outcome::Refused(refusal)) => { Err(refused(&arguments.node, &refusal)) @@ -229,7 +247,6 @@ async fn resolve_node( /// What the operator reviews before a removal, and what is reported after it. struct RemovalReview { - node_id: String, name: String, /// Facts about the node, such as its host and execution targets. @@ -245,7 +262,6 @@ struct RemovalReview { impl RemovalReview { fn stopped(plan: &NodeRemovalPlan) -> Self { Self { - node_id: plan.node.node_id.clone(), name: plan.node.display_name.clone(), facts: vec![ ("host".to_owned(), plan.node.host.clone()), @@ -275,7 +291,6 @@ impl RemovalReview { fn running(plan: &MachineRemovalPlan) -> Self { Self { - node_id: plan.node_id.clone(), name: plan.display_name.clone(), facts: vec![( "targets".to_owned(), @@ -306,16 +321,16 @@ impl RemovalReview { /// Shows the node, its execution targets, and every declaration the removal drops, then asks. fn confirm(terminal: &mut dyn Terminal, review: &RemovalReview) -> anyhow::Result<()> { - terminal.message(&Message::Heading(format!( + terminal.prompt_context(&Message::Heading(format!( "Remove {} from the site", review.name )))?; - terminal.message(&Message::KeyValues(review.facts.clone()))?; + terminal.prompt_context(&Message::KeyValues(review.facts.clone()))?; if !review.forgotten.is_empty() { - terminal.message(&Message::Warning( + terminal.prompt_context(&Message::Warning( "These deployments are dropped without cleaning up the node".to_owned(), ))?; - terminal.message(&Message::KeyValues( + terminal.prompt_context(&Message::KeyValues( review .forgotten .iter() @@ -324,10 +339,10 @@ fn confirm(terminal: &mut dyn Terminal, review: &RemovalReview) -> anyhow::Resul ))?; } if !review.routes.is_empty() { - terminal.message(&Message::Warning( + terminal.prompt_context(&Message::Warning( "These routes only served those deployments and are deleted".to_owned(), ))?; - terminal.message(&Message::KeyValues( + terminal.prompt_context(&Message::KeyValues( review .routes .iter() @@ -367,49 +382,33 @@ fn target_summary(targets: &[ExecutionTarget]) -> String { } } -/// Reports the removal, on the terminal when interactive, else as records. A running site's -/// manager has already told the machine to stop. +/// The manager's response to a removal that went through, with what it changed. +fn removed_response(plan: MachineRemovalPlan) -> RemoveMachineResponse { + RemoveMachineResponse { + outcome: Some(remove_machine_response::Outcome::Removed(plan)), + } +} + +/// Reports the removal as YAML when asked, else as a success line. A running site's manager has already told the machine to stop. fn report_removed( terminal: Option<&mut dyn Terminal>, review: &RemovalReview, running: bool, + response: &RemoveMachineResponse, + format: OutputFormat, ) -> anyhow::Result<()> { let mut notices = Notices::new(terminal); - if notices.terminal.is_some() { - notices.success(&format!("Removed {}", review.name))?; + if format == OutputFormat::Yaml { + write_yaml(response)?; } else { - let mut records = format!( - "Node removed\nDOTCORE_NODE_ID={}\nDOTCORE_NODE_NAME={}\n", - record_value(&review.node_id)?, - record_value(&review.name)?, - ); - for (id, _, _) in &review.forgotten { - records.push_str(&format!( - "DOTCORE_FORGOTTEN_DEPLOYMENT={}\n", - record_value(id)? - )); - } - for (id, _) in &review.routes { - records.push_str(&format!("DOTCORE_DELETED_ROUTE={}\n", record_value(id)?)); - } - write_records(&records)?; + notices.success(&format!("Removed {}", review.name))?; } if running { - notices.instruct( - vec![ - NextStep::new("The machine stops Dotcore by itself. To clean it up, run there:") - .with_command("dotc node leave"), - ], - "The removed machine stops Dotcore by itself; run `dotc node leave` on it to stop its workloads and delete its node folder.", + notices.notice( + "The removed machine stops Dotcore by itself; its workloads and node folder remain", ) } else { - notices.instruct( - vec![ - NextStep::new("On that machine, stop its server, then run:") - .with_command("dotc node leave"), - ], - "Stop the removed node's server, then run `dotc node leave` on that machine to stop its workloads and delete its node folder.", - ) + notices.notice("The removed machine keeps its workloads and node folder") } } @@ -417,19 +416,14 @@ fn report_removed( fn report_already_removed( terminal: Option<&mut dyn Terminal>, node_id: &str, + format: OutputFormat, ) -> anyhow::Result<()> { - match terminal { - Some(terminal) => { - terminal.message(&Message::Success(format!( - "{node_id} is already removed from the site" - )))?; - Ok(()) - } - None => write_records(&format!( - "Node already removed\nDOTCORE_NODE_ID={}\n", - record_value(node_id)? - )), + if format == OutputFormat::Yaml { + return write_yaml(&RemoveMachineResponse { + outcome: Some(remove_machine_response::Outcome::AlreadyRemoved(Empty {})), + }); } + Notices::new(terminal).success(&format!("{node_id} is already removed from the site")) } /// The manager's refusal; its message names the deployments, routes or applications that block diff --git a/backend/cli/src/output.rs b/backend/cli/src/output.rs new file mode 100644 index 00000000..12f93275 --- /dev/null +++ b/backend/cli/src/output.rs @@ -0,0 +1,249 @@ +//! Machine-readable command results: one YAML document per result on stdout. +//! +//! A command asked for YAML writes its result as the management response's protobuf JSON mapping +//! rendered as YAML, so scripts and agents read the same shape the API returns. A streaming +//! command writes one document per entry, separated by `---`. Failures never go through here: +//! they stay plain text on stderr. + +use std::{ + collections::BTreeSet, + io::{self, Write}, +}; + +use anyhow::Context; +use serde::Serialize; + +use crate::terminal::{ + ConfirmPrompt, CountdownPrompt, InputPrompt, Message, MultiSelectPrompt, PromptError, + SelectPrompt, Terminal, TerminalCondition, controlling_terminal_condition, open_terminal, +}; + +/// How a command presents its result on stdout. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum OutputFormat { + /// Tables and messages for a person, as plain text without a terminal. + Human, + + /// One YAML document per result. + Yaml, +} + +/// The process terminal, opened on first use. A command that never asks or shows anything on the +/// terminal, such as one given `--yes` or YAML output, never touches the controlling terminal. +#[derive(Default)] +pub(crate) struct LazyTerminal { + opened: Option>, +} + +impl LazyTerminal { + pub(crate) fn new() -> Self { + Self::default() + } + + fn terminal(&mut self) -> &mut dyn Terminal { + self.opened.get_or_insert_with(open_terminal).as_mut() + } +} + +impl Terminal for LazyTerminal { + fn condition(&self) -> TerminalCondition { + match &self.opened { + Some(terminal) => terminal.condition(), + None => controlling_terminal_condition(), + } + } + + fn select(&mut self, prompt: &SelectPrompt) -> Result { + self.terminal().select(prompt) + } + + fn multi_select(&mut self, prompt: &MultiSelectPrompt) -> Result, PromptError> { + self.terminal().multi_select(prompt) + } + + fn confirm(&mut self, prompt: &ConfirmPrompt) -> Result { + self.terminal().confirm(prompt) + } + + fn input(&mut self, prompt: &InputPrompt) -> Result { + self.terminal().input(prompt) + } + + fn secret(&mut self, prompt: &InputPrompt) -> Result { + self.terminal().secret(prompt) + } + + fn countdown(&mut self, prompt: &CountdownPrompt) -> Result { + self.terminal().countdown(prompt) + } + + fn message(&mut self, message: &Message) -> Result<(), PromptError> { + self.terminal().message(message) + } + + fn prompt_context(&mut self, message: &Message) -> Result<(), PromptError> { + self.terminal().prompt_context(message) + } +} + +/// Fails before anything changes when the operator passed no `--yes` and no question can be asked: +/// YAML output never asks, and otherwise a controlling terminal must be there to ask on. +/// `human` and `yaml` are the failures for each case, and both name how to answer. +pub(crate) fn require_consent( + yes: bool, + format: OutputFormat, + human: &str, + yaml: &str, +) -> anyhow::Result<()> { + if yes { + return Ok(()); + } + if format == OutputFormat::Yaml { + anyhow::bail!("{yaml}"); + } + if controlling_terminal_condition() != TerminalCondition::Interactive { + anyhow::bail!("{human}"); + } + Ok(()) +} + +/// Lays messages out as plain lines for stdout, with a blank line before each heading but the +/// first, for a result a person reads that needs no terminal. +pub(crate) fn plain_text(messages: &[Message]) -> String { + let mut text = String::new(); + for (index, message) in messages.iter().enumerate() { + if index > 0 && matches!(message, Message::Heading(_)) { + text.push('\n'); + } + for line in message.plain_lines() { + text.push_str(&line); + text.push('\n'); + } + } + text +} + +/// Presents messages to a person: on the controlling terminal when there is one, else as plain +/// text on stdout. +pub(crate) fn present(messages: &[Message]) -> anyhow::Result<()> { + if controlling_terminal_condition() == TerminalCondition::Interactive { + return present_on(open_terminal().as_mut(), messages); + } + write_plain(messages) +} + +/// Presents messages on `terminal` when it is interactive, else as plain text on stdout. +pub(crate) fn present_on(terminal: &mut dyn Terminal, messages: &[Message]) -> anyhow::Result<()> { + if terminal.condition() != TerminalCondition::Interactive { + return write_plain(messages); + } + for message in messages { + terminal.message(message)?; + } + Ok(()) +} + +/// Writes messages as plain text on stdout, whether or not a terminal is there. +pub(crate) fn write_plain(messages: &[Message]) -> anyhow::Result<()> { + write_text(&plain_text(messages)) +} + +/// Writes one result as a single YAML document on stdout. +pub(crate) fn write_yaml(document: &T) -> anyhow::Result<()> { + let text = + dotcore_proto::yaml::to_string(document).context("cannot render the result as YAML")?; + write_text(&text) +} + +/// Writes already laid out text on stdout. A closed stdout, such as a pipe into `head`, means the +/// reader is done and is not a failure. +pub(crate) fn write_text(text: &str) -> anyhow::Result<()> { + write_tolerating_closed_reader(&mut io::stdout().lock(), text) + .context("cannot write the result to standard output") +} + +/// Writes `text` to `writer` and flushes it, treating a reader that went away as success. +fn write_tolerating_closed_reader(writer: &mut dyn Write, text: &str) -> io::Result<()> { + match writer + .write_all(text.as_bytes()) + .and_then(|()| writer.flush()) + { + Err(error) if error.kind() == io::ErrorKind::BrokenPipe => Ok(()), + written => written, + } +} + +/// A stream of YAML documents on stdout, one per entry, separated by `---` lines. +#[derive(Debug, Default)] +pub(crate) struct YamlDocuments { + started: bool, +} + +impl YamlDocuments { + /// Writes one more document, after a separator when it is not the first. + pub(crate) fn write( + &mut self, + writer: &mut dyn Write, + document: &T, + ) -> io::Result<()> { + let text = dotcore_proto::yaml::to_string(document).map_err(io::Error::other)?; + if self.started { + writer.write_all(b"---\n")?; + } + writer.write_all(text.as_bytes())?; + writer.flush()?; + self.started = true; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_closed_reader_is_not_a_write_failure_but_other_errors_are() { + struct FailingWriter(io::ErrorKind); + + impl Write for FailingWriter { + fn write(&mut self, _: &[u8]) -> io::Result { + Err(self.0.into()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + write_tolerating_closed_reader(&mut FailingWriter(io::ErrorKind::BrokenPipe), "text\n") + .expect("closed reader"); + let error = write_tolerating_closed_reader( + &mut FailingWriter(io::ErrorKind::PermissionDenied), + "text\n", + ) + .expect_err("other failure"); + assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); + + let mut written = Vec::new(); + write_tolerating_closed_reader(&mut written, "text\n").expect("open reader"); + assert_eq!(written, b"text\n"); + } + + #[test] + fn documents_after_the_first_start_with_a_separator() { + let mut documents = YamlDocuments::default(); + let mut written = Vec::new(); + + documents + .write(&mut written, &serde_json::json!({"line": "one"})) + .expect("first document"); + documents + .write(&mut written, &serde_json::json!({"line": "two"})) + .expect("second document"); + + assert_eq!( + String::from_utf8(written).expect("UTF-8"), + "line: one\n---\nline: two\n" + ); + } +} diff --git a/backend/cli/src/parameters.rs b/backend/cli/src/parameters.rs index 7167f53f..655d13ec 100644 --- a/backend/cli/src/parameters.rs +++ b/backend/cli/src/parameters.rs @@ -9,15 +9,13 @@ use dotcore_proto::dotcore::catalog::v1::{ }; use crate::management::single_line; -use crate::terminal::{Message, Terminal}; +use crate::terminal::Message; -const SECRET_MASK: &str = "********"; +pub(crate) const SECRET_MASK: &str = "********"; const EMPTY_TEXT: &str = "Empty"; /// One shown parameter. pub(crate) struct ParameterRow { - /// Stable parameter identity. - pub(crate) id: String, /// Human-readable parameter label. pub(crate) name: String, /// The value as shown. @@ -49,7 +47,6 @@ impl ParameterInput<'_> { } }; Some(ParameterRow { - id: definition.parameter_id.clone(), name: single_line(&definition.display_name), value: text, }) @@ -57,9 +54,8 @@ impl ParameterInput<'_> { } /// The row of a secret that has no parameter definition, masked unless revealed. -pub(crate) fn secret_row(id: &str, name: &str, secret: &str, reveal_secrets: bool) -> ParameterRow { +pub(crate) fn secret_row(name: &str, secret: &str, reveal_secrets: bool) -> ParameterRow { ParameterRow { - id: id.to_owned(), name: name.to_owned(), value: if reveal_secrets { single_line(secret) @@ -69,6 +65,31 @@ pub(crate) fn secret_row(id: &str, name: &str, secret: &str, reveal_secrets: boo } } +/// Replaces the values of the secret parameters among `definitions` with the mask, leaving every +/// other value as it is. +pub(crate) fn mask_secret_values( + definitions: &[ParameterDefinition], + values: &mut [ParameterValue], +) { + for value in values { + let secret = definitions.iter().any(|definition| { + definition.parameter_id == value.parameter_id && is_secret(definition) + }); + if secret && value.value.is_some() { + value.value = Some(parameter_value::Value::String(SECRET_MASK.to_owned())); + } + } +} + +/// Returns the mask shown in place of a secret value. +pub(crate) fn masked(secret: &str) -> String { + if secret.is_empty() { + String::new() + } else { + SECRET_MASK.to_owned() + } +} + /// The retained value of a parameter, if it has one. pub(crate) fn retained<'a>( values: &'a [ParameterValue], @@ -80,43 +101,20 @@ pub(crate) fn retained<'a>( .and_then(|value| value.value.as_ref()) } -/// The record key suffix of a parameter: its id upper-cased, with every non-alphanumeric -/// character replaced by an underscore. -pub(crate) fn record_key(id: &str) -> String { - id.chars() - .map(|character| { - if character.is_ascii_alphanumeric() { - character.to_ascii_uppercase() - } else { - '_' - } - }) - .collect() -} - -/// One record line per row under the given key prefix. -pub(crate) fn record_lines(prefix: &str, rows: &[ParameterRow]) -> String { - rows.iter() - .map(|row| format!("{prefix}_{}={}\n", record_key(&row.id), row.value)) - .collect() -} - -/// Writes the parameter rows under a Parameters heading on the terminal, or nothing when there are -/// none. -pub(crate) fn write_parameters( - terminal: &mut dyn Terminal, - rows: &[ParameterRow], -) -> anyhow::Result<()> { +/// The messages that show the parameter rows under a Parameters heading, or none when there are +/// no rows. +pub(crate) fn parameter_messages(rows: &[ParameterRow]) -> Vec { if rows.is_empty() { - return Ok(()); + return Vec::new(); } - terminal.message(&Message::Heading("Parameters".to_owned()))?; - terminal.message(&Message::KeyValues( - rows.iter() - .map(|row| (row.name.clone(), row.value.clone())) - .collect(), - ))?; - Ok(()) + vec![ + Message::Heading("Parameters".to_owned()), + Message::KeyValues( + rows.iter() + .map(|row| (row.name.clone(), row.value.clone())) + .collect(), + ), + ] } fn display(value: ¶meter_value::Value, definition: &ParameterDefinition) -> String { diff --git a/backend/cli/src/runtime_confirmation.rs b/backend/cli/src/runtime_confirmation.rs index c0321828..5e5fe51e 100644 --- a/backend/cli/src/runtime_confirmation.rs +++ b/backend/cli/src/runtime_confirmation.rs @@ -83,11 +83,11 @@ pub(crate) fn approve_runtime_removal( ); } - terminal.message(&Message::Heading(format!( + terminal.prompt_context(&Message::Heading(format!( "{} owns these resources", approval.subject )))?; - terminal.message(&Message::KeyValues( + terminal.prompt_context(&Message::KeyValues( inventory .resources .iter() diff --git a/backend/cli/src/site/delete.rs b/backend/cli/src/site/delete.rs index 01fedee2..27328055 100644 --- a/backend/cli/src/site/delete.rs +++ b/backend/cli/src/site/delete.rs @@ -5,9 +5,8 @@ //! backend holds, and it touches only resources whose ownership evidence names the site, or, for //! native workloads, places them in the site directory. -use std::{io::Write, path::Path, sync::Arc}; +use std::{path::Path, sync::Arc}; -use anyhow::Context; use clap::Args; use dotcore_runtime::SiteRuntimeCleanup; use dotcore_site::reset::{ @@ -17,13 +16,15 @@ use dotcore_site::reset::{ }, }; +use super::output::{SiteDocument, write_directory_outcome}; use crate::{ RootPathArgs, + output::{LazyTerminal, OutputFormat, write_yaml}, runtime_confirmation::{ RuntimeRemovalApproval, RuntimeRemovalArgs, approve_runtime_removal, native_cleanup_failure, site_runtime_cleanup, site_runtime_cleanups, }, - terminal::{Terminal, open_terminal}, + terminal::Terminal, }; /// Arguments of `dotc site delete`. @@ -38,18 +39,26 @@ pub struct SiteDeleteArgs { } /// Deletes the site using the process terminal and the runtimes its configuration binds. -pub(crate) async fn delete(arguments: SiteDeleteArgs, paths: &RootPathArgs) -> anyhow::Result<()> { +pub(crate) async fn delete( + arguments: SiteDeleteArgs, + paths: &RootPathArgs, + format: OutputFormat, +) -> anyhow::Result<()> { let site_dir = paths.site_dir()?; let cache_root = paths.configured_cache_root()?; - let mut terminal = open_terminal(); + let mut terminal = LazyTerminal::new(); delete_with( arguments, &site_dir, cache_root.as_deref(), - terminal.as_mut(), + &mut terminal, site_runtime_cleanup, ) - .await + .await?; + if format == OutputFormat::Yaml { + return write_yaml(&SiteDocument::at("deleted", &site_dir)?); + } + write_directory_outcome("Site deleted", &site_dir) } async fn delete_with( @@ -92,13 +101,8 @@ async fn delete_with( transaction .delete(session) .await - .map_err(|error| delete_failure(error, site_dir))?; - writeln!( - std::io::stdout().lock(), - "Site deleted\nDOTCORE_SITE_DIR={}", - site_dir.display() - ) - .context("write site delete result") + .map(drop) + .map_err(|error| delete_failure(error, site_dir)) } fn delete_failure(error: SiteResetTransactionError, site_dir: &Path) -> anyhow::Error { diff --git a/backend/cli/src/site/init.rs b/backend/cli/src/site/init.rs index bc2783c4..eef4fd70 100644 --- a/backend/cli/src/site/init.rs +++ b/backend/cli/src/site/init.rs @@ -13,12 +13,13 @@ use dotcore_site::initial::input_store::{ use super::{ HostAwareIdentityGenerator, SiteInitArgs, SiteLocation, SiteResetArgs, collection::{CollectionAdapters, CollectionMode, collect_initial_site}, - output::write_transaction_success, + output::{SiteDocument, SiteReport}, recorded_host, reset, system_initial_site_prober, system_listener_host, validator, }; use crate::{ RootPathArgs, hosts::{ListenerHost, SystemHostEnvironment}, + output::{OutputFormat, write_yaml}, terminal::open_terminal, }; @@ -26,6 +27,7 @@ use crate::{ pub(super) async fn initialize( arguments: SiteInitArgs, paths: &RootPathArgs, + format: OutputFormat, ) -> anyhow::Result<()> { if arguments.replace && arguments.force { return reset::reset( @@ -34,6 +36,7 @@ pub(super) async fn initialize( removal: arguments.removal, }, paths, + format, ) .await; } @@ -46,7 +49,12 @@ pub(super) async fn initialize( .map_err(|error| initialization_transaction_failure(error, site_dir))? { InitialSitePresence::Missing => {} - InitialSitePresence::Initialized => return Ok(()), + InitialSitePresence::Initialized => { + if format == OutputFormat::Yaml { + write_yaml(&SiteDocument::at("alreadyInitialized", site_dir)?)?; + } + return Ok(()); + } } } let listener = system_listener_host(&arguments.configuration).await?; @@ -67,17 +75,19 @@ pub(super) async fn initialize( identities: &mut identities, }, ) - .await + .await? + .print(format) } -/// Collects the site in `mode`, then writes it unless an existing site already matches. +/// Collects the site in `mode`, then writes it unless an existing site already matches, and +/// returns what to report. async fn initialize_site( arguments: SiteInitArgs, location: &SiteLocation, listener: Option<&ListenerHost>, mode: CollectionMode<'_>, adapters: CollectionAdapters<'_>, -) -> anyhow::Result<()> { +) -> anyhow::Result { let site_dir = location.site_dir.as_path(); let recorded = if arguments.replace { None @@ -93,7 +103,7 @@ async fn initialize_site( adapters, ) .await?; - let prepared = &collected.prepared; + let prepared = collected.prepared; let writer = InitialSiteInputWriter::new(validator(location.catalog_dir.as_deref())); let outcome = writer .initialize( @@ -103,13 +113,13 @@ async fn initialize_site( arguments.replace, ) .map_err(|error| initialization_transaction_failure(error, site_dir))?; - write_transaction_success( + Ok(SiteReport::written( outcome, site_dir, - &prepared.inputs, - &prepared.request, - collected.unreported_host.as_ref(), - ) + prepared.inputs, + prepared.request, + collected.unreported_host, + )) } fn initialization_transaction_failure( @@ -158,10 +168,11 @@ mod tests { use super::initialize_site; use crate::{ hosts::test_support::{FakeHostEnvironment, TAILNET_NAME, listener_host}, + output::plain_text, site::{ ApplicationsChoice, InferenceChoice, NativeWorkloadLifetimeChoice, collection::{CollectionAdapters, CollectionMode}, - output::success_records, + output::site_messages, prepare_initial_site, test_support::{ FakeApple, FakeDocker, SiteRoot, UnavailableNvidia, adapters, flagged_request, @@ -380,15 +391,17 @@ mod tests { InitialSiteInputs::load(&site_dir, &dotcore::model::site_declaration_rules()) .expect("existing site inputs"); assert_eq!( - success_records( - "Site already initialized", - &site_dir, - &existing, - &flagged_request(&matching_arguments.configuration), - ) - .expect("success records"), + plain_text( + &site_messages( + "Site already initialized", + &site_dir, + &existing, + &flagged_request(&matching_arguments.configuration), + ) + .expect("site messages") + ), format!( - "Site already initialized\nDOTCORE_SITE_DIR={}\nDOTCORE_SITE_ID=site-test\nDOTCORE_NODE_ID=node-test\nDOTCORE_NODE_HOST=192.0.2.10\nDOTCORE_INFERENCE=simulated\nDOTCORE_APPLICATIONS=docker\n", + "✔ Site already initialized\n directory {}\n site id site-test\n node id node-test\n node host 192.0.2.10\n inference simulated\n applications docker\n", site_dir.display() ) ); diff --git a/backend/cli/src/site/mod.rs b/backend/cli/src/site/mod.rs index 1211c31b..2a21490e 100644 --- a/backend/cli/src/site/mod.rs +++ b/backend/cli/src/site/mod.rs @@ -41,6 +41,7 @@ use dotcore_site::{ use crate::{ RootPathArgs, hosts::{HostEnvironment, ListenerHost, SystemHostEnvironment, host_warning}, + output::OutputFormat, runtime_confirmation::RuntimeRemovalArgs, terminal::{TerminalCondition, controlling_terminal_condition}, }; @@ -58,18 +59,19 @@ pub struct SiteCommand { /// Actions supported by the site command group. #[derive(Debug, Subcommand)] enum SiteSubcommand { - /// Author an initial site with a site signing key and local node identity. + /// Create a site with its signing key and this machine's node identity Init(SiteInitArgs), - /// Start a fresh site, the same as `site init --replace --force`: remove its runtime - /// resources after confirmation, its workload caches, state and trust, then write new inputs. - /// Previously joined nodes become invalid. + /// Start a fresh site, replacing the current one after confirmation + /// + /// The same as `site init --replace --force`: removes the runtime resources, workload caches, + /// state and trust, then writes new inputs. Previously joined nodes become invalid. Reset(SiteResetArgs), - /// Delete a stopped site: remove its runtime resources and workload caches, then its directory. + /// Delete a stopped site, its runtime resources and its caches Delete(delete::SiteDeleteArgs), - /// Validate an existing site input bundle without starting services. + /// Validate the site's input bundle without starting services Validate, } @@ -120,7 +122,7 @@ pub struct InitialSiteConfigurationArgs { pub node_id: Option, /// SiteNode display name; defaults to this machine's hostname without a trailing `.local`. - #[arg(long, value_name = "NAME", value_parser = parse_display_name)] + #[arg(long = "name", value_name = "NAME", value_parser = parse_display_name)] pub display_name: Option, /// SiteNode host other nodes reach this node at, an IPv4 address or DNS host name; always @@ -395,17 +397,35 @@ pub(crate) struct PreparedInitialSite { } impl SiteCommand { - pub(crate) async fn dispatch(self, paths: &RootPathArgs) -> anyhow::Result<()> { + /// Runs the chosen action. YAML output never asks, so it counts as having no terminal to ask + /// on. + pub(crate) async fn dispatch( + self, + paths: &RootPathArgs, + format: OutputFormat, + ) -> anyhow::Result<()> { + let unattended = format == OutputFormat::Yaml; match self.command { - Some(SiteSubcommand::Init(arguments)) => init::initialize(arguments, paths).await, - Some(SiteSubcommand::Reset(arguments)) => reset::reset(arguments, paths).await, - Some(SiteSubcommand::Delete(arguments)) => delete::delete(arguments, paths).await, - Some(SiteSubcommand::Validate) => validate(paths).context("site validate failed"), + Some(SiteSubcommand::Init(mut arguments)) => { + arguments.configuration.non_interactive |= unattended; + init::initialize(arguments, paths, format).await + } + Some(SiteSubcommand::Reset(mut arguments)) => { + arguments.configuration.non_interactive |= unattended; + reset::reset(arguments, paths, format).await + } + Some(SiteSubcommand::Delete(mut arguments)) => { + arguments.non_interactive |= unattended; + delete::delete(arguments, paths, format).await + } + Some(SiteSubcommand::Validate) => { + validate(paths, format).context("site validate failed") + } None => bail!("site command requires an action"), } } - pub(crate) fn argument_contract_error(&self) -> Option<&'static str> { + pub(crate) fn argument_contract_error(&self, yaml: bool) -> Option<&'static str> { match &self.command { Some(SiteSubcommand::Init(arguments)) => { if arguments.force && !arguments.replace { @@ -416,10 +436,10 @@ impl SiteCommand { { return Some("--yes and --skip-runtime-cleanup require --replace --force"); } - initial_configuration_argument_error(&arguments.configuration) + initial_configuration_argument_error(&arguments.configuration, yaml) } Some(SiteSubcommand::Reset(arguments)) => { - initial_configuration_argument_error(&arguments.configuration) + initial_configuration_argument_error(&arguments.configuration, yaml) } Some(SiteSubcommand::Delete(_) | SiteSubcommand::Validate) | None => None, } @@ -428,7 +448,11 @@ impl SiteCommand { fn initial_configuration_argument_error( arguments: &InitialSiteConfigurationArgs, + yaml: bool, ) -> Option<&'static str> { + if yaml && arguments.interactive { + return Some("--interactive cannot be combined with --yaml, which never asks"); + } if !arguments.nvidia_device.is_empty() && !arguments.inference.is_empty() && !InferenceArgument::offers(&arguments.inference, InferenceChoice::Nvidia) @@ -458,6 +482,11 @@ fn initial_configuration_argument_error( return Some("--applications none cannot be combined with another --applications value"); } let missing_choices = arguments.inference.is_empty() || arguments.applications.is_empty(); + if missing_choices && yaml { + return Some( + "missing workload choices; --yaml never asks, so pass --inference and --applications", + ); + } if missing_choices && (arguments.non_interactive || (!arguments.interactive && !controlling_terminal_available())) @@ -554,13 +583,13 @@ impl InitialSiteIdentityGenerator for HostAwareIdentityGenerator { } } -fn validate(paths: &RootPathArgs) -> anyhow::Result<()> { +fn validate(paths: &RootPathArgs, format: OutputFormat) -> anyhow::Result<()> { let location = SiteLocation::resolve(paths)?; let site_dir = location.site_dir.as_path(); validator(location.catalog_dir.as_deref()) .validate_without_runtime_declarations(site_dir) .map_err(|error| validation_failure(error, site_dir))?; - write_validate_success(site_dir) + write_validate_success(site_dir, format) } fn validator(catalog_dir: Option<&Path>) -> SiteInputBundleValidator { @@ -955,7 +984,7 @@ mod tests { "shared-site", "--node-id", "shared-node", - "--display-name", + "--name", "Shared node", "--host", "192.0.2.10", @@ -1020,7 +1049,7 @@ mod tests { "simulated", "--applications", "simulated", - "--display-name", + "--name", value, ]) .expect_err("invalid display name"); @@ -1070,7 +1099,7 @@ mod tests { "applications", "--site-id", "--node-id", - "--display-name", + "--name", "127.0.0.1", "--nvidia-device", "--replace", diff --git a/backend/cli/src/site/output.rs b/backend/cli/src/site/output.rs index c1e63198..d8c7612c 100644 --- a/backend/cli/src/site/output.rs +++ b/backend/cli/src/site/output.rs @@ -1,62 +1,200 @@ -//! The stable result records init, reset and validation print on standard output. +//! What init, reset, delete and validation report on standard output. //! -//! Records are key-value lines after a one-line outcome, so scripts can read them; values with line -//! breaks are refused instead of printed. When no guided summary showed the node host and the -//! operator did not name it, standard error names it and where it came from. +//! A person gets a one-line outcome followed by the site's facts as plain text on stdout, even +//! after a guided conversation on the terminal. Asked for YAML, the same facts are one document. +//! When no guided summary showed the node host and the operator did not name it, standard error +//! names it and where it came from. -use std::path::Path; +use std::{fmt, path::Path}; -use anyhow::{Context, bail}; +use anyhow::Context; use dotcore_proto::dotcore::site::v1::SiteNode; use dotcore_site::initial::{ input_store::InitialSiteWriteOutcome, inputs::InitialSiteInputs, request::{InitialApplicationRuntime, InitialInferenceRuntime, InitialSiteRequest}, }; +use serde::Serialize; use crate::{ hosts::{HostSource, SelectedHost}, + output::{OutputFormat, write_plain, write_yaml}, terminal::{Message, notify_stderr}, }; -pub(super) fn write_success( - first_line: &str, - site_dir: &Path, - inputs: &InitialSiteInputs, - request: &InitialSiteRequest, -) -> anyhow::Result<()> { - let records = success_records(first_line, site_dir, inputs, request)?; - write_stdout(records.as_bytes(), "write site initialization result") +/// How a site command left the site. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum SiteOutcome { + Initialized, + + AlreadyInitialized, + + Reset, } -/// Writes the outcome's records, then reports `unreported_host` when given and not named by the -/// operator: the selected host for a written site, the recorded one for a site that already -/// matched. -pub(super) fn write_transaction_success( - outcome: InitialSiteWriteOutcome, - site_dir: &Path, - published: &InitialSiteInputs, - request: &InitialSiteRequest, - unreported_host: Option<&SelectedHost>, -) -> anyhow::Result<()> { - match outcome { - InitialSiteWriteOutcome::Published => { - write_success("Site initialized", site_dir, published, request)?; - if let Some(host) = unreported_host { - report_host(host); +impl SiteOutcome { + /// The outcome line a person reads. + fn line(self) -> &'static str { + match self { + Self::Initialized => "Site initialized", + Self::AlreadyInitialized => "Site already initialized", + Self::Reset => "Site reset", + } + } + + /// The outcome word of the YAML document. + fn key(self) -> &'static str { + match self { + Self::Initialized => "initialized", + Self::AlreadyInitialized => "alreadyInitialized", + Self::Reset => "reset", + } + } +} + +/// A site that init or reset wrote or found, ready to report once the command is done. +pub(super) struct SiteReport { + outcome: SiteOutcome, + site_dir: std::path::PathBuf, + inputs: InitialSiteInputs, + request: InitialSiteRequest, + + /// The selected host when nothing showed it yet, so the report names it. + unreported_host: Option, +} + +impl fmt::Debug for SiteReport { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("SiteReport") + .field("outcome", &self.outcome) + .field("site_dir", &self.site_dir) + .finish_non_exhaustive() + } +} + +impl SiteReport { + /// Reports the outcome of a write: the site it published, or the matching site it kept. + pub(super) fn written( + outcome: InitialSiteWriteOutcome, + site_dir: &Path, + published: InitialSiteInputs, + request: InitialSiteRequest, + unreported_host: Option, + ) -> Self { + let (outcome, inputs) = match outcome { + InitialSiteWriteOutcome::Published => (SiteOutcome::Initialized, published), + InitialSiteWriteOutcome::AlreadyInitialized(existing) => { + (SiteOutcome::AlreadyInitialized, existing) } + }; + Self { + outcome, + site_dir: site_dir.to_owned(), + inputs, + request, + unreported_host, + } + } + + /// Reports a site that a reset replaced. + pub(super) fn reset( + site_dir: &Path, + inputs: InitialSiteInputs, + request: InitialSiteRequest, + unreported_host: Option, + ) -> Self { + Self { + outcome: SiteOutcome::Reset, + site_dir: site_dir.to_owned(), + inputs, + request, + unreported_host, } - InitialSiteWriteOutcome::AlreadyInitialized(existing) => { - write_success("Site already initialized", site_dir, &existing, request)?; - if unreported_host.is_some_and(|host| host.source() != &HostSource::Flag) { + } + + /// Prints the result on stdout, then names the node host on stderr when nothing showed it. + pub(super) fn print(&self, format: OutputFormat) -> anyhow::Result<()> { + match format { + OutputFormat::Yaml => write_yaml(&SiteDocument::of(self)?)?, + OutputFormat::Human => write_plain(&site_messages( + self.outcome.line(), + &self.site_dir, + &self.inputs, + &self.request, + )?)?, + } + match (self.outcome, &self.unreported_host) { + (SiteOutcome::Initialized | SiteOutcome::Reset, Some(host)) => report_host(host), + (SiteOutcome::AlreadyInitialized, Some(host)) if host.source() != &HostSource::Flag => { notify_node_host(&format!( "Node host: {} (already recorded)", - local_node(&existing)?.host + local_node(&self.inputs)?.host )); } + _ => {} } + Ok(()) + } +} + +/// The YAML document of a site command: where the site is and, once initialized or reset, what it +/// is. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct SiteDocument { + outcome: &'static str, + site_dir: String, + + #[serde(flatten)] + details: Option, +} + +/// The identity and capabilities of a written site. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct SiteDetails { + site_id: String, + node_id: String, + node_host: String, + inference: Vec<&'static str>, + applications: Vec<&'static str>, +} + +impl SiteDocument { + fn of(report: &SiteReport) -> anyhow::Result { + let node = local_node(&report.inputs)?; + Ok(Self { + outcome: report.outcome.key(), + site_dir: path_text(&report.site_dir)?.to_owned(), + details: Some(SiteDetails { + site_id: report.inputs.site().site_id.clone(), + node_id: node.node_id.clone(), + node_host: node.host.clone(), + inference: report + .request + .inference() + .iter() + .map(|inference| inference_name(*inference)) + .collect(), + applications: report + .request + .applications() + .iter() + .map(|applications| applications_name(*applications)) + .collect(), + }), + }) + } + + /// The document of a command that only says what it did to the site folder. + pub(super) fn at(outcome: &'static str, site_dir: &Path) -> anyhow::Result { + Ok(Self { + outcome, + site_dir: path_text(site_dir)?.to_owned(), + details: None, + }) } - Ok(()) } /// Names the selected node host and where it came from on stderr, unless the operator named it. @@ -66,78 +204,46 @@ pub(super) fn report_host(host: &SelectedHost) { } } -pub(super) fn write_validate_success(site_dir: &Path) -> anyhow::Result<()> { - let site_dir = site_dir - .to_str() - .filter(|value| !value.contains(['\r', '\n'])) - .context( - "Site validation output path must be UTF-8 without carriage returns or newlines", - )?; - let records = format!("Site valid\nDOTCORE_SITE_DIR={site_dir}\n"); - write_stdout(records.as_bytes(), "write site validation result") -} - -/// Writes a command result record to process stdout. -/// -/// Unit tests print through libtest's capture instead, since direct stdout writes bypass it. -fn write_stdout(bytes: &[u8], context: &'static str) -> anyhow::Result<()> { - #[cfg(test)] - { - let _ = context; - print!("{}", String::from_utf8_lossy(bytes)); - Ok(()) +pub(super) fn write_validate_success(site_dir: &Path, format: OutputFormat) -> anyhow::Result<()> { + if format == OutputFormat::Yaml { + return write_yaml(&SiteDocument::at("valid", site_dir)?); } + write_directory_outcome("Site valid", site_dir) +} - #[cfg(not(test))] - { - use std::io::Write as _; - - std::io::stdout().lock().write_all(bytes).context(context) - } +/// Reports a site command that only says what it did to the site folder, such as a deletion. +pub(super) fn write_directory_outcome(outcome_line: &str, site_dir: &Path) -> anyhow::Result<()> { + write_plain(&[ + Message::Success(outcome_line.to_owned()), + Message::KeyValues(vec![( + "directory".to_owned(), + path_text(site_dir)?.to_owned(), + )]), + ]) } -pub(super) fn success_records( - first_line: &str, +/// The outcome line of a site command and the facts of the site it left. +pub(super) fn site_messages( + outcome_line: &str, site_dir: &Path, inputs: &InitialSiteInputs, request: &InitialSiteRequest, -) -> anyhow::Result { - let site_dir = site_dir - .to_str() - .filter(|value| !value.contains(['\r', '\n'])) - .context("Site output path must be UTF-8 without carriage returns or newlines")?; - let inference = capability_list(request.inference().iter().map(|inference| match inference { - InitialInferenceRuntime::Simulated => "simulated", - InitialInferenceRuntime::Nvidia => "nvidia", - InitialInferenceRuntime::Apple => "apple", - })); +) -> anyhow::Result> { + let inference = capability_list(request.inference().iter().map(|&i| inference_name(i))); let applications = - capability_list( - request - .applications() - .iter() - .map(|applications| match applications { - InitialApplicationRuntime::Simulated => "simulated", - InitialApplicationRuntime::Docker => "docker", - }), - ); + capability_list(request.applications().iter().map(|&a| applications_name(a))); let node = local_node(inputs)?; - for value in [ - first_line, - inputs.site().site_id.as_str(), - node.node_id.as_str(), - node.host.as_str(), - ] { - if value.contains(['\r', '\n']) { - bail!("Site initialization output value must not contain carriage returns or newlines"); - } - } - Ok(format!( - "{first_line}\nDOTCORE_SITE_DIR={site_dir}\nDOTCORE_SITE_ID={}\nDOTCORE_NODE_ID={}\nDOTCORE_NODE_HOST={}\nDOTCORE_INFERENCE={inference}\nDOTCORE_APPLICATIONS={applications}\n", - inputs.site().site_id, - node.node_id, - node.host, - )) + Ok(vec![ + Message::Success(outcome_line.to_owned()), + Message::KeyValues(vec![ + ("directory".to_owned(), path_text(site_dir)?.to_owned()), + ("site id".to_owned(), inputs.site().site_id.clone()), + ("node id".to_owned(), node.node_id.clone()), + ("node host".to_owned(), node.host.clone()), + ("inference".to_owned(), inference), + ("applications".to_owned(), applications), + ]), + ]) } /// Returns the declaration of the node these inputs are bound to. @@ -154,6 +260,28 @@ fn notify_node_host(host_line: &str) { notify_stderr(&[Message::Info(host_line.to_owned())], host_line); } +fn inference_name(inference: InitialInferenceRuntime) -> &'static str { + match inference { + InitialInferenceRuntime::Simulated => "simulated", + InitialInferenceRuntime::Nvidia => "nvidia", + InitialInferenceRuntime::Apple => "apple", + } +} + +fn applications_name(applications: InitialApplicationRuntime) -> &'static str { + match applications { + InitialApplicationRuntime::Simulated => "simulated", + InitialApplicationRuntime::Docker => "docker", + } +} + +/// The path as text, which a result can print only when it is UTF-8 without line breaks. +fn path_text(path: &Path) -> anyhow::Result<&str> { + path.to_str() + .filter(|value| !value.contains(['\r', '\n'])) + .context("Site output path must be UTF-8 without carriage returns or newlines") +} + /// Joins capability names with commas, such as `simulated,nvidia`, or `none` without any. fn capability_list<'a>(capabilities: impl Iterator) -> String { let capabilities = capabilities.collect::>(); @@ -168,7 +296,8 @@ fn capability_list<'a>(capabilities: impl Iterator) -> String { mod tests { use dotcore_site::initial::probe::InitialSiteProber; - use super::success_records; + use super::site_messages; + use crate::output::plain_text; use crate::site::{ ApplicationsChoice, InferenceChoice, prepare_initial_site, test_support::{ @@ -178,7 +307,7 @@ mod tests { }; #[test] - fn apple_inference_is_reported_in_the_success_records() { + fn apple_inference_is_reported_in_the_site_messages() { let fixture = SiteRoot::new(); let site_dir = fixture.root.join("site"); let mut arguments = init_arguments(ApplicationsChoice::Simulated); @@ -197,31 +326,34 @@ mod tests { )) .expect("prepare Apple site"); - assert!( - success_records( + let text = plain_text( + &site_messages( "Site initialized", &site_dir, &prepared.inputs, - &prepared.request + &prepared.request, ) - .expect("records") - .contains("DOTCORE_INFERENCE=apple\nDOTCORE_APPLICATIONS=simulated\n") + .expect("messages"), + ); + assert!( + text.ends_with(" inference apple\n applications simulated\n"), + "{text}" ); } #[test] - fn every_capability_or_none_is_reported_in_the_success_records() { + fn every_capability_or_none_is_reported_in_the_site_messages() { let site_dir = SiteRoot::new().root.join("site"); for (inference, applications, expected) in [ ( vec![InferenceChoice::Simulated], vec![ApplicationsChoice::Docker, ApplicationsChoice::Simulated], - "DOTCORE_INFERENCE=simulated\nDOTCORE_APPLICATIONS=simulated,docker\n", + " inference simulated\n applications simulated,docker\n", ), ( vec![InferenceChoice::None], vec![ApplicationsChoice::None], - "DOTCORE_INFERENCE=none\nDOTCORE_APPLICATIONS=none\n", + " inference none\n applications none\n", ), ] { let mut arguments = init_arguments(ApplicationsChoice::Simulated); @@ -240,14 +372,16 @@ mod tests { )) .expect("prepare site"); - let records = success_records( - "Site initialized", - &site_dir, - &prepared.inputs, - &prepared.request, - ) - .expect("records"); - assert!(records.ends_with(expected), "{records}"); + let text = plain_text( + &site_messages( + "Site initialized", + &site_dir, + &prepared.inputs, + &prepared.request, + ) + .expect("messages"), + ); + assert!(text.ends_with(expected), "{text}"); } } } diff --git a/backend/cli/src/site/reset.rs b/backend/cli/src/site/reset.rs index c2dbb002..b56f4424 100644 --- a/backend/cli/src/site/reset.rs +++ b/backend/cli/src/site/reset.rs @@ -24,32 +24,37 @@ use dotcore_site::{ use super::{ HostAwareIdentityGenerator, SiteLocation, SiteResetArgs, collection::{CollectionAdapters, CollectionMode, collect_initial_site}, - output::{report_host, write_success}, + output::SiteReport, system_initial_site_prober, system_listener_host, validator, }; use crate::{ RootPathArgs, hosts::{ListenerHost, SystemHostEnvironment}, + output::{LazyTerminal, OutputFormat}, runtime_confirmation::{ RuntimeRemovalApproval, approve_runtime_removal, site_runtime_cleanup, site_runtime_cleanups, }, - terminal::{Message, NextStep, Terminal, notify_stderr, open_terminal}, + terminal::{Message, Terminal, notify_stderr}, }; /// Resets the site the root path options name to a fresh one. -pub(super) async fn reset(arguments: SiteResetArgs, paths: &RootPathArgs) -> anyhow::Result<()> { +pub(super) async fn reset( + arguments: SiteResetArgs, + paths: &RootPathArgs, + format: OutputFormat, +) -> anyhow::Result<()> { let location = SiteLocation::resolve(paths)?; let cache_root = paths.configured_cache_root()?; let listener = system_listener_host(&arguments.configuration).await?; let prober = system_initial_site_prober(); - let mut terminal = open_terminal(); + let mut terminal = LazyTerminal::new(); reset_site( arguments, &location, cache_root.as_deref(), listener.as_ref(), - terminal.as_mut(), + &mut terminal, CollectionAdapters { prober: &prober, environment: &SystemHostEnvironment, @@ -57,11 +62,12 @@ pub(super) async fn reset(arguments: SiteResetArgs, paths: &RootPathArgs) -> any }, site_runtime_cleanup, ) - .await + .await? + .print(format) } /// Locks the site and gets approval to remove its runtime resources, removes the site, then -/// collects its new inputs and publishes them. +/// collects its new inputs and publishes them, returning what to report. async fn reset_site( arguments: SiteResetArgs, location: &SiteLocation, @@ -70,7 +76,7 @@ async fn reset_site( terminal: &mut dyn Terminal, adapters: CollectionAdapters<'_>, select_runtime: impl FnOnce(&SiteResetSession) -> anyhow::Result>, -) -> anyhow::Result<()> { +) -> anyhow::Result { let site_dir = location.site_dir.as_path(); let skip_runtime_cleanup = arguments.removal.skip_runtime_cleanup; let cleanups = site_runtime_cleanups(cache_root); @@ -113,15 +119,12 @@ async fn reset_site( transaction .publish_removed(removed, &collected.prepared.inputs) .map_err(|error| reset_transaction_failure(error, site_dir))?; - if let Some(host) = &collected.unreported_host { - report_host(host); - } - write_success( - "Site reset", + Ok(SiteReport::reset( site_dir, - &collected.prepared.inputs, - &collected.prepared.request, - ) + collected.prepared.inputs, + collected.prepared.request, + collected.unreported_host, + )) } /// Lists the site's runtime resources and obtains the operator's approval to remove them. Nothing @@ -169,18 +172,11 @@ async fn remove_site( .map_err(|error| reset_transaction_failure(error, &site_dir))?; if provisioned_workers > 0 { notify_stderr( - &[ - Message::Warning(format!( - "Site trust was rotated: {provisioned_workers} joined node(s) can no longer connect" - )), - Message::Next(vec![ - NextStep::new("Join each node again, with this on the manager:") - .with_command("dotc node add"), - NextStep::new("and this on the node:").with_command("dotc node join"), - ]), - ], + &[Message::Warning(format!( + "Site trust was rotated: {provisioned_workers} joined node(s) can no longer connect and must join again" + ))], &format!( - "Notice: site trust was rotated; {provisioned_workers} previously joined node(s) can no longer connect; join each node again with dotc node add and dotc node join" + "Notice: site trust was rotated; {provisioned_workers} previously joined node(s) can no longer connect and must join again" ), ); } @@ -748,6 +744,7 @@ mod tests { adapters(prober, &mut named_identities(None)), move |_| Ok(Box::new(runtime)), )) + .map(drop) } /// Every file under the site root with its bytes, in path order. diff --git a/backend/cli/src/telemetry.rs b/backend/cli/src/telemetry.rs index 6f2d2e1b..fb6ba3c5 100644 --- a/backend/cli/src/telemetry.rs +++ b/backend/cli/src/telemetry.rs @@ -30,10 +30,10 @@ pub(crate) struct TelemetryCommand { #[derive(Debug, Subcommand)] enum TelemetryAction { - /// Fit a model binding's sizing constants on one hardware class from recorded workload resources. + /// Fit a model binding's sizing constants from recorded workload resources Fit(FitArgs), - /// Check a model binding's stored sizing constants on one hardware class against recorded workload resources. + /// Check a model binding's sizing constants against recorded workload resources Check(CheckArgs), } diff --git a/backend/cli/src/terminal/line.rs b/backend/cli/src/terminal/line.rs index 1780928e..ddf08cbb 100644 --- a/backend/cli/src/terminal/line.rs +++ b/backend/cli/src/terminal/line.rs @@ -17,6 +17,7 @@ use std::{ use super::{ ConfirmPrompt, CountdownPrompt, InputPrompt, Message, MultiSelectPrompt, PromptError, SelectItem, SelectPrompt, Terminal, TerminalCondition, + output::Output, render::{LastOutput, Symbols, plain_text}, }; @@ -32,6 +33,9 @@ pub(super) struct LineTerminal { /// What was printed last, which decides the blank line before the next output. last: LastOutput, + + /// Where command output goes. + output: Output, } struct LineIo { @@ -51,6 +55,7 @@ impl LineTerminal { echo_control: None, symbols: Symbols::ASCII, last: LastOutput::Nothing, + output: Output::stdout(false), }; }; let condition = if writer.is_terminal() { @@ -59,7 +64,8 @@ impl LineTerminal { TerminalCondition::NonInteractive }; let echo_control = writer.try_clone().ok(); - let mut terminal = Self::with_io(condition, BufReader::new(reader), writer); + let output = Output::stdout(condition == TerminalCondition::Interactive); + let mut terminal = Self::with_io(condition, BufReader::new(reader), writer, output); terminal.echo_control = echo_control; terminal.symbols = Symbols::detect(); terminal @@ -69,6 +75,7 @@ impl LineTerminal { condition: TerminalCondition, reader: impl BufRead + 'static, writer: impl Write + 'static, + output: Output, ) -> Self { Self { condition, @@ -79,6 +86,7 @@ impl LineTerminal { echo_control: None, symbols: Symbols::UNICODE, last: LastOutput::Nothing, + output, } } @@ -236,6 +244,24 @@ impl Terminal for LineTerminal { } fn message(&mut self, message: &Message) -> Result<(), PromptError> { + if matches!(message, Message::Warning(_)) { + return self.output.write_warning(message).map_err(PromptError::Io); + } + let rendered = message.render(self.symbols); + if !self.output.shares_screen() { + return self.output.write_plain(&rendered).map_err(PromptError::Io); + } + if self.last.blank_before(rendered.blank_before) { + writeln!(self.output.writer()).map_err(PromptError::Io)?; + } + self.output + .write_plain(&rendered) + .map_err(PromptError::Io)?; + self.last = LastOutput::Message; + Ok(()) + } + + fn prompt_context(&mut self, message: &Message) -> Result<(), PromptError> { let rendered = message.render(self.symbols); if self.last.blank_before(rendered.blank_before) { self.write_line("")?; @@ -362,7 +388,7 @@ mod tests { use super::LineTerminal; use crate::terminal::{ ConfirmPrompt, InputPrompt, Message, MultiSelectPrompt, NextStep, PromptError, SelectItem, - SelectPrompt, Terminal, TerminalCondition, render::Symbols, + SelectPrompt, Terminal, TerminalCondition, output::Output, render::Symbols, }; #[test] @@ -547,7 +573,7 @@ mod tests { .input(&InputPrompt::new("Node name")) .expect("name"); terminal - .message(&Message::Info( + .prompt_context(&Message::Info( "Accelerator detection: nvidia detected".to_owned(), )) .expect("context"); @@ -555,10 +581,10 @@ mod tests { .select(&SelectPrompt::new("Inference", [SelectItem::new("nvidia")])) .expect("inference"); terminal - .message(&Message::Heading("Initial site plan".to_owned())) + .prompt_context(&Message::Heading("Initial site plan".to_owned())) .expect("heading"); terminal - .message(&Message::Hint("Workers connect to this host.".to_owned())) + .prompt_context(&Message::Hint("Workers connect to this host.".to_owned())) .expect("hint"); terminal .confirm(&ConfirmPrompt::new("Write this site configuration?", true)) @@ -580,6 +606,61 @@ mod tests { ); } + #[test] + fn redirected_output_is_spaced_apart_from_the_prompts_and_their_context() { + let screen = SharedOutput::default(); + let stdout = SharedOutput::default(); + let mut terminal = LineTerminal::with_io( + TerminalCondition::Interactive, + Cursor::new(b"y\n".to_vec()), + screen.clone(), + Output::new(Box::new(stdout.clone()), Box::new(io::sink()), false), + ); + + terminal + .message(&Message::Heading("Nodes".to_owned())) + .expect("heading"); + terminal + .prompt_context(&Message::Heading("Remove gpu1".to_owned())) + .expect("review"); + terminal + .confirm(&ConfirmPrompt::new("Remove it?", false)) + .expect("confirmation"); + terminal + .message(&Message::Success("Removed gpu1".to_owned())) + .expect("outcome"); + terminal + .message(&Message::Heading("Next".to_owned())) + .expect("block"); + + assert_eq!(screen.text(), "Remove gpu1\nRemove it? [no]: "); + assert_eq!(stdout.text(), "Nodes\n✔ Removed gpu1\n\nNext\n"); + } + + #[test] + fn outcome_warnings_go_to_stderr_and_leave_the_output_alone() { + let screen = SharedOutput::default(); + let stdout = SharedOutput::default(); + let stderr = SharedOutput::default(); + let mut terminal = LineTerminal::with_io( + TerminalCondition::Interactive, + Cursor::new(Vec::new()), + screen.clone(), + Output::new(Box::new(stdout.clone()), Box::new(stderr.clone()), false), + ); + + terminal + .message(&Message::Success("Removed gpu1".to_owned())) + .expect("outcome"); + terminal + .message(&Message::Warning("gpu1 keeps its workloads".to_owned())) + .expect("warning"); + + assert_eq!(screen.text(), ""); + assert_eq!(stdout.text(), "✔ Removed gpu1\n"); + assert_eq!(stderr.text(), "! gpu1 keeps its workloads\n"); + } + #[test] fn consecutive_prompts_are_separated_but_a_reask_is_not() { let (mut terminal, output) = line_terminal("1\nmaybe\nn\n"); @@ -620,6 +701,27 @@ mod tests { assert_eq!(output.text(), "Plan\nx Failed\n"); } + #[test] + fn messages_without_a_terminal_go_to_stdout_while_prompts_still_fail() { + let stdout = SharedOutput::default(); + let mut terminal = LineTerminal::with_io( + TerminalCondition::NonInteractive, + Cursor::new(Vec::new()), + io::sink(), + Output::new(Box::new(stdout.clone()), Box::new(io::sink()), false), + ); + + terminal + .message(&Message::Success("Written".to_owned())) + .expect("message"); + + assert_eq!(stdout.text(), "✔ Written\n"); + assert!(matches!( + terminal.input(&InputPrompt::new("Site")), + Err(PromptError::NotInteractive) + )); + } + #[test] fn missing_controlling_terminal_is_non_interactive() { let mut terminal = LineTerminal::from_tty(None); @@ -631,14 +733,16 @@ mod tests { )); } + /// A terminal whose prompts and output share one screen. fn line_terminal(input: &str) -> (LineTerminal, SharedOutput) { - let output = SharedOutput::default(); + let screen = SharedOutput::default(); let terminal = LineTerminal::with_io( TerminalCondition::Interactive, Cursor::new(input.as_bytes().to_vec()), - output.clone(), + screen.clone(), + Output::new(Box::new(screen.clone()), Box::new(io::sink()), true), ); - (terminal, output) + (terminal, screen) } #[derive(Clone, Default)] diff --git a/backend/cli/src/terminal/mod.rs b/backend/cli/src/terminal/mod.rs index b96cfb57..a9f56432 100644 --- a/backend/cli/src/terminal/mod.rs +++ b/backend/cli/src/terminal/mod.rs @@ -1,19 +1,20 @@ -//! Terminal interaction for guided `dotc site init` and `dotc site reset`: -//! typed choices, checklists, yes/no confirmations, text answers, and styled messages -//! behind one injectable seam, for example a host choice returning its index. +//! Terminal interaction for `dotc` commands: typed choices, checklists, yes/no confirmations, +//! text answers, and styled messages behind one injectable seam, for example a host choice +//! returning its index. //! -//! Every prompt and message uses the controlling terminal (`/dev/tty`), never -//! process stdout or stderr, so the command's result records and diagnostics -//! stay exact. Messages share one layout (status marks, spacing, aligned facts, -//! tables, next steps), which diagnostics on a terminal stderr reuse. An answered -//! question closes its block, so whatever follows starts after a blank line, -//! while the messages leading up to a question stay attached to it as its -//! context. Capable terminals get arrow-key prompts with colors; dumb or -//! unknown terminal types, and terminals that never report their cursor -//! position, get plain line prompts. An operator cancel always surfaces as one -//! distinct outcome so the command exits with 130. +//! Prompts, and the messages that give them context, use the controlling terminal (`/dev/tty`); +//! command output goes to stdout and outcome warnings to stderr. They share one layout (status +//! marks, spacing, aligned facts, tables, next steps), which diagnostics on a terminal stderr +//! reuse. Output on a terminal stdout +//! shares the prompts' screen and styles; redirected output is plain lines. An answered question +//! closes its block, so whatever follows starts after a blank line, while the messages leading up +//! to a question stay attached to it as its context. Capable terminals get arrow-key prompts with +//! colors; dumb or unknown terminal types, and terminals that never report their cursor position, +//! get plain line prompts. An operator cancel always surfaces as one distinct outcome so the +//! command exits with 130. mod line; +mod output; mod render; mod rich; mod scripted; @@ -51,8 +52,12 @@ pub trait Terminal { /// read a single key press. fn countdown(&mut self, prompt: &CountdownPrompt) -> Result; - /// Displays one styled, non-prompt message to the operator. + /// Displays one styled message as command output, on stdout; a warning goes to stderr. fn message(&mut self, message: &Message) -> Result<(), PromptError>; + + /// Displays one styled message next to the prompts, as context the operator needs to answer + /// or act, such as a review before a confirmation or a command to run on another machine. + fn prompt_context(&mut self, message: &Message) -> Result<(), PromptError>; } /// Opens the process terminal: rich prompts on a capable controlling terminal, plain line diff --git a/backend/cli/src/terminal/output.rs b/backend/cli/src/terminal/output.rs new file mode 100644 index 00000000..298f1fe5 --- /dev/null +++ b/backend/cli/src/terminal/output.rs @@ -0,0 +1,122 @@ +//! Where a terminal writes command output: process stdout, kept apart from the prompts on the +//! controlling terminal, and process stderr for outcome warnings. +//! +//! When stdout is that terminal, output shares the prompts' screen, styles and spacing. When +//! stdout is redirected, output is written as plain lines with its own spacing, so a file or a +//! pipe receives the same text without colors or the prompts' blank lines. Warnings always go to +//! stderr, so stdout carries only the result. + +use std::io::{self, IsTerminal, Write}; + +use super::{ + Message, + render::{LastOutput, Rendered, plain_text, render_for_stderr}, +}; + +/// The command output stream of one terminal. +pub(super) struct Output { + writer: Box, + placement: Placement, + diagnostics: Diagnostics, +} + +/// Where outcome warnings go. +enum Diagnostics { + /// Process stderr, laid out with the shared look when it is a terminal. + Stderr, + + /// An injected stream, written as plain lines. + #[cfg(test)] + Plain(Box), +} + +/// Whether output lands on the prompts' screen or on a separate stream. +enum Placement { + /// Output and prompts appear on the same screen, which the terminal spaces as one. + Screen, + + /// Output goes elsewhere and is spaced on its own. + Stream { last: LastOutput }, +} + +impl Output { + /// Opens process stdout; `screen` tells whether a controlling terminal draws the prompts, so a + /// terminal stdout shares their screen. + pub(super) fn stdout(screen: bool) -> Self { + let shares_screen = screen && io::stdout().is_terminal(); + Self::with_diagnostics(Box::new(io::stdout()), shares_screen, Diagnostics::Stderr) + } + + /// Creates output on `writer` with warnings on `diagnostics`, sharing the prompts' screen + /// when `shares_screen` is set. + #[cfg(test)] + pub(super) fn new( + writer: Box, + diagnostics: Box, + shares_screen: bool, + ) -> Self { + Self::with_diagnostics(writer, shares_screen, Diagnostics::Plain(diagnostics)) + } + + fn with_diagnostics( + writer: Box, + shares_screen: bool, + diagnostics: Diagnostics, + ) -> Self { + let placement = if shares_screen { + Placement::Screen + } else { + Placement::Stream { + last: LastOutput::Nothing, + } + }; + Self { + writer, + placement, + diagnostics, + } + } + + /// Reports whether output shares the prompts' screen. + pub(super) fn shares_screen(&self) -> bool { + matches!(self.placement, Placement::Screen) + } + + /// Returns the writer, for a terminal laying out output on its own screen. + pub(super) fn writer(&mut self) -> &mut dyn Write { + &mut self.writer + } + + /// Writes a message as plain lines. On a separate stream, a blank line comes first when the + /// message starts a block after earlier output; on the screen, the terminal spaces it. + pub(super) fn write_plain(&mut self, rendered: &Rendered) -> io::Result<()> { + if let Placement::Stream { last } = &mut self.placement { + if last.blank_before(rendered.blank_before) { + writeln!(self.writer)?; + } + *last = LastOutput::Message; + } + for line in &rendered.lines { + writeln!(self.writer, "{}", plain_text(line))?; + } + self.writer.flush() + } + + /// Writes an outcome warning on stderr, apart from the result on stdout. + pub(super) fn write_warning(&mut self, message: &Message) -> io::Result<()> { + let plain = || message.plain_lines().join("\n") + "\n"; + match &mut self.diagnostics { + Diagnostics::Stderr => { + let text = render_for_stderr(std::slice::from_ref(message)).unwrap_or_else(plain); + let mut stderr = io::stderr().lock(); + stderr.write_all(text.as_bytes())?; + stderr.flush() + } + #[cfg(test)] + Diagnostics::Plain(writer) => { + writer.write_all(plain().as_bytes())?; + writer.flush() + } + } + } +} diff --git a/backend/cli/src/terminal/rich/mod.rs b/backend/cli/src/terminal/rich/mod.rs index 8fedd6bd..57782403 100644 --- a/backend/cli/src/terminal/rich/mod.rs +++ b/backend/cli/src/terminal/rich/mod.rs @@ -32,6 +32,7 @@ use super::{ ConfirmPrompt, CountdownPrompt, InputPrompt, Message, MultiSelectPrompt, PromptError, SelectPrompt, Terminal, TerminalCondition, line::LineTerminal, + output::Output, render::{LastOutput, Symbols, colors_enabled}, }; use theme::Theme; @@ -52,6 +53,9 @@ pub(super) struct RichTerminal { /// Real-time bounds of the terminal's answers. timing: TerminalTiming, + + /// Where command output goes. + output: Output, } impl RichTerminal { @@ -70,6 +74,7 @@ impl RichTerminal { symbols: Symbols::detect(), last: LastOutput::Nothing, timing, + output: Output::stdout(true), }) } @@ -99,8 +104,7 @@ impl RichTerminal { self.ensure_interactive()?; if self.last.blank_before(false) { // Written before the inline viewport opens, which then starts on the row below. - self.write_lines(vec![Line::default()]) - .map_err(PromptError::Io)?; + write_lines(&mut self.tty, vec![Line::default()]).map_err(PromptError::Io)?; } // A cancelled prompt still leaves its summary line. self.last = LastOutput::Message; @@ -168,18 +172,22 @@ impl RichTerminal { Ok(outcome) } - fn write_lines(&mut self, lines: Vec>) -> io::Result<()> { - for line in lines { - for span in line.spans { - let style = span.style.patch(line.style).into_crossterm(); - crossterm::queue!( - self.tty, - PrintStyledContent(crossterm::style::StyledContent::new(style, span.content)) - )?; - } - self.tty.write_all(b"\n")?; + /// Lays out a message with the theme and the prompts' spacing: on stdout when `on_output` is + /// set, which then shares the prompts' screen, else on the controlling terminal. + fn show(&mut self, message: &Message, on_output: bool) -> Result<(), PromptError> { + let rendered = message.render(self.symbols); + let mut lines = Vec::new(); + if self.last.blank_before(rendered.blank_before) { + lines.push(Line::default()); } - self.tty.flush() + lines.extend(rendered.lines.iter().map(|line| self.theme.line(line))); + self.last = LastOutput::Message; + let writer: &mut dyn Write = if on_output { + self.output.writer() + } else { + &mut self.tty + }; + write_lines(writer, lines).map_err(PromptError::Io) } } @@ -226,14 +234,34 @@ impl Terminal for RichTerminal { } fn message(&mut self, message: &Message) -> Result<(), PromptError> { + if matches!(message, Message::Warning(_)) { + return self.output.write_warning(message).map_err(PromptError::Io); + } self.ensure_interactive()?; + if self.output.shares_screen() { + return self.show(message, true); + } let rendered = message.render(self.symbols); - let mut lines = Vec::new(); - if self.last.blank_before(rendered.blank_before) { - lines.push(Line::default()); + self.output.write_plain(&rendered).map_err(PromptError::Io) + } + + fn prompt_context(&mut self, message: &Message) -> Result<(), PromptError> { + self.ensure_interactive()?; + self.show(message, false) + } +} + +/// Writes styled lines to `writer`, one per row. +fn write_lines(mut writer: &mut dyn Write, lines: Vec>) -> io::Result<()> { + for line in lines { + for span in line.spans { + let style = span.style.patch(line.style).into_crossterm(); + crossterm::queue!( + &mut writer, + PrintStyledContent(crossterm::style::StyledContent::new(style, span.content)) + )?; } - lines.extend(rendered.lines.iter().map(|line| self.theme.line(line))); - self.last = LastOutput::Message; - self.write_lines(lines).map_err(PromptError::Io) + writer.write_all(b"\n")?; } + writer.flush() } diff --git a/backend/cli/src/terminal/rich/tty.rs b/backend/cli/src/terminal/rich/tty.rs index 09c701a2..e6d3d00c 100644 --- a/backend/cli/src/terminal/rich/tty.rs +++ b/backend/cli/src/terminal/rich/tty.rs @@ -76,8 +76,8 @@ pub(super) fn probe_cursor_reports(tty: &File, timing: TerminalTiming) -> io::Re /// A crossterm backend drawing on the controlling terminal. /// -/// Only the cursor-position query is replaced: crossterm sends it to process stdout, which must -/// carry nothing but the command's result records. +/// Only the cursor-position query is replaced: crossterm sends it to process stdout, which may be +/// redirected and carries only command output. pub(super) struct TtyBackend { inner: CrosstermBackend, tty: File, diff --git a/backend/cli/src/terminal/scripted.rs b/backend/cli/src/terminal/scripted.rs index 224d3f57..21404ba0 100644 --- a/backend/cli/src/terminal/scripted.rs +++ b/backend/cli/src/terminal/scripted.rs @@ -4,7 +4,8 @@ //! Each answer names the prompt kind it answers, for example a choice index //! or a yes/no decision, and a test fails immediately when the flow asks a //! different kind of question than the script expects. Every prompt and the -//! plain text of every message are recorded for assertions. +//! plain text of every message, output or prompt context, are recorded in order for +//! assertions. use std::collections::{BTreeSet, VecDeque}; @@ -168,6 +169,10 @@ impl Terminal for ScriptedTerminal { self.messages.push(message.clone()); Ok(()) } + + fn prompt_context(&mut self, message: &Message) -> Result<(), PromptError> { + self.message(message) + } } /// A prompt presented to a scripted terminal. diff --git a/backend/cli/src/workload/mod.rs b/backend/cli/src/workload/mod.rs index 1a3c3187..9e5559d8 100644 --- a/backend/cli/src/workload/mod.rs +++ b/backend/cli/src/workload/mod.rs @@ -71,19 +71,19 @@ struct WorkloadCommand { #[derive(Debug, Subcommand)] enum WorkloadAction { - /// Resolve and launch a workload. + /// Resolve and launch a workload Launch(LaunchArgs), - /// Inspect an ownership handle and its runtime namespace. + /// Inspect an ownership handle and its runtime namespace Inspect(InspectArgs), - /// Read workload diagnostics. + /// Read workload diagnostics Logs(LogsArgs), - /// Observe exact-process NVIDIA VRAM without mutating the workload. + /// Observe the exact-process NVIDIA VRAM of a workload Vram(VramArgs), - /// Stop and remove the owned workload. + /// Stop and remove the owned workload Teardown(TeardownArgs), } diff --git a/backend/cli/src/workload/teardown_all.rs b/backend/cli/src/workload/teardown_all.rs index 6b173042..ddeb4a45 100644 --- a/backend/cli/src/workload/teardown_all.rs +++ b/backend/cli/src/workload/teardown_all.rs @@ -170,10 +170,10 @@ fn confirm( live.len() ); } - terminal.message(&Message::Heading( + terminal.prompt_context(&Message::Heading( "These development workloads will be stopped and removed:".to_owned(), ))?; - terminal.message(&Message::KeyValues( + terminal.prompt_context(&Message::KeyValues( live.iter() .map(|handle| { ( diff --git a/backend/cli/tests/application_contract.rs b/backend/cli/tests/application_contract.rs index 6c942def..07370d35 100644 --- a/backend/cli/tests/application_contract.rs +++ b/backend/cli/tests/application_contract.rs @@ -19,6 +19,7 @@ use dotcore_proto::{ }, google::protobuf::Timestamp, }; +use serde_json::json; use tonic::Status; mod support; @@ -33,7 +34,7 @@ use support::{ }; #[test] -fn list_prints_one_record_block_per_deployment_in_every_state() { +fn list_prints_a_table_with_one_row_per_deployment_in_every_state() { let manager = FakeManager::start(FakeState::with_applications(mixed_deployments())); let output = run(&manager, &["list"]); @@ -42,15 +43,7 @@ fn list_prints_one_record_block_per_deployment_in_every_state() { assert_eq!(output.status.code(), Some(0)); assert_eq!( text(&output.stdout), - [ - list_block("app-1", "Chat", "Ready", "false"), - list_block("app-2", "Notes", "Starting", "false"), - list_block("app-3", "Wiki", "Failed", "false"), - list_block("app-4", "Docs", "Paused", "false"), - list_block("app-5", "Old", "Tearing down", "false"), - list_block("app-6", "Mirror", "Running", "true"), - ] - .join("\n") + " NAME ID STATE NODE APPLICATION\n Chat app-1 Ready gb10-host Open WebUI\n Notes app-2 Starting gb10-host Open WebUI\n Wiki app-3 Failed gb10-host Open WebUI\n Docs app-4 Paused gb10-host Open WebUI\n Old app-5 Tearing down gb10-host Open WebUI\n Mirror app-6 Running (stale) gb10-host Open WebUI\n" ); assert_eq!( manager.calls(), @@ -71,20 +64,20 @@ fn list_shows_the_node_id_when_the_manager_does_not_name_the_node() { assert_eq!(output.status.code(), Some(0)); assert!( - text(&output.stdout).contains("DOTCORE_APPLICATION_DEPLOYMENT_NODE=node-1\n"), + text(&output.stdout).contains(" Chat app-1 Ready node-1 Open WebUI\n"), "{}", text(&output.stdout) ); } #[test] -fn list_of_an_empty_site_prints_nothing() { +fn list_of_an_empty_site_says_there_are_no_deployments() { let manager = FakeManager::start(FakeState::with_applications(Vec::new())); let output = run(&manager, &["list"]); assert_eq!(output.status.code(), Some(0)); - assert_eq!(text(&output.stdout), ""); + assert_eq!(text(&output.stdout), "No application deployments\n"); assert_eq!(text(&output.stderr), ""); } @@ -115,22 +108,7 @@ fn show_prints_every_key_for_a_running_deployment_with_its_endpoint() { assert_eq!(output.status.code(), Some(0)); assert_eq!( text(&output.stdout), - block(&[ - ("ID", "app-1"), - ("NAME", "Chat"), - ("STATE", "Ready"), - ("DESIRED_STATE", "Present"), - ("READINESS", "Ready"), - ("STALE", "false"), - ("NODE", "gb10-host"), - ("EXECUTION_TARGET", "node-1-apps"), - ("APPLICATION", "Open WebUI"), - ("SERVICES", "web: Running, db: Starting"), - ("ENDPOINT", "http://gb10-host:8080"), - ("ROUTE", "gemma"), - ("FAILURE", ""), - ("MESSAGE", ""), - ]) + "Application deployment Chat\n name Chat\n id app-1\n state Ready\n desired Present\n readiness Ready\n node gb10-host\n target Docker applications\n target id node-1-apps\n application Open WebUI\n service web Running\n service db Starting\n endpoint http://gb10-host:8080\n route gemma\n" ); } @@ -144,60 +122,15 @@ fn show_reports_stage_failure_and_stale_observation_by_id() { assert_eq!( text(&starting.stdout), - block(&[ - ("ID", "app-2"), - ("NAME", "Notes"), - ("STATE", "Starting"), - ("DESIRED_STATE", "Present"), - ("READINESS", ""), - ("STALE", "false"), - ("NODE", "gb10-host"), - ("EXECUTION_TARGET", "node-1-apps"), - ("APPLICATION", "Open WebUI"), - ("SERVICES", "web: Starting"), - ("ENDPOINT", ""), - ("ROUTE", ""), - ("FAILURE", ""), - ("MESSAGE", "Pulling images"), - ]) + "Application deployment Notes\n name Notes\n id app-2\n state Starting\n desired Present\n node gb10-host\n target Docker applications\n target id node-1-apps\n application Open WebUI\n service web Starting\n message Pulling images\n" ); assert_eq!( text(&failed.stdout), - block(&[ - ("ID", "app-3"), - ("NAME", "Wiki"), - ("STATE", "Failed"), - ("DESIRED_STATE", "Present"), - ("READINESS", ""), - ("STALE", "false"), - ("NODE", "gb10-host"), - ("EXECUTION_TARGET", "node-1-apps"), - ("APPLICATION", "Open WebUI"), - ("SERVICES", "web: Failed"), - ("ENDPOINT", ""), - ("ROUTE", ""), - ("FAILURE", "Image pull failed"), - ("MESSAGE", ""), - ]) + "Application deployment Wiki\n name Wiki\n id app-3\n state Failed\n desired Present\n node gb10-host\n target Docker applications\n target id node-1-apps\n application Open WebUI\n service web Failed\n failure Image pull failed\n" ); assert_eq!( text(&stale.stdout), - block(&[ - ("ID", "app-6"), - ("NAME", "Mirror"), - ("STATE", "Running"), - ("DESIRED_STATE", "Present"), - ("READINESS", "Not ready"), - ("STALE", "true"), - ("NODE", "gb10-host"), - ("EXECUTION_TARGET", "node-1-apps"), - ("APPLICATION", "Open WebUI"), - ("SERVICES", ""), - ("ENDPOINT", ""), - ("ROUTE", ""), - ("FAILURE", ""), - ("MESSAGE", ""), - ]) + "Application deployment Mirror\n name Mirror\n id app-6\n state Running\n desired Present\n readiness Not ready\n stale yes\n node gb10-host\n target Docker applications\n target id node-1-apps\n application Open WebUI\n" ); } @@ -217,23 +150,20 @@ fn show_applies_the_console_state_overrides() { let tearing_down = run(&manager, &["show", "Old"]); assert!( - text(&paused.stdout).contains( - "STATE=Paused\nDOTCORE_APPLICATION_DEPLOYMENT_DESIRED_STATE=Paused\nDOTCORE_APPLICATION_DEPLOYMENT_READINESS=\n" - ), + text(&paused.stdout).contains(" state Paused\n desired Paused\n node"), "{}", text(&paused.stdout) ); + let pausing = text(&pausing.stdout); assert!( - text(&pausing.stdout).contains( - "STATE=Pausing\nDOTCORE_APPLICATION_DEPLOYMENT_DESIRED_STATE=Paused\nDOTCORE_APPLICATION_DEPLOYMENT_READINESS=\n" - ) && text(&pausing.stdout).contains("DOTCORE_APPLICATION_DEPLOYMENT_ENDPOINT=\n"), - "a requested pause hides readiness and endpoint\n{}", - text(&pausing.stdout) + pausing.contains(" state Pausing\n desired Paused\n node") + && !pausing.contains("readiness") + && !pausing.contains("endpoint"), + "a requested pause hides readiness and endpoint\n{pausing}" ); assert!( - text(&tearing_down.stdout).contains( - "STATE=Tearing down\nDOTCORE_APPLICATION_DEPLOYMENT_DESIRED_STATE=Teardown\n" - ), + text(&tearing_down.stdout) + .contains(" state Tearing down\n desired Teardown\n node"), "{}", text(&tearing_down.stdout) ); @@ -252,41 +182,11 @@ fn show_hides_the_stage_that_a_requested_change_overrides() { assert_eq!( text(&tearing_down.stdout), - block(&[ - ("ID", "app-7"), - ("NAME", "Old Wiki"), - ("STATE", "Tearing down"), - ("DESIRED_STATE", "Teardown"), - ("READINESS", ""), - ("STALE", "false"), - ("NODE", "gb10-host"), - ("EXECUTION_TARGET", "node-1-apps"), - ("APPLICATION", "Open WebUI"), - ("SERVICES", ""), - ("ENDPOINT", ""), - ("ROUTE", ""), - ("FAILURE", ""), - ("MESSAGE", ""), - ]) + "Application deployment Old Wiki\n name Old Wiki\n id app-7\n state Tearing down\n desired Teardown\n node gb10-host\n target Docker applications\n target id node-1-apps\n application Open WebUI\n" ); assert_eq!( text(&pausing.stdout), - block(&[ - ("ID", "app-8"), - ("NAME", "Calendar"), - ("STATE", "Pausing"), - ("DESIRED_STATE", "Paused"), - ("READINESS", ""), - ("STALE", "false"), - ("NODE", "gb10-host"), - ("EXECUTION_TARGET", "node-1-apps"), - ("APPLICATION", "Open WebUI"), - ("SERVICES", ""), - ("ENDPOINT", ""), - ("ROUTE", ""), - ("FAILURE", ""), - ("MESSAGE", ""), - ]) + "Application deployment Calendar\n name Calendar\n id app-8\n state Pausing\n desired Paused\n node gb10-host\n target Docker applications\n target id node-1-apps\n application Open WebUI\n" ); } @@ -303,7 +203,7 @@ fn a_generated_stored_name_addresses_the_deployment_like_its_display_name() { assert_eq!(by_stored_name.status.code(), Some(0)); assert!( text(&by_stored_name.stdout).starts_with( - "Application deployment\nDOTCORE_APPLICATION_DEPLOYMENT_ID=app-9\nDOTCORE_APPLICATION_DEPLOYMENT_NAME=Open WebUI\n" + "Application deployment Open WebUI\n name Open WebUI\n id app-9\n" ), "{}", text(&by_stored_name.stdout) @@ -372,7 +272,7 @@ fn commands_need_no_site_folder() { let output = command.output().expect("run dotc application list"); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); - assert!(text(&output.stdout).contains("DOTCORE_APPLICATION_DEPLOYMENT_ID=app-1\n")); + assert!(text(&output.stdout).contains(" Chat app-1 Ready")); assert_eq!( std::fs::read_dir(empty.path()) .expect("read working directory") @@ -435,6 +335,203 @@ fn logs_read_then_follow_an_application_deployment() { ); } +#[test] +fn yaml_list_prints_the_manager_deployments_with_their_names() { + let manager = FakeManager::start(FakeState::with_applications(vec![ + local_application_deployment("app-1", "Chat", Running, Present), + ])); + + let output = run(&manager, &["list", "--yaml"]); + + assert_eq!(text(&output.stderr), ""); + assert_eq!(output.status.code(), Some(0)); + let placement = json!({ + "siteNodeId": "node-1", + "executionTargetId": "node-1-apps", + }); + assert_eq!( + support::yaml_documents(&text(&output.stdout)), + [json!({ + "deployments": [{ + "applicationDeploymentId": "app-1", + "applicationDeploymentName": "Chat", + "placement": placement, + "snapshot": { + "applicationId": "open-webui", + "displayName": "Open WebUI", + "placement": placement, + }, + "desiredState": "APPLICATION_DEPLOYMENT_DESIRED_STATE_PRESENT", + "state": { "lifecycleState": "APPLICATION_LIFECYCLE_STATE_RUNNING" }, + "siteNodeDisplayName": "gb10-host", + "executionTargetDisplayName": "Docker applications", + }], + })] + ); +} + +#[test] +fn yaml_lifecycle_verbs_print_the_accepted_deployment_with_its_names() { + let manager = FakeManager::start(FakeState::with_applications(vec![ + local_application_deployment("app-1", "Chat", Running, Present), + local_application_deployment("app-2", "Notes", Running, Present), + local_application_deployment("app-3", "Wiki", Running, Present), + ])); + let placement = json!({ + "siteNodeId": "node-1", + "executionTargetId": "node-1-apps", + }); + let document = |id: &str, name: &str, desired: &str, lifecycle: &str| { + json!({ + "applicationDeploymentId": id, + "applicationDeploymentName": name, + "placement": placement, + "snapshot": { + "applicationId": "open-webui", + "displayName": "Open WebUI", + "placement": placement, + }, + "desiredState": desired, + "state": { "lifecycleState": lifecycle }, + "siteNodeDisplayName": "gb10-host", + "executionTargetDisplayName": "Docker applications", + }) + }; + + let paused = run(&manager, &["pause", "Chat", "--yaml"]); + let resumed = run(&manager, &["resume", "Notes", "--yaml"]); + let torn_down = run(&manager, &["teardown", "Wiki", "--yaml", "--yes"]); + let refused = run(&manager, &["teardown", "Chat", "--yaml"]); + + for output in [&paused, &resumed, &torn_down] { + assert_eq!(text(&output.stderr), ""); + assert_eq!(output.status.code(), Some(0)); + } + assert_eq!( + support::yaml_documents(&text(&paused.stdout)), + [document( + "app-1", + "Chat", + "APPLICATION_DEPLOYMENT_DESIRED_STATE_PAUSED", + "APPLICATION_LIFECYCLE_STATE_RUNNING" + )] + ); + assert_eq!( + support::yaml_documents(&text(&resumed.stdout)), + [document( + "app-2", + "Notes", + "APPLICATION_DEPLOYMENT_DESIRED_STATE_PRESENT", + "APPLICATION_LIFECYCLE_STATE_RUNNING" + )] + ); + assert_eq!( + support::yaml_documents(&text(&torn_down.stdout)), + [document( + "app-3", + "Wiki", + "APPLICATION_DEPLOYMENT_DESIRED_STATE_TEARDOWN", + "APPLICATION_LIFECYCLE_STATE_STOPPING" + )] + ); + assert_eq!(refused.status.code(), Some(1)); + assert_eq!(text(&refused.stdout), ""); + assert_eq!( + text(&refused.stderr), + "tearing down an application deployment needs confirmation, which --yaml never asks for; pass --yes to tear it down\n" + ); + assert_eq!( + lifecycle_calls(&manager), + vec![ + call(Rpc::PauseApplicationDeployment, Some("app-1")), + call(Rpc::ResumeApplicationDeployment, Some("app-2")), + call(Rpc::RemoveApplicationDeployment, Some("app-3")), + ] + ); +} + +#[test] +fn yaml_list_and_show_mask_secret_values_unless_revealed() { + let deployment = deployment_with_parameters(); + let manager = FakeManager::start(FakeState::with_applications(vec![deployment.clone()])); + + let listed = run(&manager, &["list", "--yaml"]); + let masked = run(&manager, &["show", "Chat", "--yaml"]); + let revealed = run(&manager, &["show", "Chat", "--yaml", "--reveal-secrets"]); + + let mut revealed_document = serde_json::to_value(&deployment).expect("deployment mapping"); + revealed_document["siteNodeDisplayName"] = json!("gb10-host"); + revealed_document["executionTargetDisplayName"] = json!("Docker applications"); + let mut masked_document = revealed_document.clone(); + let password = masked_document["snapshot"]["parameterValues"] + .as_array_mut() + .expect("values") + .iter_mut() + .find(|value| value["parameterId"] == "admin-password") + .expect("password value"); + assert_eq!(password["string"], "s3cretPassw0rd"); + password["string"] = json!("********"); + assert_eq!( + support::yaml_documents(&text(&listed.stdout)), + [json!({ "deployments": [masked_document.clone()] })] + ); + assert_eq!( + support::yaml_documents(&text(&masked.stdout)), + [masked_document] + ); + assert_eq!( + support::yaml_documents(&text(&revealed.stdout)), + [revealed_document] + ); + for output in [listed, masked, revealed] { + assert_eq!(text(&output.stderr), ""); + assert_eq!(output.status.code(), Some(0)); + } +} + +#[test] +fn yaml_logs_print_one_document_per_entry() { + let manager = FakeManager::start(FakeState::with_applications(mixed_deployments())); + { + let mut state = manager.state(); + state.application_logs.page = ReadDeploymentLogsResponse { + sources: vec![log_source("web", DeploymentLogSourceState::Available)], + entries: vec![log_entry("web", 10, b"serving")], + ..Default::default() + }; + state.application_logs.follow = vec![Ok(FollowDeploymentLogsResponse { + event: Some(Event::Entry(log_entry("web", 11, b"stopping"))), + })]; + } + + let output = run(&manager, &["logs", "Chat", "--follow", "--yaml"]); + + assert_eq!( + text(&output.stderr), + "the log follow of application deployment Chat ended\n" + ); + assert_eq!(output.status.code(), Some(0)); + assert_eq!( + support::yaml_documents(&text(&output.stdout)), + [ + json!({ + "sourceName": "web", + "sourceLabel": "Web", + "timestamp": { "seconds": "1794500010" }, + "content": "c2VydmluZw==", + "text": "serving", + }), + json!({ + "sourceName": "web", + "sourceLabel": "Web", + "timestamp": { "seconds": "1794500011" }, + "content": "c3RvcHBpbmc=", + "text": "stopping", + }), + ] + ); +} + #[test] fn help_lists_the_six_verbs_and_the_manager_flag() { let group = isolated_dotc() @@ -442,7 +539,7 @@ fn help_lists_the_six_verbs_and_the_manager_flag() { .output() .expect("run help"); let list = isolated_dotc() - .args(["application", "list", "--help"]) + .args(["application", "list", "-h"]) .output() .expect("run help"); @@ -472,15 +569,9 @@ fn pause_and_resume_request_the_change_and_print_the_accepted_state() { let paused = run(&manager, &["pause", "Chat"]); - assert_eq!( - text(&paused.stderr), - "Notice: Run `dotc application list` to follow its progress.\n" - ); + assert_eq!(text(&paused.stderr), ""); assert_eq!(paused.status.code(), Some(0)); - assert_eq!( - text(&paused.stdout), - "Application deployment\nDOTCORE_APPLICATION_DEPLOYMENT_ID=app-1\nDOTCORE_APPLICATION_DEPLOYMENT_NAME=Chat\nDOTCORE_APPLICATION_DEPLOYMENT_STATE=Pausing\nDOTCORE_APPLICATION_DEPLOYMENT_DESIRED_STATE=Paused\n" - ); + assert_eq!(text(&paused.stdout), "✔ Pausing Chat\n"); assert_eq!( manager.application_deployment("app-1").desired_state(), Paused @@ -489,10 +580,8 @@ fn pause_and_resume_request_the_change_and_print_the_accepted_state() { let resumed = run(&manager, &["resume", "app-4"]); assert_eq!(resumed.status.code(), Some(0)); - assert_eq!( - text(&resumed.stdout), - "Application deployment\nDOTCORE_APPLICATION_DEPLOYMENT_ID=app-4\nDOTCORE_APPLICATION_DEPLOYMENT_NAME=Docs\nDOTCORE_APPLICATION_DEPLOYMENT_STATE=Paused\nDOTCORE_APPLICATION_DEPLOYMENT_DESIRED_STATE=Present\n" - ); + assert_eq!(text(&resumed.stderr), ""); + assert_eq!(text(&resumed.stdout), "✔ Resuming Docs\n"); assert_eq!( manager.application_deployment("app-4").desired_state(), Present @@ -513,10 +602,8 @@ fn teardown_with_yes_removes_the_deployment_and_prints_the_accepted_state() { let output = run(&manager, &["teardown", "Wiki", "--yes"]); assert_eq!(output.status.code(), Some(0)); - assert_eq!( - text(&output.stdout), - "Application deployment\nDOTCORE_APPLICATION_DEPLOYMENT_ID=app-3\nDOTCORE_APPLICATION_DEPLOYMENT_NAME=Wiki\nDOTCORE_APPLICATION_DEPLOYMENT_STATE=Tearing down\nDOTCORE_APPLICATION_DEPLOYMENT_DESIRED_STATE=Teardown\n" - ); + assert_eq!(text(&output.stderr), ""); + assert_eq!(text(&output.stdout), "✔ Tearing down Wiki\n"); assert_eq!( manager.application_deployment("app-3").desired_state(), Teardown @@ -592,7 +679,10 @@ fn an_answer_without_the_asked_desired_state_is_not_accepted() { fn a_terminal_shows_the_list_as_a_table() { let manager = FakeManager::start(FakeState::with_applications(mixed_deployments())); - let Some(run) = run_in_pty(terminal_command(&manager, &["list"]), Session::new([])) else { + let Some(run) = run_in_pty( + terminal_command(&manager, &["list"]), + Session::new([]).with_stdout_on_terminal(), + ) else { return; }; @@ -622,7 +712,7 @@ fn a_terminal_shows_the_details_of_one_deployment() { let Some(run) = run_in_pty( terminal_command(&manager, &["show", "Chat"]), - Session::new([]), + Session::new([]).with_stdout_on_terminal(), ) else { return; }; @@ -653,12 +743,12 @@ fn a_terminal_shows_the_details_of_one_deployment() { } #[test] -fn a_terminal_reports_a_pause_with_the_next_step() { +fn a_terminal_reports_a_pause_without_a_next_step() { let manager = FakeManager::start(FakeState::with_applications(mixed_deployments())); let Some(run) = run_in_pty( terminal_command(&manager, &["pause", "Chat"]), - Session::new([]), + Session::new([]).with_stdout_on_terminal(), ) else { return; }; @@ -666,9 +756,7 @@ fn a_terminal_reports_a_pause_with_the_next_step() { assert_eq!(run.code(), Some(0), "screen:\n{}", run.screen()); assert_eq!(run.stdout(), ""); assert_eq!(run.stderr(), ""); - let lines = run.screen().lines().map(str::trim).collect::>(); - assert!(lines.contains(&"OK Pausing Chat"), "{}", run.screen()); - assert!(lines.contains(&"dotc application list"), "{}", run.screen()); + assert_eq!(run.screen().trim(), "OK Pausing Chat"); assert_eq!( manager.application_deployment("app-1").desired_state(), Paused @@ -685,14 +773,13 @@ fn a_terminal_teardown_warns_about_data_and_removes_when_accepted() { Step::Wait("Tear down Chat?"), Step::Wait("[no]"), Step::Send(b"yes\n"), - Step::Wait("Tearing down Chat"), ]), ) else { return; }; assert_eq!(run.code(), Some(0), "screen:\n{}", run.screen()); - assert_eq!(run.stdout(), ""); + assert_eq!(run.stdout(), "OK Tearing down Chat\n"); assert_eq!(run.stderr(), ""); let screen = run .screen() @@ -748,10 +835,7 @@ fn show_prints_parameters_in_catalog_order_with_secrets_masked() { assert_eq!(output.status.code(), Some(0)); let stdout = text(&output.stdout); assert!(!stdout.contains("s3cretPassw0rd"), "{stdout}"); - assert_eq!( - support::parameter_lines(&stdout, PARAMETER_PREFIX), - PARAMETER_LINES_MASKED - ); + assert_eq!(support::parameter_rows(&stdout), PARAMETER_ROWS_MASKED); } #[test] @@ -803,8 +887,8 @@ fn show_prints_only_retained_parameters() { assert_eq!(output.status.code(), Some(0)); assert_eq!( - support::parameter_lines(&text(&output.stdout), PARAMETER_PREFIX), - ["DOTCORE_APPLICATION_DEPLOYMENT_PARAMETER_REQUIRE_LOGIN=false"] + support::parameter_rows(&text(&output.stdout)), + ["Require login false"] ); } @@ -817,11 +901,8 @@ fn show_reveals_secret_parameters_with_the_flag() { let output = run(&manager, &["show", "Chat", "--reveal-secrets"]); assert_eq!(output.status.code(), Some(0)); - let revealed = PARAMETER_LINES_MASKED.map(|line| line.replace("********", "s3cretPassw0rd")); - assert_eq!( - support::parameter_lines(&text(&output.stdout), PARAMETER_PREFIX), - revealed - ); + let revealed = PARAMETER_ROWS_MASKED.map(|line| line.replace("********", "s3cretPassw0rd")); + assert_eq!(support::parameter_rows(&text(&output.stdout)), revealed); } #[test] @@ -849,7 +930,7 @@ fn a_terminal_shows_parameters_under_their_own_heading() { let Some(run) = run_in_pty( terminal_command(&manager, &["show", "Chat"]), - Session::new([]), + Session::new([]).with_stdout_on_terminal(), ) else { return; }; @@ -877,13 +958,12 @@ fn a_terminal_shows_parameters_under_their_own_heading() { ); } -const PARAMETER_PREFIX: &str = "DOTCORE_APPLICATION_DEPLOYMENT_PARAMETER_"; -const PARAMETER_LINES_MASKED: [&str; 5] = [ - "DOTCORE_APPLICATION_DEPLOYMENT_PARAMETER_WEB_SEARCH=true", - "DOTCORE_APPLICATION_DEPLOYMENT_PARAMETER_MEMORY_LIMIT=2048 MB", - "DOTCORE_APPLICATION_DEPLOYMENT_PARAMETER_MODE=fast", - "DOTCORE_APPLICATION_DEPLOYMENT_PARAMETER_WELCOME_NOTE=Empty", - "DOTCORE_APPLICATION_DEPLOYMENT_PARAMETER_ADMIN_PASSWORD=********", +const PARAMETER_ROWS_MASKED: [&str; 5] = [ + "Web search true", + "Memory limit 2048 MB", + "Mode fast", + "Welcome note Empty", + "Admin password ********", ]; /// A deployment with one parameter of each kind: a default boolean, a non-default integer with a @@ -1027,27 +1107,6 @@ fn service(name: &str, state: ApplicationServiceLifecycleState) -> ApplicationSe } } -/// The record block `application list` prints for one seeded deployment. -fn list_block(id: &str, name: &str, state: &str, stale: &str) -> String { - block(&[ - ("ID", id), - ("NAME", name), - ("STATE", state), - ("STALE", stale), - ("NODE", "gb10-host"), - ("APPLICATION", "Open WebUI"), - ]) -} - -/// Renders `fields` as an application deployment record block. -fn block(fields: &[(&str, &str)]) -> String { - let mut block = "Application deployment\n".to_owned(); - for (key, value) in fields { - block.push_str(&format!("DOTCORE_APPLICATION_DEPLOYMENT_{key}={value}\n")); - } - block -} - fn call(rpc: Rpc, id: Option<&str>) -> Call { Call { rpc, diff --git a/backend/cli/tests/application_manager_contract.rs b/backend/cli/tests/application_manager_contract.rs index 0860e7d4..8d6a2cbe 100644 --- a/backend/cli/tests/application_manager_contract.rs +++ b/backend/cli/tests/application_manager_contract.rs @@ -36,38 +36,25 @@ fn application_commands_drive_a_simulated_deployment_through_pause_resume_and_te let list = run(&manager, &["list"]); assert_eq!(text(&list.stderr), ""); assert_eq!(list.status.code(), Some(0)); - assert_eq!( - text(&list.stdout), - block(&[ - ("ID", &id), - ("NAME", "Round trip"), - ("STATE", "Ready"), - ("STALE", "false"), - ("NODE", NODE_NAME), - ("APPLICATION", APPLICATION_NAME), - ]) - ); + assert_eq!(text(&list.stdout), list_row(&id, "Ready")); let show = run(&manager, &["show", "Round trip"]); assert_eq!(text(&show.stderr), ""); assert_eq!(show.status.code(), Some(0)); assert_eq!( text(&show.stdout), - block(&[ - ("ID", &id), - ("NAME", "Round trip"), - ("STATE", "Ready"), - ("DESIRED_STATE", "Present"), - ("READINESS", "Ready"), - ("STALE", "false"), - ("NODE", NODE_NAME), - ("EXECUTION_TARGET", APPLICATION_TARGET_ID), - ("APPLICATION", APPLICATION_NAME), - ("SERVICES", "web: Running"), - ("ENDPOINT", &endpoint), - ("ROUTE", ""), - ("FAILURE", ""), - ("MESSAGE", ""), + shown(&[ + ("name", "Round trip"), + ("id", &id), + ("state", "Ready"), + ("desired", "Present"), + ("readiness", "Ready"), + ("node", NODE_NAME), + ("target", APPLICATION_TARGET_ID), + ("target id", APPLICATION_TARGET_ID), + ("application", APPLICATION_NAME), + ("service web", "Running"), + ("endpoint", &endpoint), ]) ); @@ -88,39 +75,29 @@ fn application_commands_drive_a_simulated_deployment_through_pause_resume_and_te // The manager accepts resuming a present deployment as a no-op rather than rejecting it. let resumed = run(&manager, &["resume", "Round trip"]); - assert_accepted(&resumed, &id, "Ready", "Present"); + assert_accepted(&resumed, "Resuming"); assert_eq!(desired_state(&manager, &id), Some(Present)); let paused = run(&manager, &["pause", "Round trip"]); - assert_accepted(&paused, &id, "Pausing", "Paused"); + assert_accepted(&paused, "Pausing"); assert_eq!(desired_state(&manager, &id), Some(Paused)); manager.wait_for(&id, "a current Paused state", |deployment| { is_current(deployment, ApplicationLifecycleState::Paused) }); let list = run(&manager, &["list"]); - assert_eq!( - text(&list.stdout), - block(&[ - ("ID", &id), - ("NAME", "Round trip"), - ("STATE", "Paused"), - ("STALE", "false"), - ("NODE", NODE_NAME), - ("APPLICATION", APPLICATION_NAME), - ]) - ); + assert_eq!(text(&list.stdout), list_row(&id, "Paused")); // Pausing again is accepted as well, and reports the settled state. let paused_again = run(&manager, &["pause", &id]); - assert_accepted(&paused_again, &id, "Paused", "Paused"); + assert_accepted(&paused_again, "Pausing"); let resumed = run(&manager, &["resume", &id]); - assert_accepted(&resumed, &id, "Starting", "Present"); + assert_accepted(&resumed, "Resuming"); assert_eq!(desired_state(&manager, &id), Some(Present)); manager.wait_for(&id, "a current Ready state after resume", is_ready); let removed = run(&manager, &["teardown", "--yes", "Round trip"]); - assert_accepted(&removed, &id, "Tearing down", "Teardown"); + assert_accepted(&removed, "Tearing down"); // The simulated runtime stops at once, so the manager may already have removed it here. assert!(matches!( desired_state(&manager, &id), @@ -130,7 +107,7 @@ fn application_commands_drive_a_simulated_deployment_through_pause_resume_and_te let list = run(&manager, &["list"]); assert_eq!(list.status.code(), Some(0)); - assert_eq!(text(&list.stdout), ""); + assert_eq!(text(&list.stdout), "No application deployments\n"); // A removed deployment is no longer listed, so the command stops before reaching the manager. let removed_again = run(&manager, &["teardown", "--yes", &id]); @@ -144,22 +121,11 @@ fn application_commands_drive_a_simulated_deployment_through_pause_resume_and_te ); } -/// Asserts a lifecycle command succeeded and printed the state the manager accepted. -fn assert_accepted(output: &Output, id: &str, state: &str, desired: &str) { +/// Asserts a lifecycle command succeeded and reported the progressive `verb` for the deployment. +fn assert_accepted(output: &Output, verb: &str) { assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); - assert_eq!( - text(&output.stdout), - block(&[ - ("ID", id), - ("NAME", "Round trip"), - ("STATE", state), - ("DESIRED_STATE", desired), - ]) - ); - assert_eq!( - text(&output.stderr), - "Notice: Run `dotc application list` to follow its progress.\n" - ); + assert_eq!(text(&output.stdout), format!("✔ {verb} Round trip\n")); + assert_eq!(text(&output.stderr), ""); } /// Whether the manager's view shows `lifecycle` from a current observation. @@ -187,13 +153,29 @@ fn desired_state( }) } -/// Renders `fields` as an application deployment record block. -fn block(fields: &[(&str, &str)]) -> String { - let mut block = "Application deployment\n".to_owned(); - for (key, value) in fields { - block.push_str(&format!("DOTCORE_APPLICATION_DEPLOYMENT_{key}={value}\n")); +/// The table `application list` prints for the one deployment of the test. +fn list_row(id: &str, state: &str) -> String { + let (name, id_width, state_width) = ("Round trip", id.len().max(2), state.len().max(5)); + let node_width = NODE_NAME.len().max(4); + format!( + " {:<10} {: String { + let width = facts + .iter() + .map(|(label, _)| label.len()) + .max() + .unwrap_or(0); + let mut text = "Application deployment Round trip\n".to_owned(); + for (label, value) in facts { + text.push_str(&format!(" {label:` against the manager without any terminal. diff --git a/backend/cli/tests/command_contract.rs b/backend/cli/tests/command_contract.rs index be0fa2a0..450728d0 100644 --- a/backend/cli/tests/command_contract.rs +++ b/backend/cli/tests/command_contract.rs @@ -28,7 +28,7 @@ use dotcore_site::{ use support::{ command::{detach_from_controlling_terminal, dotc, isolated_dotc}, - pty::{Session, Stdin, Step, run_in_pty}, + pty::{Session, Stdin, Step, attach_controlling_terminal, run_in_pty}, }; #[test] @@ -59,7 +59,6 @@ fn config_show_reports_explicit_xdg_and_home_paths_without_mutation() { "cacheDir": fixture.root.join("explicit-cache"), "modelArtifactCacheDir": fixture.root.join("explicit-cache/model-artifacts/v1"), "workloadCacheDir": fixture.root.join("explicit-cache/workload-cache/v2"), - "nodeHost": serde_json::Value::Null, }), ), ( @@ -71,11 +70,9 @@ fn config_show_reports_explicit_xdg_and_home_paths_without_mutation() { serde_json::json!({ "role": "manager", "siteDir": fixture.root.join("xdg-state/dotcore/site"), - "masterCatalogDir": serde_json::Value::Null, "cacheDir": fixture.root.join("xdg-cache/dotcore"), "modelArtifactCacheDir": fixture.root.join("xdg-cache/dotcore/model-artifacts/v1"), "workloadCacheDir": fixture.root.join("xdg-cache/dotcore/workload-cache/v2"), - "nodeHost": serde_json::Value::Null, }), ), ( @@ -83,11 +80,9 @@ fn config_show_reports_explicit_xdg_and_home_paths_without_mutation() { serde_json::json!({ "role": "manager", "siteDir": fixture.root.join("home/.local/state/dotcore/site"), - "masterCatalogDir": serde_json::Value::Null, "cacheDir": fixture.root.join("home/.cache/dotcore"), "modelArtifactCacheDir": fixture.root.join("home/.cache/dotcore/model-artifacts/v1"), "workloadCacheDir": fixture.root.join("home/.cache/dotcore/workload-cache/v2"), - "nodeHost": serde_json::Value::Null, }), ), ]; @@ -95,7 +90,7 @@ fn config_show_reports_explicit_xdg_and_home_paths_without_mutation() { for (environment, expected) in cases { let mut command = dotc(); command - .args(["config", "show", "--format", "json"]) + .args(["--yaml", "config", "show"]) .clear_test_environment(); for (name, value) in environment { command.env(name, value); @@ -103,11 +98,7 @@ fn config_show_reports_explicit_xdg_and_home_paths_without_mutation() { let output = command.output().expect("run config show"); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); assert!(output.stderr.is_empty()); - assert_eq!( - serde_json::from_slice::(&output.stdout) - .expect("configuration JSON"), - expected - ); + assert_eq!(support::yaml_documents(&text(&output.stdout)), [expected]); } assert_eq!( @@ -119,6 +110,35 @@ fn config_show_reports_explicit_xdg_and_home_paths_without_mutation() { ); } +#[test] +fn config_show_prints_labeled_values_for_a_person() { + let fixture = TemporarySite::new(); + + let output = dotc() + .args(["config", "show", "--site-dir"]) + .arg(fixture.site_path()) + .args(["--cache-dir"]) + .arg(fixture.root.join("cache")) + .clear_test_environment() + .env("HOME", fixture.root.join("home")) + .output() + .expect("run config show"); + + assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); + assert!(output.stderr.is_empty()); + let cache = fixture.root.join("cache"); + assert_eq!( + text(&output.stdout), + format!( + " role manager\n site folder {}\n cache folder {}\n model artifact cache folder {}\n workload cache folder {}\n node host 127.0.0.2\n", + fixture.site_path().display(), + cache.display(), + cache.join("model-artifacts/v1").display(), + cache.join("workload-cache/v2").display(), + ) + ); +} + #[test] fn config_show_reports_the_node_role_from_the_folder_contents() { let fixture = TemporarySite::empty(); @@ -136,19 +156,19 @@ fn config_show_reports_the_node_role_from_the_folder_contents() { std::fs::write(site.join(file), "").expect("create folder file"); } let output = dotc() - .args(["config", "show", "--format", "json"]) + .args(["--yaml", "config", "show"]) .clear_test_environment() .env("DOTCORE_SITE_DIR", &site) .env("HOME", fixture.root.join("home")) .output() .expect("run config show"); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); - let json = serde_json::from_slice::(&output.stdout) - .expect("configuration JSON"); - assert_eq!(json["role"], expected, "role of the {name} folder"); - assert_eq!( - json["nodeHost"], - serde_json::Value::Null, + let [document] = &support::yaml_documents(&text(&output.stdout))[..] else { + panic!("one configuration document"); + }; + assert_eq!(document["role"], expected, "role of the {name} folder"); + assert!( + document.get("nodeHost").is_none(), "node host of the {name} folder" ); } @@ -159,7 +179,7 @@ fn config_show_reports_the_node_host_a_manager_site_records() { let fixture = TemporarySite::new(); let output = dotc() - .args(["config", "show", "--format", "json", "--site-dir"]) + .args(["--yaml", "config", "show", "--site-dir"]) .arg(fixture.site_path()) .clear_test_environment() .env("HOME", fixture.root.join("home")) @@ -167,16 +187,17 @@ fn config_show_reports_the_node_host_a_manager_site_records() { .expect("run config show"); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); - let json = - serde_json::from_slice::(&output.stdout).expect("configuration JSON"); - assert_eq!(json["role"], "manager"); - assert_eq!(json["nodeHost"], "127.0.0.2"); + let [document] = &support::yaml_documents(&text(&output.stdout))[..] else { + panic!("one configuration document"); + }; + assert_eq!(document["role"], "manager"); + assert_eq!(document["nodeHost"], "127.0.0.2"); } #[test] fn config_show_rejects_invalid_xdg_inputs_with_actionable_diagnostics() { let output = dotc() - .args(["config", "show", "--format", "json"]) + .args(["--yaml", "config", "show"]) .clear_test_environment() .env("XDG_STATE_HOME", "relative-state") .env("XDG_CACHE_HOME", "/cache") @@ -203,7 +224,6 @@ fn config_show_applies_the_root_paths_before_or_after_the_command_and_over_the_e "cacheDir": root.join("k"), "modelArtifactCacheDir": root.join("k/model-artifacts/v1"), "workloadCacheDir": root.join("k/workload-cache/v2"), - "nodeHost": serde_json::Value::Null, }); let flags = [ ("--site-dir", root.join("s")), @@ -226,7 +246,7 @@ fn config_show_applies_the_root_paths_before_or_after_the_command_and_over_the_e command.arg(flag).arg(value); } } - command.args(["config", "show", "--format", "json"]); + command.args(["--yaml", "config", "show"]); if !before { for (flag, value) in &flags { command.arg(format!("{flag}={}", value.display())); @@ -235,19 +255,19 @@ fn config_show_applies_the_root_paths_before_or_after_the_command_and_over_the_e let output = command.output().expect("run config show"); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); assert!(output.stderr.is_empty()); - serde_json::from_slice::(&output.stdout).expect("configuration JSON") + support::yaml_documents(&text(&output.stdout)) }; - assert_eq!(run(true, false), expected); - assert_eq!(run(false, false), expected); + assert_eq!(run(true, false), std::slice::from_ref(&expected)); + assert_eq!(run(false, false), std::slice::from_ref(&expected)); assert_eq!( run(true, true), - expected, + std::slice::from_ref(&expected), "flags before the command beat the environment" ); assert_eq!( run(false, true), - expected, + [expected], "flags after the command beat the environment" ); } @@ -296,7 +316,7 @@ fn root_path_flags_and_variables_with_unusable_values_fail_with_the_absolute_pat for (flag, value, variable, message) in cases { let expected = format!("Invalid site path: {message}\n"); let by_flag = dotc() - .args(["config", "show", "--format", "json", flag, value]) + .args(["--yaml", "config", "show", flag, value]) .clear_test_environment() .env("HOME", "/home/user") .output() @@ -306,7 +326,7 @@ fn root_path_flags_and_variables_with_unusable_values_fail_with_the_absolute_pat assert_eq!(text(&by_flag.stderr), expected, "{flag} {value:?}"); let by_variable = dotc() - .args(["config", "show", "--format", "json"]) + .args(["--yaml", "config", "show"]) .clear_test_environment() .env("HOME", "/home/user") .env(variable, value) @@ -460,7 +480,9 @@ fn site_delete_without_a_site_dir_targets_the_default_site_directory() { assert_eq!( text(&output.stdout), format!( - "Site deleted\nDOTCORE_SITE_DIR={}\n", + "✔ Site deleted + directory {} +", default_site.display() ) ); @@ -974,7 +996,7 @@ fn site_reset_replaces_broken_retained_state_offline_and_repeats_exactly() { .expect("unknown retained state"); let expected = format!( - "Site reset\nDOTCORE_SITE_DIR={}\nDOTCORE_SITE_ID=reset-site\nDOTCORE_NODE_ID=reset-node\nDOTCORE_NODE_HOST=127.0.0.1\nDOTCORE_INFERENCE=simulated\nDOTCORE_APPLICATIONS=simulated\n", + "✔ Site reset\n directory {}\n site id reset-site\n node id reset-node\n node host 127.0.0.1\n inference simulated\n applications simulated\n", site_dir.display() ); let docker = FakeDockerDaemon::start(); @@ -1001,7 +1023,12 @@ fn site_reset_replaces_broken_retained_state_offline_and_repeats_exactly() { assert!(validation.stderr.is_empty()); assert_eq!( text(&validation.stdout), - format!("Site valid\nDOTCORE_SITE_DIR={}\n", site_dir.display()) + format!( + "✔ Site valid + directory {} +", + site_dir.display() + ) ); } docker.assert_empty_site_reset_requests(&["retained-site", "reset-site"]); @@ -1029,6 +1056,18 @@ fn site_reset_replaces_obsolete_manager_identity_and_invalidates_worker_trust() .output() .expect("reset obsolete site trust offline"); assert_eq!(reset.status.code(), Some(0), "{}", text(&reset.stderr)); + assert!( + text(&reset.stderr).contains( + "Notice: site trust was rotated; 1 previously joined node(s) can no longer connect and must join again\n" + ), + "{}", + text(&reset.stderr) + ); + assert!( + !text(&reset.stderr).contains("dotc node add"), + "{}", + text(&reset.stderr) + ); assert_generated_simulated_bundle(site_dir, "reset-site", "reset-node"); assert_ne!( std::fs::read(trust.join("site-ca.der")).unwrap(), @@ -1129,7 +1168,7 @@ fn site_reset_of_a_simulated_site_skips_unreachable_docker_with_a_notice() { assert_eq!( text(&output.stdout), format!( - "Site reset\nDOTCORE_SITE_DIR={}\nDOTCORE_SITE_ID=reset-site\nDOTCORE_NODE_ID=reset-node\nDOTCORE_NODE_HOST=127.0.0.1\nDOTCORE_INFERENCE=simulated\nDOTCORE_APPLICATIONS=simulated\n", + "✔ Site reset\n directory {}\n site id reset-site\n node id reset-node\n node host 127.0.0.1\n inference simulated\n applications simulated\n", site_dir.display() ) ); @@ -1382,7 +1421,7 @@ fn site_init_replace_force_is_the_same_operation_as_site_reset() { assert_eq!( text(&output.stdout), format!( - "Site reset\nDOTCORE_SITE_DIR={}\nDOTCORE_SITE_ID=reset-site\nDOTCORE_NODE_ID=reset-node\nDOTCORE_NODE_HOST=127.0.0.1\nDOTCORE_INFERENCE=simulated\nDOTCORE_APPLICATIONS=simulated\n", + "✔ Site reset\n directory {}\n site id reset-site\n node id reset-node\n node host 127.0.0.1\n inference simulated\n applications simulated\n", site_dir.display() ) ); @@ -1519,7 +1558,7 @@ fn guided_presentation_uses_the_controlling_terminal_and_keeps_process_streams_e assert_eq!(run.stderr(), ""); let expected_stdout = if writes { format!( - "Site initialized\nDOTCORE_SITE_DIR={}\nDOTCORE_SITE_ID=site-test\nDOTCORE_NODE_ID=node-test\nDOTCORE_NODE_HOST=127.0.0.1\nDOTCORE_INFERENCE=simulated\nDOTCORE_APPLICATIONS=simulated\n", + "✔ Site initialized\n directory {}\n site id site-test\n node id node-test\n node host 127.0.0.1\n inference simulated\n applications simulated\n", site_dir.display() ) } else { @@ -1572,11 +1611,11 @@ fn rich_guided_golden_path_is_driven_by_arrow_keys_and_keeps_process_streams_exa assert_eq!(run.code(), Some(0), "screen:\n{}", run.screen()); assert_eq!(run.stderr(), ""); let stdout = run.stdout(); - let host = record(&stdout, "DOTCORE_NODE_HOST="); + let host = fact(&stdout, "node host"); assert_eq!( stdout, format!( - "Site initialized\nDOTCORE_SITE_DIR={}\nDOTCORE_SITE_ID=site-test\nDOTCORE_NODE_ID=node-test\nDOTCORE_NODE_HOST={host}\nDOTCORE_INFERENCE=simulated\nDOTCORE_APPLICATIONS=simulated\n", + "✔ Site initialized\n directory {}\n site id site-test\n node id node-test\n node host {host}\n inference simulated\n applications simulated\n", site_dir.display() ) ); @@ -1640,7 +1679,7 @@ fn rich_guided_cancel_exits_130_without_output_or_site() { ), ( "Esc at the inference selector", - &["--host", "127.0.0.1", "--display-name", "Test node"], + &["--host", "127.0.0.1", "--name", "Test node"], vec![Step::Wait("? Inference"), Step::Send(KEY_ESC)], ), ( @@ -1648,7 +1687,7 @@ fn rich_guided_cancel_exits_130_without_output_or_site() { &[ "--host", "127.0.0.1", - "--display-name", + "--name", "Test node", "--inference", "simulated", @@ -1660,7 +1699,7 @@ fn rich_guided_cancel_exits_130_without_output_or_site() { &[ "--host", "127.0.0.1", - "--display-name", + "--name", "Test node", "--inference", "simulated", @@ -1709,7 +1748,7 @@ fn rich_guided_another_address_is_entered_by_keystrokes_after_a_rejected_wildcar let command = rich_guided_init( &site_dir, &[ - "--display-name", + "--name", "Test node", "--inference", "simulated", @@ -1724,7 +1763,7 @@ fn rich_guided_another_address_is_entered_by_keystrokes_after_a_rejected_wildcar assert_eq!(run.code(), Some(0), "screen:\n{}", run.screen()); assert_eq!(run.stderr(), ""); - assert!(run.stdout().starts_with("Site initialized\n")); + assert!(run.stdout().starts_with("✔ Site initialized\n")); let site = std::fs::read_to_string(site_dir.join("site.yaml")).expect("Site input"); assert!(site.contains("host: 192.0.2.44\n"), "{site}"); } @@ -1739,7 +1778,7 @@ fn rich_guided_colors_follow_no_color_and_reach_only_the_terminal() { &[ "--host", "127.0.0.1", - "--display-name", + "--name", "Test node", "--inference", "simulated", @@ -1764,7 +1803,7 @@ fn rich_guided_colors_follow_no_color_and_reach_only_the_terminal() { assert_eq!( run.stdout(), format!( - "Site initialized\nDOTCORE_SITE_DIR={}\nDOTCORE_SITE_ID=site-test\nDOTCORE_NODE_ID=node-test\nDOTCORE_NODE_HOST=127.0.0.1\nDOTCORE_INFERENCE=simulated\nDOTCORE_APPLICATIONS=simulated\n", + "✔ Site initialized\n directory {}\n site id site-test\n node id node-test\n node host 127.0.0.1\n inference simulated\n applications simulated\n", site_dir.display() ), "NO_COLOR set: {no_color}" @@ -1786,7 +1825,7 @@ fn rich_guided_leaves_the_terminal_restored_and_inline() { let all_flags = [ "--host", "127.0.0.1", - "--display-name", + "--name", "Test node", "--inference", "simulated", @@ -1830,7 +1869,7 @@ fn rich_guided_falls_back_to_line_prompts_when_the_terminal_never_answers_the_cu let command = rich_guided_init( &site_dir, &[ - "--display-name", + "--name", "Test node", "--inference", "simulated", @@ -1849,11 +1888,11 @@ fn rich_guided_falls_back_to_line_prompts_when_the_terminal_never_answers_the_cu assert_eq!(run.code(), Some(0), "session:\n{}", run.session()); assert_eq!(run.stderr(), ""); let stdout = run.stdout(); - let host = record(&stdout, "DOTCORE_NODE_HOST="); + let host = fact(&stdout, "node host"); assert_eq!( stdout, format!( - "Site initialized\nDOTCORE_SITE_DIR={}\nDOTCORE_SITE_ID=site-test\nDOTCORE_NODE_ID=node-test\nDOTCORE_NODE_HOST={host}\nDOTCORE_INFERENCE=simulated\nDOTCORE_APPLICATIONS=simulated\n", + "✔ Site initialized\n directory {}\n site id site-test\n node id node-test\n node host {host}\n inference simulated\n applications simulated\n", site_dir.display() ) ); @@ -1948,7 +1987,7 @@ fn site_init_noninteractive_uses_the_home_fallback() { assert_eq!(text(&output.stderr), LOOPBACK_FLAG_STDERR); assert!(site_dir.join("site.yaml").is_file()); assert!(site_dir.join("node.yaml").is_file()); - assert!(text(&output.stdout).contains(&format!("DOTCORE_SITE_DIR={}\n", site_dir.display()))); + assert!(text(&output.stdout).contains(&format!(" directory {}\n", site_dir.display()))); } #[test] @@ -1964,14 +2003,14 @@ fn site_init_simulated_creates_a_complete_bundle_with_exact_output_and_defaults( assert_eq!(output.status.code(), Some(0)); assert_eq!(text(&output.stderr), LOOPBACK_FLAG_STDERR); let stdout = text(&output.stdout); - let site_id = record(&stdout, "DOTCORE_SITE_ID="); - let node_id = record(&stdout, "DOTCORE_NODE_ID="); + let site_id = fact(&stdout, "site id"); + let node_id = fact(&stdout, "node id"); assert!(site_id.starts_with("site-")); assert!(node_id.starts_with("node-")); assert_eq!( stdout, format!( - "Site initialized\nDOTCORE_SITE_DIR={}\nDOTCORE_SITE_ID={site_id}\nDOTCORE_NODE_ID={node_id}\nDOTCORE_NODE_HOST=127.0.0.1\nDOTCORE_INFERENCE=simulated\nDOTCORE_APPLICATIONS=simulated\n", + "✔ Site initialized\n directory {}\n site id {site_id}\n node id {node_id}\n node host 127.0.0.1\n inference simulated\n applications simulated\n", site_dir.display() ) ); @@ -1995,7 +2034,7 @@ fn site_init_flag_overrides_site_directory_environment() { assert!(flag_site.join("site.yaml").is_file()); assert!(flag_site.join("node.yaml").is_file()); assert!(!environment_site.exists()); - assert!(text(&output.stdout).contains(&format!("DOTCORE_SITE_DIR={}\n", flag_site.display()))); + assert!(text(&output.stdout).contains(&format!(" directory {}\n", flag_site.display()))); } #[test] @@ -2016,7 +2055,9 @@ fn site_validate_flags_override_both_environment_path_sources() { assert_eq!( text(&output.stdout), format!( - "Site valid\nDOTCORE_SITE_DIR={}\n", + "✔ Site valid + directory {} +", fixture.site_path().display() ) ); @@ -2041,11 +2082,11 @@ fn site_init_matching_rerun_preserves_generated_files_byte_for_byte() { assert_eq!(text(&second.stderr), LOOPBACK_FLAG_STDERR); let first_stdout = text(&first.stdout); let second_stdout = text(&second.stdout); - let site_id = record(&first_stdout, "DOTCORE_SITE_ID="); - let node_id = record(&first_stdout, "DOTCORE_NODE_ID="); - assert_eq!(record(&second_stdout, "DOTCORE_SITE_ID="), site_id); - assert_eq!(record(&second_stdout, "DOTCORE_NODE_ID="), node_id); - assert!(second_stdout.starts_with("Site already initialized\n")); + let site_id = fact(&first_stdout, "site id"); + let node_id = fact(&first_stdout, "node id"); + assert_eq!(fact(&second_stdout, "site id"), site_id); + assert_eq!(fact(&second_stdout, "node id"), node_id); + assert!(second_stdout.starts_with("✔ Site already initialized\n")); assert_eq!( std::fs::read(site_dir.join("site.yaml")).expect("Site input"), site_before @@ -2067,7 +2108,7 @@ fn site_init_records_a_host_name_as_the_site_node_host() { .expect("run simulated init with a host name"); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); - assert!(text(&output.stdout).starts_with("Site initialized\n")); + assert!(text(&output.stdout).starts_with("✔ Site initialized\n")); let site = std::fs::read_to_string(site_dir.join("site.yaml")).expect("Site input"); assert!(site.contains("host: manager.example.ts.net\n"), "{site}"); } @@ -2421,20 +2462,18 @@ fn node_add_and_join_run_non_interactively_and_install_a_node_folder() { loopback_peer_address_toward(std::net::Ipv4Addr::new(127, 0, 0, 2)), ) ); - let node_id = record(&text(&added.stdout), "DOTCORE_NODE_ID="); - assert!(node_id.starts_with("node-"), "{node_id}"); + let node_id = WORKER_NODE_ID; assert_eq!( text(&added.stdout), format!( - "Node join ready\nDOTCORE_JOIN_COMMAND=dotc node join --token-file {}\nNode added\nDOTCORE_NODE_ID={node_id}\nDOTCORE_NODE_NAME=Worker two\nDOTCORE_NODE_HOST=127.0.0.3\n", + "On the new machine, run:\n dotc node join --token-file {}\n✔ Added Worker two at 127.0.0.3\n", token_file.display(), ) ); assert_eq!( text(&joined.stdout), format!( - "Node joined\nDOTCORE_SITE_ID=cli-test-site\nDOTCORE_NODE_ID={node_id}\nDOTCORE_NODE_NAME=Worker two\nDOTCORE_NODE_HOST=127.0.0.3\nDOTCORE_PRIVATE_ADDR=127.0.0.3:{}\nDOTCORE_START_COMMAND=dotcore --site-dir {}\n", - node_private_port(), + "✔ Joined cli-test-site as Worker two at 127.0.0.3\nStart the node with:\n dotcore --site-dir {}\n", node_dir.display() ) ); @@ -2582,17 +2621,16 @@ fn node_add_prints_a_join_command_that_joins_when_run_on_the_new_machine() { .stderr(Stdio::piped()); let mut child = command.spawn().expect("spawn node add"); let mut stdout = BufReader::new(child.stdout.take().expect("stdout")); - let mut records = String::new(); - while !records.contains("DOTCORE_JOIN_COMMAND=") { + let mut printed = String::new(); + while !printed.starts_with("dotc node join") { let mut line = String::new(); assert_ne!( - stdout.read_line(&mut line).expect("read record"), + stdout.read_line(&mut line).expect("read output"), 0, - "{records}" + "{printed}" ); - records.push_str(&line); + printed = line.trim().to_owned(); } - let printed = record(&records, "DOTCORE_JOIN_COMMAND="); // Running the printed command on the new machine: its flags are passed as printed, and the // operator adds the flags that suit the machine. @@ -2865,11 +2903,142 @@ fn node_add_ending_early_cancels_the_join() { const WORKER_NODE_ID: &str = "node-7b836d678d251736"; const WORKER_APPLICATION_TARGET: &str = "application-execution-target-7182af3d809190c5-simulated"; +#[test] +fn plural_nouns_and_ls_are_aliases_that_group_help_hides() { + for arguments in [ + &["nodes", "ls", "--help"][..], + &["node", "ls", "--help"], + &["models", "ls", "--help"], + &["applications", "ls", "--help"], + &["app", "ls", "--help"], + &["sites", "validate", "--help"], + ] { + let output = dotc() + .args(arguments) + .clear_test_environment() + .output() + .expect("alias help"); + assert_eq!(output.status.code(), Some(0), "{arguments:?}"); + let usage = text(&output.stdout); + let canonical = match arguments[0] { + "nodes" | "node" => "node", + "models" => "model", + "sites" => "site", + _ => "application", + }; + assert!( + usage.contains(&format!("Usage: dotc {canonical} ")), + "{arguments:?}\n{usage}" + ); + } + + let root = text( + &dotc() + .arg("--help") + .clear_test_environment() + .output() + .expect("root help") + .stdout, + ); + for plural in ["nodes", "models", "applications", "sites"] { + assert!( + !root + .lines() + .any(|line| line.trim_start().starts_with(&format!("{plural} "))), + "{root}" + ); + } + assert!(root.contains("application Inspect and control the application deployments of the running site [alias: app]"), "{root}"); +} + +#[test] +fn site_init_and_reset_name_the_node_with_name_and_reject_display_name() { + for action in ["init", "reset"] { + let help = dotc() + .args(["site", action, "--help"]) + .clear_test_environment() + .output() + .expect("site help"); + let help = text(&help.stdout); + assert!(help.contains("--name "), "{help}"); + assert!(!help.contains("--display-name"), "{help}"); + + let rejected = dotc() + .args(["site", action, "--display-name", "Test node"]) + .clear_test_environment() + .output() + .expect("rejected flag"); + assert_eq!(rejected.status.code(), Some(2), "{action}"); + assert!( + text(&rejected.stderr).contains("unexpected argument '--display-name'"), + "{}", + text(&rejected.stderr) + ); + } +} + +#[test] +fn logs_help_names_the_deployment_kind_and_every_manager_flag_comes_last() { + for (kind, noun) in [("model", "model"), ("application", "application")] { + let help = text( + &dotc() + .args([kind, "logs", "-h"]) + .clear_test_environment() + .output() + .expect("logs help") + .stdout, + ); + assert!( + help.contains(&format!( + " Name or ID of the {noun} deployment\n" + )), + "{help}" + ); + } + + for arguments in [ + &["node", "add"][..], + &["node", "remove"], + &["model", "list"], + &["model", "show"], + &["model", "pause"], + &["model", "resume"], + &["model", "teardown"], + &["model", "logs"], + &["application", "list"], + &["application", "show"], + &["application", "pause"], + &["application", "resume"], + &["application", "teardown"], + &["application", "logs"], + ] { + let help = text( + &dotc() + .args(arguments) + .arg("-h") + .clear_test_environment() + .output() + .expect("help") + .stdout, + ); + let options: Vec<&str> = help + .lines() + .skip_while(|line| *line != "Options:") + .skip(1) + .collect(); + let manager = options.last().expect("options"); + assert!( + manager.trim_start().starts_with("--manager
"), + "{arguments:?}\n{help}" + ); + } +} + #[test] fn node_remove_leave_and_list_help_describe_their_arguments() { let help = |action: &str| { let output = dotc() - .args(["node", action, "--help"]) + .args(["node", action, "-h"]) .clear_test_environment() .output() .expect("help"); @@ -2880,15 +3049,15 @@ fn node_remove_leave_and_list_help_describe_their_arguments() { assert_eq!( help("remove"), - "Remove a worker node from the site, through the running manager or from this stopped site. Run `dotc node leave` on the removed machine afterwards\n\nUsage: dotc node remove [OPTIONS] \n\nArguments:\n Display name or node id of the worker node to remove\n\nOptions:\n --manager
Management address of the running site manager, as host:port or http://host:port [env: DOTCORE_MANAGEMENT_ADDR=] [default: 127.0.0.1:50051]\n --verbose Show the complete cause chain of a failure on a terminal\n --forget-deployments Drop the declarations of deployments placed on the node, and the routes only they serve, without cleanup evidence from the node. Without it, a node with deployments is refused. A running site accepts it only while the node is not connected\n --site-dir Absolute site or node folder; defaults to $XDG_STATE_HOME/dotcore/site, else ~/.local/state/dotcore/site [env: DOTCORE_SITE_DIR]\n --catalog-dir Absolute master catalog folder [env: DOTCORE_CATALOG_DIR]\n --yes Remove the node without asking for confirmation\n --cache-dir Absolute root of the recreatable caches; defaults to $XDG_CACHE_HOME/dotcore, else ~/.cache/dotcore [env: DOTCORE_CACHE_DIR]\n -h, --help Print help\n" + "Remove a worker node from the site\n\nUsage: dotc node remove [OPTIONS] \n\nArguments:\n Display name or node id of the worker node to remove\n\nOptions:\n --forget-deployments Drop the declarations of deployments placed on the node, and the routes only they serve, without cleanup evidence from the node. Without it, a node with deployments is refused. A running site accepts it only while the node is not connected\n --verbose Show the complete cause chain of a failure on a terminal\n --yaml Print the result as YAML on stdout, for scripts and agents; the command never asks a question\n --yes Remove the node without asking for confirmation\n --site-dir Absolute site or node folder; defaults to $XDG_STATE_HOME/dotcore/site, else ~/.local/state/dotcore/site [env: DOTCORE_SITE_DIR]\n --catalog-dir Absolute master catalog folder [env: DOTCORE_CATALOG_DIR]\n --cache-dir Absolute root of the recreatable caches; defaults to $XDG_CACHE_HOME/dotcore, else ~/.cache/dotcore [env: DOTCORE_CACHE_DIR]\n -h, --help Print help (see more with '--help')\n --manager
Management address of the running site manager, as host:port or http://host:port [env: DOTCORE_MANAGEMENT_ADDR=] [default: 127.0.0.1:50051]\n" ); assert_eq!( help("leave"), - "Stop this node's workloads and delete its node folder; runs on the removed machine with its server stopped\n\nUsage: dotc node leave [OPTIONS]\n\nOptions:\n --verbose Show the complete cause chain of a failure on a terminal\n --yes Stop the node's workloads and delete its folder without asking for confirmation\n --site-dir Absolute site or node folder; defaults to $XDG_STATE_HOME/dotcore/site, else ~/.local/state/dotcore/site [env: DOTCORE_SITE_DIR]\n --catalog-dir Absolute master catalog folder [env: DOTCORE_CATALOG_DIR]\n --cache-dir Absolute root of the recreatable caches; defaults to $XDG_CACHE_HOME/dotcore, else ~/.cache/dotcore [env: DOTCORE_CACHE_DIR]\n -h, --help Print help\n" + "Leave the site: stop this node's workloads and delete its node folder\n\nUsage: dotc node leave [OPTIONS]\n\nOptions:\n --verbose Show the complete cause chain of a failure on a terminal\n --yes Stop the node's workloads and delete its folder without asking for confirmation\n --yaml Print the result as YAML on stdout, for scripts and agents; the command never asks a question\n --site-dir Absolute site or node folder; defaults to $XDG_STATE_HOME/dotcore/site, else ~/.local/state/dotcore/site [env: DOTCORE_SITE_DIR]\n --catalog-dir Absolute master catalog folder [env: DOTCORE_CATALOG_DIR]\n --cache-dir Absolute root of the recreatable caches; defaults to $XDG_CACHE_HOME/dotcore, else ~/.cache/dotcore [env: DOTCORE_CACHE_DIR]\n -h, --help Print help (see more with '--help')\n" ); assert_eq!( help("list"), - "List the nodes of this site with their addresses and deployments; runs on the manager, which may be running\n\nUsage: dotc node list [OPTIONS]\n\nOptions:\n --details Also show the address each node uses to reach the manager and whether the manager trusts the node's certificate; terminal output only\n --verbose Show the complete cause chain of a failure on a terminal\n --execution-targets Also list each node's execution targets; terminal output only\n --site-dir Absolute site or node folder; defaults to $XDG_STATE_HOME/dotcore/site, else ~/.local/state/dotcore/site [env: DOTCORE_SITE_DIR]\n --catalog-dir Absolute master catalog folder [env: DOTCORE_CATALOG_DIR]\n --cache-dir Absolute root of the recreatable caches; defaults to $XDG_CACHE_HOME/dotcore, else ~/.cache/dotcore [env: DOTCORE_CACHE_DIR]\n -h, --help Print help\n" + "List the site's nodes with their addresses and deployments\n\nUsage: dotc node list [OPTIONS]\n\nOptions:\n --details Also show the address each node uses to reach the manager and whether the manager trusts the node's certificate\n --verbose Show the complete cause chain of a failure on a terminal\n --execution-targets Also list each node's execution targets\n --yaml Print the result as YAML on stdout, for scripts and agents; the command never asks a question\n --site-dir Absolute site or node folder; defaults to $XDG_STATE_HOME/dotcore/site, else ~/.local/state/dotcore/site [env: DOTCORE_SITE_DIR]\n --catalog-dir Absolute master catalog folder [env: DOTCORE_CATALOG_DIR]\n --cache-dir Absolute root of the recreatable caches; defaults to $XDG_CACHE_HOME/dotcore, else ~/.cache/dotcore [env: DOTCORE_CACHE_DIR]\n -h, --help Print help (see more with '--help')\n" ); } @@ -2964,20 +3133,20 @@ fn node_remove_yes_drops_the_node_its_targets_and_its_pin_and_prints_the_records .expect("run node remove"); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); - assert_eq!( - text(&output.stdout), - format!("Node removed\nDOTCORE_NODE_ID={WORKER_NODE_ID}\nDOTCORE_NODE_NAME=Worker two\n") - ); + assert_eq!(text(&output.stdout), "✔ Removed Worker two\n"); assert_eq!( text(&output.stderr), - "Notice: Stop the removed node's server, then run `dotc node leave` on that machine to stop its workloads and delete its node folder.\n" + "Notice: The removed machine keeps its workloads and node folder\n" ); assert_eq!(pin_files(fixture.site_path()), Vec::::new()); let site = std::fs::read_to_string(fixture.site_path().join("site.yaml")).expect("Site"); assert!(!site.contains(WORKER_NODE_ID), "{site}"); assert!(!site.contains("Worker two"), "{site}"); assert_eq!(site.matches("executionTargetId:").count(), 2, "{site}"); - assert_eq!(node_list_stdout(fixture.site_path()), MANAGER_LIST_BLOCK); + assert_eq!( + node_list_stdout(fixture.site_path()), + expected_node_list(None) + ); } #[test] @@ -3025,12 +3194,7 @@ fn node_remove_refuses_placed_deployments_unless_they_are_forgotten() { "{}", text(&forgotten.stderr) ); - assert_eq!( - text(&forgotten.stdout), - format!( - "Node removed\nDOTCORE_NODE_ID={WORKER_NODE_ID}\nDOTCORE_NODE_NAME=Worker two\nDOTCORE_FORGOTTEN_DEPLOYMENT=worker-app\n" - ) - ); + assert_eq!(text(&forgotten.stdout), "✔ Removed Worker two\n"); let site = std::fs::read_to_string(fixture.site_path().join("site.yaml")).expect("Site"); assert!(!site.contains("worker-app"), "{site}"); assert_eq!(pin_files(fixture.site_path()), Vec::::new()); @@ -3057,7 +3221,7 @@ fn node_remove_of_an_already_removed_node_id_succeeds_and_an_unknown_name_fails( assert_eq!(retry.status.code(), Some(0), "{}", text(&retry.stderr)); assert_eq!( text(&retry.stdout), - format!("Node already removed\nDOTCORE_NODE_ID={WORKER_NODE_ID}\n") + format!("✔ {WORKER_NODE_ID} is already removed from the site\n") ); let by_name = node_remove_command(fixture.site_path(), "Worker two") @@ -3107,9 +3271,10 @@ fn node_remove_goes_through_the_running_manager_and_reports_its_outcomes() { // A worker without deployments is previewed, then removed. let removed = remove("Worker two", false); assert_eq!(removed.status.code(), Some(0), "{}", text(&removed.stderr)); + assert_eq!(text(&removed.stdout), "✔ Removed Worker two\n"); assert_eq!( - text(&removed.stdout), - "Node removed\nDOTCORE_NODE_ID=node-00000000000000bb\nDOTCORE_NODE_NAME=Worker two\n" + text(&removed.stderr), + "Notice: The removed machine stops Dotcore by itself; its workloads and node folder remain\n" ); assert_eq!( fake.calls() @@ -3139,7 +3304,7 @@ fn node_remove_goes_through_the_running_manager_and_reports_its_outcomes() { assert_eq!(retry.status.code(), Some(0), "{}", text(&retry.stderr)); assert_eq!( text(&retry.stdout), - "Node already removed\nDOTCORE_NODE_ID=node-00000000000000bb\n" + "✔ node-00000000000000bb is already removed from the site\n" ); // Placed deployments refuse it, and a connected worker can't forget them. @@ -3186,10 +3351,7 @@ fn a_removed_node_leaves_and_joins_again_with_the_same_name_host_and_node_id() { .output() .expect("leave"); assert_eq!(left.status.code(), Some(0), "{}", text(&left.stderr)); - assert_eq!( - text(&left.stdout), - format!("Node left\nDOTCORE_SITE_ID=cli-test-site\nDOTCORE_NODE_ID={WORKER_NODE_ID}\n") - ); + assert_eq!(text(&left.stdout), "✔ Left cli-test-site\n"); assert_eq!( text(&left.stderr), "Notice: skipped Docker runtime cleanup because it is unreachable; the site does not bind it, so only resources left by an earlier configuration could remain: connect to local Docker daemon for site cleanup: Docker Engine API request failed: Socket not found: /nonexistent/docker.sock: Socket not found: /nonexistent/docker.sock\n" @@ -3210,7 +3372,7 @@ fn a_removed_node_leaves_and_joins_again_with_the_same_name_host_and_node_id() { ); assert_eq!( node_list_stdout(fixture.site_path()), - format!("{MANAGER_LIST_BLOCK}\n{}", worker_list_block()) + expected_node_list(Some(("127.0.0.3", 0))) ); } @@ -3287,8 +3449,7 @@ fn a_node_joins_again_from_its_intact_folder_on_a_new_host() { assert_eq!( text(&joined.stdout), format!( - "Node rejoined\nDOTCORE_SITE_ID=cli-test-site\nDOTCORE_NODE_ID={WORKER_NODE_ID}\nDOTCORE_NODE_NAME=Worker two\nDOTCORE_NODE_HOST=127.0.0.4\nDOTCORE_PRIVATE_ADDR=127.0.0.4:{}\nDOTCORE_START_COMMAND=dotcore --site-dir {}\n", - node_private_port(), + "✔ Rejoined Worker two at 127.0.0.4\nStart the node with:\n dotcore --site-dir {}\n", node_dir.display() ) ); @@ -3296,7 +3457,7 @@ fn a_node_joins_again_from_its_intact_folder_on_a_new_host() { assert_eq!( text(&added.stdout), format!( - "Node join ready\nDOTCORE_JOIN_COMMAND=dotc node join --token-file {}\nNode rejoined\nDOTCORE_NODE_ID={WORKER_NODE_ID}\nDOTCORE_NODE_NAME=Worker two\nDOTCORE_NODE_HOST=127.0.0.4\n", + "On the new machine, run:\n dotc node join --token-file {}\n✔ Rejoined Worker two at 127.0.0.4\n", node_dir.with_extension("rejoin.token").display() ) ); @@ -3316,10 +3477,7 @@ fn a_node_joins_again_from_its_intact_folder_on_a_new_host() { assert_eq!(after.trust_anchor, before.trust_anchor); assert_eq!( node_list_stdout(fixture.site_path()), - format!( - "{MANAGER_LIST_BLOCK}\n{}", - worker_list_block().replace("127.0.0.3", "127.0.0.4") - ) + expected_node_list(Some(("127.0.0.4", 0))) ); } @@ -3363,7 +3521,7 @@ fn a_rejoin_without_a_host_keeps_the_declared_host() { JoinedState::read(fixture.site_path(), &node_dir).site, before.site ); - assert!(text(&joined.stdout).contains("DOTCORE_NODE_HOST=127.0.0.3\n")); + assert!(text(&joined.stdout).contains("at 127.0.0.3\n")); } #[test] @@ -3812,22 +3970,19 @@ fn site_delete_refuses_a_node_folder_held_by_a_running_node() { } #[test] -fn node_list_prints_one_record_block_per_node_with_and_without_the_site_lock() { +fn node_list_prints_a_table_row_per_node_with_and_without_the_site_lock() { let fixture = TemporarySite::new(); let nodes = TemporarySite::empty(); let node_dir = nodes.root.join("worker"); - assert_eq!(node_list_stdout(fixture.site_path()), MANAGER_LIST_BLOCK); + assert_eq!( + node_list_stdout(fixture.site_path()), + expected_node_list(None) + ); join_node(fixture.site_path(), &node_dir, "Worker two", "127.0.0.3"); place_worker_application(fixture.site_path(), "worker-app"); - let expected = format!( - "{MANAGER_LIST_BLOCK}\n{}", - worker_list_block().replace( - "DOTCORE_NODE_APPLICATION_DEPLOYMENTS=0", - "DOTCORE_NODE_APPLICATION_DEPLOYMENTS=1" - ) - ); + let expected = expected_node_list(Some(("127.0.0.3", 1))); assert_eq!(node_list_stdout(fixture.site_path()), expected); // A running manager holds the site lock exclusively; listing does not need it. @@ -3854,6 +4009,431 @@ fn node_list_prints_one_record_block_per_node_with_and_without_the_site_lock() { ); } +#[test] +fn yaml_node_add_and_join_print_progress_on_stderr_and_one_document_on_stdout() { + let fixture = TemporarySite::new(); + let nodes = TemporarySite::empty(); + let node_dir = nodes.root.join("worker"); + let token_file = nodes.root.join("worker.token"); + let manager = LiveManager::start(fixture.site_path()); + let mut add_command = node_add_command(&manager, Some(&token_file)); + add_command + .args(["--yes", "--yaml"]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let add = NodeAdd::start_command(add_command, &token_file); + + let joined = node_join(&token_file, &node_dir, "Worker two", "127.0.0.3") + .arg("--yaml") + .output() + .expect("run node join"); + let added = add.finish(); + + assert_eq!(joined.status.code(), Some(0), "{}", text(&joined.stderr)); + assert_eq!( + text(&joined.stderr), + "Connected to site cli-test-site\nWaiting for approval on the manager...\n" + ); + assert_eq!( + support::yaml_documents(&text(&joined.stdout)), + [serde_json::json!({ + "outcome": "joined", + "siteId": "cli-test-site", + "nodeId": WORKER_NODE_ID, + "displayName": "Worker two", + "host": "127.0.0.3", + "privateAddress": format!("127.0.0.3:{}", node_private_port()), + "startCommand": format!("dotcore --site-dir {}", node_dir.display()), + })] + ); + assert_eq!(added.status.code(), Some(0), "{}", text(&added.stderr)); + assert_eq!( + text(&added.stderr), + format!( + "Warning: the manager host 127.0.0.2 is a loopback address, which only this machine reaches; a remote node must join with --manager-host
, and the manager must listen on that address\nOn the new machine, run: dotc node join --token-file {}\nWaiting for the node...\nWarning: the node proposes host 127.0.0.3 but connected from 127.0.0.1; confirm that other nodes reach it at the proposed host\n", + token_file.display() + ) + ); + assert_eq!( + support::yaml_documents(&text(&added.stdout)), + [serde_json::json!({ + "outcome": "added", + "nodeId": WORKER_NODE_ID, + "displayName": "Worker two", + "host": "127.0.0.3", + })] + ); + + // The same node joins again from its folder on a new host. + let rejoin_token = nodes.root.join("rejoin.token"); + let mut rejoin_add = node_add_command(&manager, Some(&rejoin_token)); + rejoin_add + .args(["--yes", "--yaml"]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let rejoin_add = NodeAdd::start_command(rejoin_add, &rejoin_token); + let rejoined = rejoin_command(&rejoin_token, &node_dir, &["--host", "127.0.0.4", "--yaml"]) + .output() + .expect("run node join again"); + let readded = rejoin_add.finish(); + manager.stop(); + + assert_eq!( + rejoined.status.code(), + Some(0), + "{}", + text(&rejoined.stderr) + ); + assert_eq!( + support::yaml_documents(&text(&rejoined.stdout)), + [serde_json::json!({ + "outcome": "rejoined", + "siteId": "cli-test-site", + "nodeId": WORKER_NODE_ID, + "displayName": "Worker two", + "host": "127.0.0.4", + "privateAddress": format!("127.0.0.4:{}", node_private_port()), + "startCommand": format!("dotcore --site-dir {}", node_dir.display()), + })] + ); + assert_eq!( + support::yaml_documents(&text(&readded.stdout)), + [serde_json::json!({ + "outcome": "rejoined", + "nodeId": WORKER_NODE_ID, + "displayName": "Worker two", + "host": "127.0.0.4", + })] + ); +} + +#[test] +fn yaml_node_list_prints_every_node_with_its_facts() { + let fixture = TemporarySite::new(); + let nodes = TemporarySite::empty(); + join_node( + fixture.site_path(), + &nodes.root.join("worker"), + "Worker two", + "127.0.0.3", + ); + place_worker_application(fixture.site_path(), "worker-app"); + let platform = match std::env::consts::ARCH { + "aarch64" => "linux/arm64", + _ => "linux/amd64", + }; + + let output = node_list_command(fixture.site_path()) + .arg("--yaml") + .output() + .expect("run node list"); + + assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); + assert_eq!(text(&output.stderr), ""); + assert_eq!( + support::yaml_documents(&text(&output.stdout)), + [serde_json::json!({ + "siteId": "cli-test-site", + "nodes": [ + { + "node": { + "nodeId": "cli-test-node", + "displayName": "CLI test node", + "host": "127.0.0.2", + "siteManager": {}, + }, + "isManager": true, + "pinned": false, + "executionTargets": [ + { + "id": "cli-test-target", + "displayName": "cli-test-target", + "kind": "model", + "platform": "linux/amd64", + }, + { + "id": "cli-test-application-target", + "displayName": "cli-test-application-target", + "kind": "application", + "platform": "linux/amd64", + }, + ], + "placedModels": 0, + "placedApplications": 0, + }, + { + "node": { + "nodeId": WORKER_NODE_ID, + "displayName": "Worker two", + "host": "127.0.0.3", + }, + "isManager": false, + "pinned": true, + "executionTargets": [ + { + "id": "execution-target-7182af3d809190c5-simulated-4d747ac0", + "displayName": "Simulated NVIDIA GeForce RTX 5090", + "kind": "model", + "platform": platform, + }, + { + "id": WORKER_APPLICATION_TARGET, + "displayName": "Simulated applications", + "kind": "application", + "platform": platform, + }, + ], + "placedModels": 0, + "placedApplications": 1, + }, + ], + })] + ); +} + +#[test] +fn yaml_node_remove_prints_the_removal_response_of_a_stopped_and_a_running_site() { + let fixture = TemporarySite::new(); + let nodes = TemporarySite::empty(); + let removed_response = |forgotten: serde_json::Value| { + let mut plan = serde_json::json!({ + "nodeId": WORKER_NODE_ID, + "displayName": "Worker two", + "executionTargetIds": [ + "execution-target-7182af3d809190c5-simulated-4d747ac0", + WORKER_APPLICATION_TARGET, + ], + }); + if !forgotten.is_null() { + plan["forgottenDeployments"] = forgotten; + } + serde_json::json!({ "removed": plan }) + }; + + // A stopped site removes the node itself, with the deployments it was told to forget. + join_node( + fixture.site_path(), + &nodes.root.join("worker"), + "Worker two", + "127.0.0.3", + ); + place_worker_application(fixture.site_path(), "worker-app"); + let stopped = node_remove_command(fixture.site_path(), "Worker two") + .args(["--yaml", "--forget-deployments"]) + .output() + .expect("run node remove on a stopped site"); + assert_eq!(stopped.status.code(), Some(0), "{}", text(&stopped.stderr)); + assert_eq!( + text(&stopped.stderr), + "Notice: The removed machine keeps its workloads and node folder\n" + ); + assert_eq!( + support::yaml_documents(&text(&stopped.stdout)), + [removed_response(serde_json::json!([{ + "kind": "MACHINE_REMOVAL_DEPLOYMENT_KIND_APPLICATION", + "deploymentId": "worker-app", + "name": "Worker app", + }]))] + ); + + // Removing it again is reported as already done. + let again = node_remove_command(fixture.site_path(), WORKER_NODE_ID) + .arg("--yaml") + .output() + .expect("run node remove again"); + assert_eq!(again.status.code(), Some(0), "{}", text(&again.stderr)); + assert_eq!( + support::yaml_documents(&text(&again.stdout)), + [serde_json::json!({ "alreadyRemoved": {} })] + ); + + // A running site's manager answers with the same response. + join_node( + fixture.site_path(), + &nodes.root.join("worker-again"), + "Worker two", + "127.0.0.3", + ); + let manager = LiveManager::start(fixture.site_path()); + let running = node_remove_command(fixture.site_path(), "Worker two") + .args(["--yaml", "--manager"]) + .arg(manager.management()) + .output() + .expect("run node remove on a running site"); + manager.stop(); + assert_eq!(running.status.code(), Some(0), "{}", text(&running.stderr)); + assert_eq!( + text(&running.stderr), + "Notice: The removed machine stops Dotcore by itself; its workloads and node folder remain\n" + ); + assert_eq!( + support::yaml_documents(&text(&running.stdout)), + [removed_response(serde_json::Value::Null)] + ); +} + +#[test] +fn yaml_node_leave_prints_the_site_and_node_that_left() { + let fixture = TemporarySite::new(); + let nodes = TemporarySite::empty(); + let node_dir = nodes.root.join("worker"); + join_node(fixture.site_path(), &node_dir, "Worker two", "127.0.0.3"); + + let output = node_leave_command(&node_dir) + .arg("--yaml") + .output() + .expect("run node leave"); + + assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); + assert_eq!(text(&output.stderr), ""); + assert_eq!( + support::yaml_documents(&text(&output.stdout)), + [serde_json::json!({ + "outcome": "left", + "siteId": "cli-test-site", + "nodeId": WORKER_NODE_ID, + })] + ); + assert!(!node_dir.exists()); +} + +#[test] +fn yaml_commands_that_would_ask_fail_naming_the_flag_that_answers_without_asking() { + let nodes = TemporarySite::empty(); + let site = nodes.root.join("site"); + let cases: [(&[&str], &str); 5] = [ + ( + &["node", "add", "--manager", "127.0.0.1:1"], + "allowing a node needs confirmation, which --yaml never asks for; pass --yes to allow the node that presents the token", + ), + ( + &["node", "join", "--token", "dcjoin1.bad"], + "joining asks for confirmation, which --yaml never gives; pass --yes", + ), + ( + &["node", "remove", "Worker two"], + "removing a node needs confirmation, which --yaml never asks for; pass --yes to remove it", + ), + ( + &["node", "leave"], + "leaving the site needs confirmation, which --yaml never asks for; pass --yes to stop the node's workloads and delete its folder", + ), + ( + &["site", "init"], + "error: missing workload choices; --yaml never asks, so pass --inference and --applications", + ), + ]; + + for (arguments, expected) in cases { + let mut command = dotc(); + command + .arg("--yaml") + .args(arguments) + .arg("--site-dir") + .arg(&site) + .clear_test_environment(); + let output = command.output().expect("run a command that would ask"); + + assert!(!output.status.success(), "{arguments:?}"); + assert_eq!(text(&output.stdout), "", "{arguments:?}"); + assert!( + text(&output.stderr).starts_with(expected), + "{arguments:?}: {}", + text(&output.stderr) + ); + } + assert!(!site.exists()); +} + +#[test] +fn yaml_site_commands_print_one_document_each() { + let fixture = TemporarySite::empty(); + let site_dir = fixture.root.join("site"); + let site_command = |verb: &[&str]| { + let mut command = dotc(); + command + .arg("--yaml") + .arg("site") + .args(verb) + .arg("--site-dir") + .arg(&site_dir) + .args([ + "--host", + "127.0.0.1", + "--inference", + "simulated", + "--applications", + "simulated", + "--applications", + "docker", + "--site-id", + "site-test", + "--node-id", + "node-test", + ]) + .clear_test_environment(); + command + }; + let site_document = |outcome: &str| { + serde_json::json!({ + "outcome": outcome, + "siteDir": site_dir, + "siteId": "site-test", + "nodeId": "node-test", + "nodeHost": "127.0.0.1", + "inference": ["simulated"], + "applications": ["simulated", "docker"], + }) + }; + + let initialized = site_command(&["init"]).output().expect("run site init"); + let kept = site_command(&["init"]) + .output() + .expect("run site init again"); + let reset = site_command(&["reset"]).output().expect("run site reset"); + let mut validate = dotc(); + validate + .args(["--yaml", "site", "validate", "--site-dir"]) + .arg(&site_dir) + .clear_test_environment(); + let validated = validate.output().expect("run site validate"); + let mut if_missing = dotc(); + if_missing + .args(["--yaml", "site", "init", "--if-missing", "--site-dir"]) + .arg(&site_dir) + .args(["--inference", "none", "--applications", "none"]) + .clear_test_environment(); + let present = if_missing.output().expect("run site init --if-missing"); + let mut delete = dotc(); + delete + .args(["--yaml", "site", "delete", "--site-dir"]) + .arg(&site_dir) + .clear_test_environment(); + let deleted = delete.output().expect("run site delete"); + + for (output, document) in [ + (&initialized, site_document("initialized")), + (&kept, site_document("alreadyInitialized")), + (&reset, site_document("reset")), + ( + &validated, + serde_json::json!({ "outcome": "valid", "siteDir": site_dir }), + ), + ( + &present, + serde_json::json!({ "outcome": "alreadyInitialized", "siteDir": site_dir }), + ), + ( + &deleted, + serde_json::json!({ "outcome": "deleted", "siteDir": site_dir }), + ), + ] { + assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); + assert_eq!(support::yaml_documents(&text(&output.stdout)), [document]); + } + assert!(!site_dir.exists()); +} + #[test] fn fake_manager_serves_seeded_deployments_and_applies_lifecycle_requests() { use dotcore_proto::dotcore::{ @@ -4011,7 +4591,8 @@ fn node_remove_asks_the_operator_to_review_and_confirm_in_a_terminal() { Session::new([ Step::Wait("Remove this node from the site?"), Step::Send(b"yes\n"), - ]), + ]) + .with_stdout_on_terminal(), ) else { return; }; @@ -4025,8 +4606,7 @@ fn node_remove_asks_the_operator_to_review_and_confirm_in_a_terminal() { "These deployments are dropped without cleaning up the node", "application Worker app (present)", "Removed Worker two", - "On that machine, stop its server, then run:", - "dotc node leave", + "The removed machine keeps its workloads and node folder", ] { assert!( run.screen().contains(expected), @@ -4034,6 +4614,9 @@ fn node_remove_asks_the_operator_to_review_and_confirm_in_a_terminal() { run.screen() ); } + for absent in ["Next", "dotc node leave"] { + assert!(!run.screen().contains(absent), "{absent}\n{}", run.screen()); + } assert_eq!(pin_files(fixture.site_path()), Vec::::new()); } @@ -4193,10 +4776,7 @@ fn node_join_in_the_default_folder_prints_the_plain_start_command() { assert_eq!(joined.status.code(), Some(0), "{}", text(&joined.stderr)); assert_eq!(add.finish().status.code(), Some(0)); - assert_eq!( - record(&text(&joined.stdout), "DOTCORE_START_COMMAND="), - "dotcore" - ); + assert_eq!(start_command(&text(&joined.stdout)), "dotcore"); assert!(state.join("dotcore/site/trust/node-key.pk8").is_file()); } @@ -4232,10 +4812,7 @@ fn node_join_in_a_folder_from_the_environment_prints_the_plain_start_command() { assert_eq!(joined.status.code(), Some(0), "{}", text(&joined.stderr)); assert_eq!(add.finish().status.code(), Some(0)); - assert_eq!( - record(&text(&joined.stdout), "DOTCORE_START_COMMAND="), - "dotcore" - ); + assert_eq!(start_command(&text(&joined.stdout)), "dotcore"); assert!(node_dir.join("trust/node-key.pk8").is_file()); } @@ -4288,7 +4865,7 @@ fn the_printed_start_command_starts_the_joined_node() { .expect("run node join"); assert_eq!(joined.status.code(), Some(0), "{}", text(&joined.stderr)); assert_eq!(add.finish().status.code(), Some(0)); - let printed = record(&text(&joined.stdout), "DOTCORE_START_COMMAND="); + let printed = start_command(&text(&joined.stdout)); assert_eq!( printed, format!("dotcore --site-dir {}", node_dir.display()) @@ -4433,10 +5010,7 @@ fn node_join_proposes_the_machine_host_variable_unless_the_host_flag_is_given() .output() .expect("join with the host variable"); assert_eq!(joined.status.code(), Some(0), "{}", text(&joined.stderr)); - assert_eq!( - record(&text(&joined.stdout), "DOTCORE_NODE_HOST="), - "localhost" - ); + assert_eq!(joined_host(&text(&joined.stdout)), "localhost"); assert_eq!(add.finish().status.code(), Some(0)); // The flag wins over the variable. @@ -4451,10 +5025,7 @@ fn node_join_proposes_the_machine_host_variable_unless_the_host_flag_is_given() join.env("DOTCORE_MACHINE_HOST", "localhost"); let joined = join.output().expect("join with the host flag and variable"); assert_eq!(joined.status.code(), Some(0), "{}", text(&joined.stderr)); - assert_eq!( - record(&text(&joined.stdout), "DOTCORE_NODE_HOST="), - "127.0.0.3" - ); + assert_eq!(joined_host(&text(&joined.stdout)), "127.0.0.3"); assert_eq!(add.finish().status.code(), Some(0)); // The retired DOTCORE_DEV_HOST name is not read: without a host the manager falls back to the @@ -4505,7 +5076,7 @@ fn node_join_proposes_the_machine_host_variable_unless_the_host_flag_is_given() text(&observed.stderr) ); assert_eq!( - record(&text(&observed.stdout), "DOTCORE_NODE_HOST="), + joined_host(&text(&observed.stdout)), observed_host.to_string() ); assert_eq!(add.finish().status.code(), Some(0)); @@ -4601,7 +5172,8 @@ fn node_add_asks_the_operator_and_node_join_enters_the_token_hidden() { let add_run = thread::spawn(move || { run_in_pty( add, - Session::new([Step::Wait("Allow this node to join?"), Step::Send(b"yes\n")]), + Session::new([Step::Wait("Allow this node to join?"), Step::Send(b"yes\n")]) + .with_stdout_on_terminal(), ) }); wait_for_file(&token_file, &manager); @@ -4637,7 +5209,8 @@ fn node_add_asks_the_operator_and_node_join_enters_the_token_hidden() { Step::Wait("Waiting for approval on the manager..."), Step::Wait("Node name"), Step::Send(b"Interactive node\n"), - ]); + ]) + .with_stdout_on_terminal(); let Some(joined) = run_in_pty(join, session) else { return; }; @@ -4653,10 +5226,11 @@ fn node_add_asks_the_operator_and_node_join_enters_the_token_hidden() { joined.screen() ); assert!( - joined.screen().contains("Start the node:"), + joined.screen().contains("The node is not started"), "{}", joined.screen() ); + assert!(!joined.screen().contains("Next"), "{}", joined.screen()); assert!( !joined.screen().contains(&token[..16]), "the token was echoed:\n{}", @@ -4763,7 +5337,8 @@ fn an_interactive_join_starts_the_node_with_its_packaged_launcher_or_shows_how() Session::new([ Step::Wait("Send this proposal to the manager?"), Step::Send(confirm), - ]), + ]) + .with_stdout_on_terminal(), ) else { return; }; @@ -4785,7 +5360,7 @@ fn an_interactive_join_starts_the_node_with_its_packaged_launcher_or_shows_how() joined.session() ); assert!( - !joined.session().contains("Start the node:"), + !joined.session().contains("The node is not started"), "{}", joined.session() ); @@ -4793,10 +5368,12 @@ fn an_interactive_join_starts_the_node_with_its_packaged_launcher_or_shows_how() // Line prompts can't skip with a key, so they show the command instead. assert!(!launched.exists(), "the launcher ran on a dumb terminal"); assert!( - joined.session().contains(&format!( - "Start the node:\n dotcore --site-dir {}", - node_dir.display() - )), + joined.session().contains("The node is not started"), + "{}", + joined.session() + ); + assert!( + !joined.session().contains("dotcore --site-dir"), "{}", joined.session() ); @@ -4909,7 +5486,9 @@ fn site_validate_success_prints_only_the_exact_machine_readable_records() { assert_eq!( text(&output.stdout), format!( - "Site valid\nDOTCORE_SITE_DIR={}\n", + "✔ Site valid + directory {} +", fixture.site_path().display() ) ); @@ -4919,7 +5498,7 @@ fn site_validate_success_prints_only_the_exact_machine_readable_records() { #[test] fn site_commands_read_a_site_that_holds_deployments() { let fixture = TemporarySite::new(); - let valid = "siteId: cli-test-site\nmodelDeploymentIdentityAllocator: { namespace: 0123456789abcdef, nextSequence: '1' }\nnodes:\n- nodeId: cli-test-node\n host: 127.0.0.2\n displayName: CLI test node\n siteManager: {}\nmodelDeployments:\n- modelDeploymentId: upstream-one\n snapshot:\n upstream:\n upstreamModelTemplate:\n upstreamModelTemplateId: openai-compatible\n displayName: OpenAI-compatible\n wireProtocol: UPSTREAM_WIRE_PROTOCOL_OPENAI_COMPATIBLE\n desiredState: MODEL_DEPLOYMENT_DESIRED_STATE_PRESENT\n lifecycleGeneration: '1'\n lifecycleTransition: MODEL_DEPLOYMENT_LIFECYCLE_TRANSITION_CREATE\n upstreamDesiredConfiguration:\n upstreamModelId: hosted-private-model\n apiKey: test-upstream-key\n inputCapabilities:\n supportsText: true\n supportsImage: true\n endpoint:\n baseUrl: https://endpoint.example/v1\n allowInsecureHttp: false\n boundary:\n locality: UPSTREAM_MODEL_LOCALITY_PUBLIC_EXTERNAL\n trustDomain: endpoint.example\n dataEgressClass: UPSTREAM_MODEL_DATA_EGRESS_CLASS_PUBLIC_INTERNET\n"; + let valid = "siteId: cli-test-site\ndeploymentIdentityAllocator: { suffixKey: 0123456789abcdef, nextSequence: '1' }\nnodes:\n- nodeId: cli-test-node\n host: 127.0.0.2\n displayName: CLI test node\n siteManager: {}\nmodelDeployments:\n- modelDeploymentId: upstream-one\n snapshot:\n upstream:\n upstreamModelTemplate:\n upstreamModelTemplateId: openai-compatible\n displayName: OpenAI-compatible\n wireProtocol: UPSTREAM_WIRE_PROTOCOL_OPENAI_COMPATIBLE\n desiredState: MODEL_DEPLOYMENT_DESIRED_STATE_PRESENT\n lifecycleGeneration: '1'\n lifecycleTransition: MODEL_DEPLOYMENT_LIFECYCLE_TRANSITION_CREATE\n upstreamDesiredConfiguration:\n upstreamModelId: hosted-private-model\n apiKey: test-upstream-key\n inputCapabilities:\n supportsText: true\n supportsImage: true\n endpoint:\n baseUrl: https://endpoint.example/v1\n allowInsecureHttp: false\n boundary:\n locality: UPSTREAM_MODEL_LOCALITY_PUBLIC_EXTERNAL\n trustDomain: endpoint.example\n dataEgressClass: UPSTREAM_MODEL_DATA_EGRESS_CLASS_PUBLIC_INTERNET\n"; let site_yaml = fixture.site_path().join("site.yaml"); std::fs::write(&site_yaml, valid).expect("Upstream site input"); std::fs::set_permissions( @@ -4943,13 +5522,15 @@ fn site_commands_read_a_site_that_holds_deployments() { assert_eq!( text(&validated.stdout), format!( - "Site valid\nDOTCORE_SITE_DIR={}\n", + "✔ Site valid + directory {} +", fixture.site_path().display() ) ); let configuration = dotc() - .args(["config", "show", "--format", "json", "--site-dir"]) + .args(["--yaml", "config", "show", "--site-dir"]) .arg(fixture.site_path()) .clear_test_environment() .env("HOME", fixture.root.join("home")) @@ -4961,9 +5542,10 @@ fn site_commands_read_a_site_that_holds_deployments() { "{}", text(&configuration.stderr) ); - let json = serde_json::from_slice::(&configuration.stdout) - .expect("configuration JSON"); - assert_eq!(json["nodeHost"], "127.0.0.2"); + let [document] = &support::yaml_documents(&text(&configuration.stdout))[..] else { + panic!("one configuration document"); + }; + assert_eq!(document["nodeHost"], "127.0.0.2"); let replaced = dotc() .args(["site", "init", "--replace", "--site-dir"]) @@ -5008,7 +5590,9 @@ fn site_validate_platform_catalog_composition_is_optional_and_read_only() { assert_eq!( text(&output.stdout), format!( - "Site valid\nDOTCORE_SITE_DIR={}\n", + "✔ Site valid + directory {} +", fixture.site_path().display() ) ); @@ -5336,11 +5920,18 @@ fn site_reset_rejects_a_live_server_without_mutation_then_succeeds_after_shutdow #[test] fn server_start_emits_startup_protocol_and_exits_cleanly_after_signals() { for signal in [libc::SIGINT, libc::SIGTERM] { - assert_lifecycle(signal); + assert_lifecycle(signal, false); } } -fn assert_lifecycle(signal: libc::c_int) { +#[test] +fn server_start_from_a_terminal_session_writes_only_the_startup_protocol_to_stdout() { + assert_lifecycle(libc::SIGTERM, true); +} + +/// Runs the server until `signal` stops it, with a controlling terminal when `terminal` is set, +/// and asserts its stdout carries exactly the startup protocol. +fn assert_lifecycle(signal: libc::c_int, terminal: bool) { let fixture = TemporarySite::new(); let mut command = dotc(); command @@ -5354,6 +5945,14 @@ fn assert_lifecycle(signal: libc::c_int) { .env("DOTCORE_CATALOG_DIR", fixture.catalog_path()) .env("DOTCORE_CACHE_DIR", fixture.cache_path()) .env("RUST_LOG", "info"); + let _terminal = if terminal { + let Some(terminal) = attach_controlling_terminal(&mut command) else { + return; + }; + Some(terminal) + } else { + None + }; let child = command .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -6118,19 +6717,47 @@ fn join_node(site_dir: &Path, node_dir: &Path, name: &str, host: &str) { manager.stop(); } -const MANAGER_LIST_BLOCK: &str = "Node\nDOTCORE_NODE_ID=cli-test-node\nDOTCORE_NODE_NAME=CLI test node\nDOTCORE_NODE_ROLE=manager\nDOTCORE_NODE_HOST=127.0.0.2\nDOTCORE_NODE_MANAGER_HOST=default\nDOTCORE_NODE_PIN=own identity\nDOTCORE_NODE_EXECUTION_TARGET=cli-test-target model linux/amd64\nDOTCORE_NODE_EXECUTION_TARGET=cli-test-application-target application linux/amd64\nDOTCORE_NODE_MODEL_DEPLOYMENTS=0\nDOTCORE_NODE_APPLICATION_DEPLOYMENTS=0\n"; - -/// The joined worker's `node list` block: its simulated models run on the default simulated GPU, -/// which the declared machine puts on a Linux host of this machine's architecture, and its -/// simulated applications take that architecture too. -fn worker_list_block() -> String { - let platform = match std::env::consts::ARCH { - "aarch64" => "linux/arm64", - _ => "linux/amd64", - }; - format!( - "Node\nDOTCORE_NODE_ID=node-7b836d678d251736\nDOTCORE_NODE_NAME=Worker two\nDOTCORE_NODE_ROLE=worker\nDOTCORE_NODE_HOST=127.0.0.3\nDOTCORE_NODE_MANAGER_HOST=default\nDOTCORE_NODE_PIN=yes\nDOTCORE_NODE_EXECUTION_TARGET=execution-target-7182af3d809190c5-simulated-4d747ac0 model {platform}\nDOTCORE_NODE_EXECUTION_TARGET=application-execution-target-7182af3d809190c5-simulated application {platform}\nDOTCORE_NODE_MODEL_DEPLOYMENTS=0\nDOTCORE_NODE_APPLICATION_DEPLOYMENTS=0\n" - ) +/// The plain table `dotc node list` prints for the fixture's manager and, when given, the joined +/// worker with its host and placed applications. +fn expected_node_list(worker: Option<(&str, usize)>) -> String { + let mut rows = vec![ + ["NAME", "ID", "ROLE", "HOST", "MODELS", "APPS"].map(str::to_owned), + [ + "CLI test node", + "cli-test-node", + "manager", + "127.0.0.2", + "0", + "0", + ] + .map(str::to_owned), + ]; + if let Some((host, applications)) = worker { + rows.push( + [ + "Worker two", + WORKER_NODE_ID, + "worker", + host, + "0", + &applications.to_string(), + ] + .map(str::to_owned), + ); + } + let widths: [usize; 6] = + std::array::from_fn(|column| rows.iter().map(|row| row[column].len()).max().unwrap_or(0)); + let mut text = "Nodes of site cli-test-site\n".to_owned(); + for row in &rows { + let cells = row + .iter() + .zip(widths) + .map(|(cell, width)| format!("{cell:>() + .join(" "); + text.push_str(&format!(" {}\n", cells.trim_end())); + } + text } /// Builds a non-interactive `dotc node remove` of `node` on the fixture site. @@ -6163,7 +6790,7 @@ fn node_list_command(site_dir: &Path) -> Command { command } -/// Runs `dotc node list` without a terminal and returns its records. +/// Runs `dotc node list` without a terminal and returns its output. fn node_list_stdout(site_dir: &Path) -> String { let output = node_list_command(site_dir).output().expect("run node list"); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); @@ -6272,13 +6899,44 @@ fn neighbor_lines<'a>(text: &'a str, start: &str) -> (Option<&'a str>, Option<&' ) } -fn record(stdout: &str, prefix: &str) -> String { - let mut records = stdout.lines().filter_map(|line| line.strip_prefix(prefix)); - let value = records +/// The command a joined node's output says starts it, on the line after its announcement. +fn start_command(stdout: &str) -> String { + let mut lines = stdout + .lines() + .skip_while(|line| *line != "Start the node with:"); + lines.next().expect("start announcement in the output"); + lines + .next() + .unwrap_or_else(|| panic!("missing start command in {stdout:?}")) + .trim() + .to_owned() +} + +/// The host a join's success line names, such as `127.0.0.3` in `Joined site as node at 127.0.0.3`. +fn joined_host(stdout: &str) -> String { + let line = stdout + .lines() + .find(|line| line.contains("Joined ") || line.contains("Rejoined ")) + .unwrap_or_else(|| panic!("missing join success line in {stdout:?}")); + line.rsplit_once(" at ") + .expect("host after `at`") + .1 + .to_owned() +} + +/// The value of a labeled fact in a command's output, such as `node host` in a site summary. +fn fact(stdout: &str, label: &str) -> String { + let mut values = stdout.lines().filter_map(|line| { + line.trim_start() + .strip_prefix(label) + .filter(|rest| rest.starts_with(" ")) + .map(|rest| rest.trim().to_owned()) + }); + let value = values .next() - .unwrap_or_else(|| panic!("missing {prefix} in {stdout:?}")); - assert!(records.next().is_none(), "duplicate {prefix} in {stdout:?}"); - value.to_owned() + .unwrap_or_else(|| panic!("missing {label} in {stdout:?}")); + assert!(values.next().is_none(), "duplicate {label} in {stdout:?}"); + value } fn assert_generated_simulated_bundle(site_dir: &Path, site_id: &str, node_id: &str) { @@ -6431,7 +7089,7 @@ impl TemporarySite { std::fs::create_dir_all(root.join("cache")).expect("cache directory"); std::fs::write( root.join("site.yaml"), - "siteId: cli-test-site\nmodelDeploymentIdentityAllocator: { namespace: 0123456789abcdef, nextSequence: '1' }\nnodes:\n- nodeId: cli-test-node\n host: 127.0.0.2\n displayName: CLI test node\n siteManager: {}\nexecutionTargets:\n- executionTargetId: cli-test-target\n siteNodeId: cli-test-node\n displayName: cli-test-target\n platform: { operatingSystem: linux, architecture: amd64 }\n acceleratorDeviceIds: [GPU-00000000-0000-0000-0000-000000005090]\n modelRuntime:\n simulatedRuntime:\n defaultScenario: { readyDelayMillis: 0, stopDelayMillis: 0 }\n- executionTargetId: cli-test-application-target\n siteNodeId: cli-test-node\n displayName: cli-test-application-target\n platform: { operatingSystem: linux, architecture: amd64 }\n applicationRuntime: { simulatedRuntime: {} }\nmodelDeployments: []\ninferenceRoutes: []\napplicationDeployments: []\n", + "siteId: cli-test-site\ndeploymentIdentityAllocator: { suffixKey: 0123456789abcdef, nextSequence: '1' }\nnodes:\n- nodeId: cli-test-node\n host: 127.0.0.2\n displayName: CLI test node\n siteManager: {}\nexecutionTargets:\n- executionTargetId: cli-test-target\n siteNodeId: cli-test-node\n displayName: cli-test-target\n platform: { operatingSystem: linux, architecture: amd64 }\n acceleratorDeviceIds: [GPU-00000000-0000-0000-0000-000000005090]\n modelRuntime:\n simulatedRuntime:\n defaultScenario: { readyDelayMillis: 0, stopDelayMillis: 0 }\n- executionTargetId: cli-test-application-target\n siteNodeId: cli-test-node\n displayName: cli-test-application-target\n platform: { operatingSystem: linux, architecture: amd64 }\n applicationRuntime: { simulatedRuntime: {} }\nmodelDeployments: []\ninferenceRoutes: []\napplicationDeployments: []\n", ) .expect("desired site"); std::fs::write( @@ -6684,6 +7342,113 @@ fn hardware_recommend_prints_exact_tables_for_a_described_machine() { ); } +#[test] +fn yaml_hardware_recommend_prints_the_recommendations_as_one_document() { + let catalog = Path::new(env!("CARGO_MANIFEST_DIR")).join("../fixtures/recommendation-catalog"); + let fixture = TemporarySite::empty(); + let machine = fixture.root.join("roomy.yaml"); + std::fs::write( + &machine, + "platform: linux/amd64\ncpuCount: 8\nhostMemory: { totalBytes: 34359738368, idleUsedBytes: 4294967296 }\ngpus:\n - id: GPU-fixture\n vendor: nvidia\n model: Fixture GPU X\n driverVersion: \"580.173.02\"\n memory: { architecture: dedicated, totalBytes: 34359738368, reservedBytes: 536870912 }\n", + ) + .expect("write machine description"); + + let output = isolated_dotc() + .args(["--yaml", "hardware", "recommend", "--machine"]) + .arg(&machine) + .arg("--catalog-dir") + .arg(&catalog) + .output() + .expect("run dotc hardware recommend"); + + assert!(output.status.success(), "{}", text(&output.stderr)); + assert_eq!(text(&output.stderr), ""); + let recommendation = |model: &str, name: &str, total: u64| { + serde_json::json!({ + "modelId": model, + "modelName": name, + "profileId": "q4", + "profileName": "Fixture Q4", + "contextPerRequest": 32768, + "targets": [{ + "executionTargetId": "execution-target-4e1fd5461dfe5ef9-nvidia-94da1331", + "executionTargetName": "Fixture GPU X", + "fit": "fitsNow", + "startingTotalContext": total, + }], + }) + }; + assert_eq!( + support::yaml_documents(&text(&output.stdout)), + [serde_json::json!({ + "useCases": [ + { + "useCase": "USE_CASE_CODING", + "recommendations": [ + recommendation("big", "Fixture Big", 131072), + recommendation("small", "Fixture Small", 131072), + ], + }, + { + "useCase": "USE_CASE_CHAT_ASSISTANT", + "recommendations": [recommendation("small", "Fixture Small", 131072)], + "application": { + "applicationId": "fixture-chat", + "displayName": "Fixture Chat", + "note": "no target matches its preferred accelerators: apple", + }, + }, + { + "useCase": "USE_CASE_IMAGE_GENERATION", + "recommendations": [], + "application": { + "applicationId": "fixture-art", + "displayName": "Fixture Art", + }, + }, + ], + })] + ); +} + +#[test] +fn hardware_show_summarizes_the_machine_and_yaml_prints_a_loadable_description() { + let human = isolated_dotc() + .args(["hardware", "show"]) + .output() + .expect("run dotc hardware show"); + let yaml = isolated_dotc() + .args(["--yaml", "hardware", "show"]) + .output() + .expect("run dotc --yaml hardware show"); + + assert!(human.status.success(), "{}", text(&human.stderr)); + let summary = text(&human.stdout); + assert!(summary.starts_with("Hardware\n"), "{summary}"); + for label in ["dotcore ", "platform ", "cpus ", "host memory "] { + assert!(summary.contains(label), "{label}: {summary}"); + } + assert!(!summary.contains("cpuCount"), "{summary}"); + + assert!(yaml.status.success(), "{}", text(&yaml.stderr)); + let report = text(&yaml.stdout); + assert!( + report.starts_with(&format!("# Dotcore {}", env!("CARGO_PKG_VERSION"))), + "{report}" + ); + let [document] = &support::yaml_documents(&report)[..] else { + panic!("one machine description"); + }; + let mut keys = document + .as_object() + .expect("machine description") + .keys() + .map(String::as_str) + .collect::>(); + keys.retain(|key| *key != "gpus"); + assert_eq!(keys, ["cpuCount", "hostMemory", "platform"]); +} + fn list_machines_request() -> &'static [u8] { b"POST /dotcore.site.v1.SiteService/ListMachines HTTP/1.1\r\nHost: localhost\r\nOrigin: http://127.0.0.1:5173\r\nContent-Type: application/grpc-web+proto\r\nx-grpc-web: 1\r\nConnection: close\r\nContent-Length: 5\r\n\r\n\0\0\0\0\0" } diff --git a/backend/cli/tests/model_contract.rs b/backend/cli/tests/model_contract.rs index 01dce909..c3e6254e 100644 --- a/backend/cli/tests/model_contract.rs +++ b/backend/cli/tests/model_contract.rs @@ -21,6 +21,7 @@ use dotcore_proto::{ }, google::protobuf::Timestamp, }; +use serde_json::json; use tonic::Status; mod support; @@ -35,7 +36,7 @@ use support::{ }; #[test] -fn list_prints_one_record_block_per_deployment_in_every_state() { +fn list_prints_a_table_row_per_deployment_in_every_state() { let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); let output = run(&manager, &["list"]); @@ -44,15 +45,7 @@ fn list_prints_one_record_block_per_deployment_in_every_state() { assert_eq!(output.status.code(), Some(0)); assert_eq!( text(&output.stdout), - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-1\nDOTCORE_MODEL_DEPLOYMENT_NAME=Gemma\nDOTCORE_MODEL_DEPLOYMENT_STATE=Ready\nDOTCORE_MODEL_DEPLOYMENT_NODE=gb10-host\nDOTCORE_MODEL_DEPLOYMENT_MODEL=Gemma 4 E4B\n\ -\n\ -Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-2\nDOTCORE_MODEL_DEPLOYMENT_NAME=Qwen\nDOTCORE_MODEL_DEPLOYMENT_STATE=Downloading\nDOTCORE_MODEL_DEPLOYMENT_NODE=gb10-host\nDOTCORE_MODEL_DEPLOYMENT_MODEL=Gemma 4 E4B\n\ -\n\ -Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-3\nDOTCORE_MODEL_DEPLOYMENT_NAME=Llama\nDOTCORE_MODEL_DEPLOYMENT_STATE=Failed\nDOTCORE_MODEL_DEPLOYMENT_NODE=gb10-host\nDOTCORE_MODEL_DEPLOYMENT_MODEL=Gemma 4 E4B\n\ -\n\ -Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-4\nDOTCORE_MODEL_DEPLOYMENT_NAME=Mistral\nDOTCORE_MODEL_DEPLOYMENT_STATE=Paused\nDOTCORE_MODEL_DEPLOYMENT_NODE=gb10-host\nDOTCORE_MODEL_DEPLOYMENT_MODEL=Gemma 4 E4B\n\ -\n\ -Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-5\nDOTCORE_MODEL_DEPLOYMENT_NAME=Phi\nDOTCORE_MODEL_DEPLOYMENT_STATE=Tearing down\nDOTCORE_MODEL_DEPLOYMENT_NODE=gb10-host\nDOTCORE_MODEL_DEPLOYMENT_MODEL=Gemma 4 E4B\n" + " NAME ID STATE NODE MODEL\n Gemma model-1 Ready gb10-host Gemma 4 E4B\n Qwen model-2 Downloading gb10-host Gemma 4 E4B\n Llama model-3 Failed gb10-host Gemma 4 E4B\n Mistral model-4 Paused gb10-host Gemma 4 E4B\n Phi model-5 Tearing down gb10-host Gemma 4 E4B\n" ); assert_eq!( manager.calls(), @@ -73,25 +66,25 @@ fn list_shows_the_node_id_when_the_manager_does_not_name_the_node() { assert_eq!(output.status.code(), Some(0)); assert!( - text(&output.stdout).contains("DOTCORE_MODEL_DEPLOYMENT_NODE=node-1\n"), + text(&output.stdout).contains(" Ready node-1 Gemma 4 E4B\n"), "{}", text(&output.stdout) ); } #[test] -fn list_of_an_empty_site_prints_nothing() { +fn list_of_an_empty_site_says_there_are_no_deployments() { let manager = FakeManager::start(FakeState::with_models(Vec::new())); let output = run(&manager, &["list"]); assert_eq!(output.status.code(), Some(0)); - assert_eq!(text(&output.stdout), ""); + assert_eq!(text(&output.stdout), "No model deployments\n"); assert_eq!(text(&output.stderr), ""); } #[test] -fn show_prints_every_key_for_a_ready_deployment() { +fn show_prints_every_known_fact_for_a_ready_deployment() { let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); let output = run(&manager, &["show", "Gemma"]); @@ -100,7 +93,7 @@ fn show_prints_every_key_for_a_ready_deployment() { assert_eq!(output.status.code(), Some(0)); assert_eq!( text(&output.stdout), - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-1\nDOTCORE_MODEL_DEPLOYMENT_NAME=Gemma\nDOTCORE_MODEL_DEPLOYMENT_STATE=Ready\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE=Present\nDOTCORE_MODEL_DEPLOYMENT_NODE=gb10-host\nDOTCORE_MODEL_DEPLOYMENT_EXECUTION_TARGET=node-1-model\nDOTCORE_MODEL_DEPLOYMENT_MODEL=Gemma 4 E4B\nDOTCORE_MODEL_DEPLOYMENT_PROFILE=default\nDOTCORE_MODEL_DEPLOYMENT_ENGINE=llama-cpp\nDOTCORE_MODEL_DEPLOYMENT_PROGRESS=\nDOTCORE_MODEL_DEPLOYMENT_FAILURE=\nDOTCORE_MODEL_DEPLOYMENT_MESSAGE=\n" + "Model deployment Gemma\n name Gemma\n id model-1\n state Ready\n desired Present\n node gb10-host\n target Simulated models\n target id node-1-model\n model Gemma 4 E4B\n profile default\n engine llama-cpp\n" ); } @@ -113,11 +106,11 @@ fn show_reports_progress_failure_and_status_message_by_id() { assert_eq!( text(&downloading.stdout), - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-2\nDOTCORE_MODEL_DEPLOYMENT_NAME=Qwen\nDOTCORE_MODEL_DEPLOYMENT_STATE=Downloading\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE=Present\nDOTCORE_MODEL_DEPLOYMENT_NODE=gb10-host\nDOTCORE_MODEL_DEPLOYMENT_EXECUTION_TARGET=node-1-model\nDOTCORE_MODEL_DEPLOYMENT_MODEL=Gemma 4 E4B\nDOTCORE_MODEL_DEPLOYMENT_PROFILE=default\nDOTCORE_MODEL_DEPLOYMENT_ENGINE=llama-cpp\nDOTCORE_MODEL_DEPLOYMENT_PROGRESS=42%\nDOTCORE_MODEL_DEPLOYMENT_FAILURE=\nDOTCORE_MODEL_DEPLOYMENT_MESSAGE=Fetching weights\n" + "Model deployment Qwen\n name Qwen\n id model-2\n state Downloading\n desired Present\n node gb10-host\n target Simulated models\n target id node-1-model\n model Gemma 4 E4B\n profile default\n engine llama-cpp\n progress 42%\n message Fetching weights\n" ); assert_eq!( text(&failed.stdout), - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-3\nDOTCORE_MODEL_DEPLOYMENT_NAME=Llama\nDOTCORE_MODEL_DEPLOYMENT_STATE=Failed\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE=Present\nDOTCORE_MODEL_DEPLOYMENT_NODE=gb10-host\nDOTCORE_MODEL_DEPLOYMENT_EXECUTION_TARGET=node-1-model\nDOTCORE_MODEL_DEPLOYMENT_MODEL=Gemma 4 E4B\nDOTCORE_MODEL_DEPLOYMENT_PROFILE=default\nDOTCORE_MODEL_DEPLOYMENT_ENGINE=llama-cpp\nDOTCORE_MODEL_DEPLOYMENT_PROGRESS=\nDOTCORE_MODEL_DEPLOYMENT_FAILURE=Out of memory on the GPU\nDOTCORE_MODEL_DEPLOYMENT_MESSAGE=\n" + "Model deployment Llama\n name Llama\n id model-3\n state Failed\n desired Present\n node gb10-host\n target Simulated models\n target id node-1-model\n model Gemma 4 E4B\n profile default\n engine llama-cpp\n failure Out of memory on the GPU\n" ); } @@ -129,16 +122,12 @@ fn show_applies_the_console_state_overrides() { let tearing_down = run(&manager, &["show", "Phi"]); assert!( - text(&paused.stdout).contains( - "DOTCORE_MODEL_DEPLOYMENT_STATE=Paused\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE=Paused\n" - ), + text(&paused.stdout).contains(" state Paused\n desired Paused\n"), "{}", text(&paused.stdout) ); assert!( - text(&tearing_down.stdout).contains( - "DOTCORE_MODEL_DEPLOYMENT_STATE=Tearing down\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE=Teardown\n" - ), + text(&tearing_down.stdout).contains(" state Tearing down\n desired Teardown\n"), "{}", text(&tearing_down.stdout) ); @@ -161,11 +150,11 @@ fn show_hides_the_status_message_that_a_requested_change_overrides() { assert_eq!( text(&tearing_down.stdout), - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-6\nDOTCORE_MODEL_DEPLOYMENT_NAME=Old\nDOTCORE_MODEL_DEPLOYMENT_STATE=Tearing down\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE=Teardown\nDOTCORE_MODEL_DEPLOYMENT_NODE=gb10-host\nDOTCORE_MODEL_DEPLOYMENT_EXECUTION_TARGET=node-1-model\nDOTCORE_MODEL_DEPLOYMENT_MODEL=Gemma 4 E4B\nDOTCORE_MODEL_DEPLOYMENT_PROFILE=default\nDOTCORE_MODEL_DEPLOYMENT_ENGINE=llama-cpp\nDOTCORE_MODEL_DEPLOYMENT_PROGRESS=\nDOTCORE_MODEL_DEPLOYMENT_FAILURE=\nDOTCORE_MODEL_DEPLOYMENT_MESSAGE=\n" + "Model deployment Old\n name Old\n id model-6\n state Tearing down\n desired Teardown\n node gb10-host\n target Simulated models\n target id node-1-model\n model Gemma 4 E4B\n profile default\n engine llama-cpp\n" ); assert_eq!( text(&pausing.stdout), - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-7\nDOTCORE_MODEL_DEPLOYMENT_NAME=Slow\nDOTCORE_MODEL_DEPLOYMENT_STATE=Pausing\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE=Paused\nDOTCORE_MODEL_DEPLOYMENT_NODE=gb10-host\nDOTCORE_MODEL_DEPLOYMENT_EXECUTION_TARGET=node-1-model\nDOTCORE_MODEL_DEPLOYMENT_MODEL=Gemma 4 E4B\nDOTCORE_MODEL_DEPLOYMENT_PROFILE=default\nDOTCORE_MODEL_DEPLOYMENT_ENGINE=llama-cpp\nDOTCORE_MODEL_DEPLOYMENT_PROGRESS=\nDOTCORE_MODEL_DEPLOYMENT_FAILURE=\nDOTCORE_MODEL_DEPLOYMENT_MESSAGE=\n" + "Model deployment Slow\n name Slow\n id model-7\n state Pausing\n desired Paused\n node gb10-host\n target Simulated models\n target id node-1-model\n model Gemma 4 E4B\n profile default\n engine llama-cpp\n" ); } @@ -227,7 +216,7 @@ fn commands_need_no_site_folder() { let output = command.output().expect("run dotc model list"); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); - assert!(text(&output.stdout).contains("DOTCORE_MODEL_DEPLOYMENT_ID=model-1\n")); + assert!(text(&output.stdout).contains(" Gemma model-1 Ready")); assert_eq!( std::fs::read_dir(empty.path()) .expect("read working directory") @@ -249,7 +238,7 @@ fn the_manager_flag_overrides_the_environment_address() { let output = command.output().expect("run dotc model list"); assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); - assert!(text(&output.stdout).contains("DOTCORE_MODEL_DEPLOYMENT_ID=model-5\n")); + assert!(text(&output.stdout).contains(" Phi model-5 Tearing down")); } #[test] @@ -259,7 +248,7 @@ fn help_lists_the_six_verbs_and_the_manager_flag() { .output() .expect("run help"); let list = isolated_dotc() - .args(["model", "list", "--help"]) + .args(["model", "list", "-h"]) .output() .expect("run help"); @@ -286,24 +275,16 @@ fn pause_and_resume_request_the_change_and_print_the_accepted_state() { let paused = run(&manager, &["pause", "Gemma"]); - assert_eq!( - text(&paused.stderr), - "Notice: Run `dotc model list` to follow its progress.\n" - ); + assert_eq!(text(&paused.stderr), ""); assert_eq!(paused.status.code(), Some(0)); - assert_eq!( - text(&paused.stdout), - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-1\nDOTCORE_MODEL_DEPLOYMENT_NAME=Gemma\nDOTCORE_MODEL_DEPLOYMENT_STATE=Pausing\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE=Paused\n" - ); + assert_eq!(text(&paused.stdout), "✔ Pausing Gemma\n"); assert_eq!(manager.model_deployment("model-1").desired_state(), Paused); let resumed = run(&manager, &["resume", "model-4"]); assert_eq!(resumed.status.code(), Some(0)); - assert_eq!( - text(&resumed.stdout), - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-4\nDOTCORE_MODEL_DEPLOYMENT_NAME=Mistral\nDOTCORE_MODEL_DEPLOYMENT_STATE=Paused\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE=Present\n" - ); + assert_eq!(text(&resumed.stderr), ""); + assert_eq!(text(&resumed.stdout), "✔ Resuming Mistral\n"); assert_eq!(manager.model_deployment("model-4").desired_state(), Present); assert_eq!( lifecycle_calls(&manager), @@ -321,10 +302,8 @@ fn teardown_with_yes_removes_the_deployment_and_prints_the_accepted_state() { let output = run(&manager, &["teardown", "Llama", "--yes"]); assert_eq!(output.status.code(), Some(0)); - assert_eq!( - text(&output.stdout), - "Model deployment\nDOTCORE_MODEL_DEPLOYMENT_ID=model-3\nDOTCORE_MODEL_DEPLOYMENT_NAME=Llama\nDOTCORE_MODEL_DEPLOYMENT_STATE=Tearing down\nDOTCORE_MODEL_DEPLOYMENT_DESIRED_STATE=Teardown\n" - ); + assert_eq!(text(&output.stderr), ""); + assert_eq!(text(&output.stdout), "✔ Tearing down Llama\n"); assert_eq!( manager.model_deployment("model-3").desired_state(), Teardown @@ -640,7 +619,10 @@ fn logs_of_an_unknown_deployment_fail_before_reading_any_log() { fn a_terminal_shows_the_list_as_a_table() { let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); - let Some(run) = run_in_pty(terminal_command(&manager, &["list"]), Session::new([])) else { + let Some(run) = run_in_pty( + terminal_command(&manager, &["list"]), + Session::new([]).with_stdout_on_terminal(), + ) else { return; }; @@ -663,13 +645,35 @@ fn a_terminal_shows_the_list_as_a_table() { } } +#[test] +fn a_terminal_session_writes_the_list_to_a_redirected_stdout() { + let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); + + let Some(run) = run_in_pty(terminal_command(&manager, &["list"]), Session::new([])) else { + return; + }; + + assert_eq!(run.code(), Some(0), "screen:\n{}", run.screen()); + assert_eq!( + run.stdout(), + " NAME ID STATE NODE MODEL\n\ + \x20 Gemma model-1 Ready gb10-host Gemma 4 E4B\n\ + \x20 Qwen model-2 Downloading gb10-host Gemma 4 E4B\n\ + \x20 Llama model-3 Failed gb10-host Gemma 4 E4B\n\ + \x20 Mistral model-4 Paused gb10-host Gemma 4 E4B\n\ + \x20 Phi model-5 Tearing down gb10-host Gemma 4 E4B\n" + ); + assert_eq!(run.stderr(), ""); + assert_eq!(run.screen().trim(), ""); +} + #[test] fn a_terminal_shows_the_details_of_one_deployment() { let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); let Some(run) = run_in_pty( terminal_command(&manager, &["show", "Qwen"]), - Session::new([]), + Session::new([]).with_stdout_on_terminal(), ) else { return; }; @@ -698,25 +702,115 @@ fn a_terminal_shows_the_details_of_one_deployment() { } #[test] -fn a_terminal_reports_a_pause_with_the_next_step() { +fn a_terminal_session_writes_the_details_to_a_redirected_stdout() { let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); let Some(run) = run_in_pty( - terminal_command(&manager, &["pause", "Gemma"]), + terminal_command(&manager, &["show", "Qwen"]), Session::new([]), ) else { return; }; + assert_eq!(run.code(), Some(0), "screen:\n{}", run.screen()); + assert_eq!( + run.stdout(), + "Model deployment Qwen\n\ + \x20 name Qwen\n\ + \x20 id model-2\n\ + \x20 state Downloading\n\ + \x20 desired Present\n\ + \x20 node gb10-host\n\ + \x20 target Simulated models\n\ + \x20 target id node-1-model\n\ + \x20 model Gemma 4 E4B\n\ + \x20 profile default\n\ + \x20 engine llama-cpp\n\ + \x20 progress 42%\n\ + \x20 message Fetching weights\n" + ); + assert_eq!(run.stderr(), ""); + assert_eq!(run.screen().trim(), ""); +} + +#[test] +fn a_terminal_reports_a_pause_without_a_next_step() { + let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); + + let Some(run) = run_in_pty( + terminal_command(&manager, &["pause", "Gemma"]), + Session::new([]).with_stdout_on_terminal(), + ) else { + return; + }; + assert_eq!(run.code(), Some(0), "screen:\n{}", run.screen()); assert_eq!(run.stdout(), ""); assert_eq!(run.stderr(), ""); - let lines = run.screen().lines().map(str::trim).collect::>(); - assert!(lines.contains(&"OK Pausing Gemma"), "{}", run.screen()); - assert!(lines.contains(&"dotc model list"), "{}", run.screen()); + assert_eq!(run.screen().trim(), "OK Pausing Gemma"); assert_eq!(manager.model_deployment("model-1").desired_state(), Paused); } +#[test] +fn a_terminal_session_writes_a_pause_to_a_redirected_stdout() { + let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); + + let Some(run) = run_in_pty( + terminal_command(&manager, &["pause", "Gemma"]), + Session::new([]), + ) else { + return; + }; + + assert_eq!(run.code(), Some(0), "screen:\n{}", run.screen()); + assert_eq!(run.stdout(), "OK Pausing Gemma\n"); + assert_eq!(run.stderr(), ""); + assert_eq!(run.screen().trim(), ""); + assert_eq!(manager.model_deployment("model-1").desired_state(), Paused); +} + +#[test] +fn a_color_terminal_styles_output_only_when_stdout_is_the_terminal() { + let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); + let colored = |stdout_on_terminal: bool| { + let mut command = terminal_command(&manager, &["pause", "Gemma"]); + command.env("TERM", "xterm-256color"); + let session = Session::new([]); + run_in_pty( + command, + if stdout_on_terminal { + session.with_stdout_on_terminal() + } else { + session + }, + ) + }; + + let (Some(on_terminal), Some(redirected)) = (colored(true), colored(false)) else { + return; + }; + + assert_eq!( + on_terminal.code(), + Some(0), + "screen:\n{}", + on_terminal.screen() + ); + assert!( + on_terminal.color_sgr_count() > 0, + "{}", + on_terminal.screen() + ); + assert_eq!( + redirected.code(), + Some(0), + "screen:\n{}", + redirected.screen() + ); + assert_eq!(redirected.color_sgr_count(), 0); + assert_eq!(redirected.stdout(), "OK Pausing Gemma\n"); +} + #[test] fn a_terminal_teardown_asks_and_removes_when_accepted() { let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); @@ -728,14 +822,18 @@ fn a_terminal_teardown_asks_and_removes_when_accepted() { "Tear down Gemma? This removes the deployment and its running workload resources. [no]", ), Step::Send(b"yes\n"), - Step::Wait("Tearing down Gemma"), ]), ) else { return; }; assert_eq!(run.code(), Some(0), "screen:\n{}", run.screen()); - assert_eq!(run.stdout(), ""); + assert_eq!(run.stdout(), "OK Tearing down Gemma\n"); + assert!( + !run.screen().contains("Tearing down Gemma"), + "{}", + run.screen() + ); assert_eq!(run.stderr(), ""); assert_eq!( manager.model_deployment("model-1").desired_state(), @@ -796,10 +894,7 @@ fn show_prints_visible_parameters_in_schema_order_with_secrets_masked() { assert_eq!(output.status.code(), Some(0)); let stdout = text(&output.stdout); assert!(!stdout.contains("s3cretKey"), "{stdout}"); - assert_eq!( - support::parameter_lines(&stdout, PARAMETER_PREFIX), - PARAMETER_LINES_MASKED - ); + assert_eq!(support::parameter_rows(&stdout), PARAMETER_ROWS_MASKED); } #[test] @@ -809,11 +904,8 @@ fn show_reveals_secret_parameters_with_the_flag() { let output = run(&manager, &["show", "Gemma", "--reveal-secrets"]); assert_eq!(output.status.code(), Some(0)); - let revealed = PARAMETER_LINES_MASKED.map(|line| line.replace("********", "s3cretKey")); - assert_eq!( - support::parameter_lines(&text(&output.stdout), PARAMETER_PREFIX), - revealed - ); + let revealed = PARAMETER_ROWS_MASKED.map(|line| line.replace("********", "s3cretKey")); + assert_eq!(support::parameter_rows(&text(&output.stdout)), revealed); } #[test] @@ -832,14 +924,8 @@ fn show_prints_the_upstream_api_key_masked_unless_revealed() { let revealed = text(&run(&manager, &["show", "Remote", "--reveal-secrets"]).stdout); assert!(!masked.contains("sk-remote"), "{masked}"); - assert_eq!( - support::parameter_lines(&masked, PARAMETER_PREFIX), - ["DOTCORE_MODEL_DEPLOYMENT_PARAMETER_API_KEY=********"] - ); - assert_eq!( - support::parameter_lines(&revealed, PARAMETER_PREFIX), - ["DOTCORE_MODEL_DEPLOYMENT_PARAMETER_API_KEY=sk-remote"] - ); + assert_eq!(support::parameter_rows(&masked), ["API key ********"]); + assert_eq!(support::parameter_rows(&revealed), ["API key sk-remote"]); } #[test] @@ -865,7 +951,7 @@ fn a_terminal_shows_parameters_under_their_own_heading() { let Some(run) = run_in_pty( terminal_command(&manager, &["show", "Gemma"]), - Session::new([]), + Session::new([]).with_stdout_on_terminal(), ) else { return; }; @@ -893,13 +979,389 @@ fn a_terminal_shows_parameters_under_their_own_heading() { ); } -const PARAMETER_PREFIX: &str = "DOTCORE_MODEL_DEPLOYMENT_PARAMETER_"; -const PARAMETER_LINES_MASKED: [&str; 5] = [ - "DOTCORE_MODEL_DEPLOYMENT_PARAMETER_FLASH_ATTENTION=true", - "DOTCORE_MODEL_DEPLOYMENT_PARAMETER_PARALLEL_REQUESTS=4", - "DOTCORE_MODEL_DEPLOYMENT_PARAMETER_EXPERT_CAP=24576 MiB", - "DOTCORE_MODEL_DEPLOYMENT_PARAMETER_TUNED_FLAG=false", - "DOTCORE_MODEL_DEPLOYMENT_PARAMETER_API_KEY=********", +#[test] +fn yaml_list_prints_the_manager_deployments_with_their_names_and_secrets_masked() { + let mut downloading = local_model_deployment("model-2", "Qwen", Downloading, Present); + downloading.state.as_mut().expect("seeded state").progress = Some(ModelDeploymentProgress { + percent: Some(42), + completed: 5_000_000_000, + ..Default::default() + }); + let mut upstream = local_model_deployment("model-9", "Remote", Ready, Present); + upstream.intent = None; + upstream.snapshot = Some(ModelDeploymentSnapshot { + source: Some(Source::Upstream(Default::default())), + }); + upstream.upstream_desired_configuration = Some(UpstreamModelDesiredConfiguration { + upstream_model_id: "gpt-remote".to_owned(), + api_key: "sk-remote".to_owned(), + ..Default::default() + }); + let manager = FakeManager::start(FakeState::with_models(vec![downloading, upstream])); + + let output = run(&manager, &["--yaml", "list"]); + + assert_eq!(text(&output.stderr), ""); + assert_eq!(output.status.code(), Some(0)); + assert_eq!( + support::yaml_documents(&text(&output.stdout)), + [json!({ + "deployments": [ + { + "modelDeploymentId": "model-2", + "modelDeploymentName": "Qwen", + "intent": { + "placement": { + "siteNodeId": "node-1", + "executionTargetId": "node-1-model", + }, + }, + "snapshot": { + "local": { + "modelId": "gemma-4-e4b", + "modelDisplayName": "Gemma 4 E4B", + "profileId": "default", + "engineArtifact": { "engineReleaseId": "llama-cpp" }, + }, + }, + "state": { + "status": "MODEL_DEPLOYMENT_STATUS_DOWNLOADING", + "progress": { "percent": 42, "completed": "5000000000" }, + }, + "desiredState": "MODEL_DEPLOYMENT_DESIRED_STATE_PRESENT", + "siteNodeDisplayName": "gb10-host", + "executionTargetDisplayName": "Simulated models", + }, + { + "modelDeploymentId": "model-9", + "modelDeploymentName": "Remote", + "snapshot": { "upstream": {} }, + "state": { "status": "MODEL_DEPLOYMENT_STATUS_READY" }, + "desiredState": "MODEL_DEPLOYMENT_DESIRED_STATE_PRESENT", + "upstreamDesiredConfiguration": { + "upstreamModelId": "gpt-remote", + "apiKey": "********", + }, + }, + ], + })] + ); +} + +#[test] +fn yaml_list_of_an_empty_site_is_an_empty_document() { + let manager = FakeManager::start(FakeState::with_models(Vec::new())); + + let output = run(&manager, &["list", "--yaml"]); + + assert_eq!(output.status.code(), Some(0)); + assert_eq!(support::yaml_documents(&text(&output.stdout)), [json!({})]); +} + +#[test] +fn yaml_show_prints_the_deployment_with_secret_values_masked_unless_revealed() { + let deployment = deployment_with_parameters(); + let manager = FakeManager::start(FakeState::with_models(vec![deployment.clone()])); + + let masked = run(&manager, &["show", "Gemma", "--yaml"]); + let revealed = run(&manager, &["show", "Gemma", "--yaml", "--reveal-secrets"]); + + assert_eq!(text(&masked.stderr), ""); + assert_eq!(masked.status.code(), Some(0)); + let mut revealed_document = serde_json::to_value(&deployment).expect("deployment mapping"); + revealed_document["siteNodeDisplayName"] = json!("gb10-host"); + revealed_document["executionTargetDisplayName"] = json!("Simulated models"); + let mut masked_document = revealed_document.clone(); + let api_key = masked_document["snapshot"]["local"]["engineParameterValues"]["values"] + .as_array_mut() + .expect("values") + .iter_mut() + .find(|value| value["parameterId"] == "api-key") + .expect("api key value"); + assert_eq!(api_key["string"], "s3cretKey"); + api_key["string"] = json!("********"); + assert_eq!( + support::yaml_documents(&text(&masked.stdout)), + [masked_document] + ); + + assert_eq!(revealed.status.code(), Some(0)); + assert_eq!( + support::yaml_documents(&text(&revealed.stdout)), + [revealed_document] + ); +} + +#[test] +fn yaml_logs_print_one_document_per_entry() { + let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); + manager.state().model_logs.page = log_page( + vec![ + log_source("server", DeploymentLogSourceState::Available), + log_source("proxy", DeploymentLogSourceState::Unavailable), + ], + vec![ + log_entry("server", 10, b"loading weights"), + log_entry("proxy", 11, b"listening"), + ], + ); + + let output = run(&manager, &["logs", "Gemma", "--yaml"]); + + assert_eq!(text(&output.stderr), "Proxy (proxy): unavailable\n"); + assert_eq!(output.status.code(), Some(0)); + let stdout = text(&output.stdout); + assert_eq!(stdout.lines().filter(|line| *line == "---").count(), 1); + assert_eq!( + support::yaml_documents(&stdout), + [ + json!({ + "sourceName": "server", + "sourceLabel": "Server", + "timestamp": { "seconds": "1794500010" }, + "content": "bG9hZGluZyB3ZWlnaHRz", + "text": "loading weights", + }), + json!({ + "sourceName": "proxy", + "sourceLabel": "Proxy", + "timestamp": { "seconds": "1794500011" }, + "content": "bGlzdGVuaW5n", + "text": "listening", + }), + ] + ); +} + +#[test] +fn yaml_logs_text_replaces_invalid_utf8_and_keeps_the_raw_content() { + let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); + manager.state().model_logs.page = log_page( + vec![log_source("server", DeploymentLogSourceState::Available)], + vec![log_entry("server", 10, b"bad \xff byte")], + ); + + let output = run(&manager, &["logs", "Gemma", "--yaml"]); + + assert_eq!(output.status.code(), Some(0)); + assert_eq!( + support::yaml_documents(&text(&output.stdout)), + [json!({ + "sourceName": "server", + "sourceLabel": "Server", + "timestamp": { "seconds": "1794500010" }, + "content": "YmFkIP8gYnl0ZQ==", + "text": "bad \u{fffd} byte", + })] + ); +} + +#[test] +fn yaml_logs_with_follow_stream_one_document_per_new_entry() { + let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); + { + let mut state = manager.state(); + state.model_logs.page = log_page( + vec![log_source("server", DeploymentLogSourceState::Available)], + vec![log_entry("server", 10, b"loading weights")], + ); + state.model_logs.follow = vec![ + Ok(follow_entry("server", 12, b"ready")), + Ok(follow_source("server", DeploymentLogSourceState::Ended)), + ]; + } + + let output = run(&manager, &["logs", "Gemma", "--follow", "--yaml"]); + + assert_eq!( + text(&output.stderr), + "Server (server): ended\nthe log follow of model deployment Gemma ended\n" + ); + assert_eq!(output.status.code(), Some(0)); + let contents = support::yaml_documents(&text(&output.stdout)) + .into_iter() + .map(|document| document["content"].clone()) + .collect::>(); + assert_eq!(contents, [json!("bG9hZGluZyB3ZWlnaHRz"), json!("cmVhZHk=")]); +} + +#[test] +fn a_yaml_failure_prints_nothing_on_stdout_and_the_plain_failure_on_stderr() { + let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); + manager.state().model_logs.page = log_page( + vec![log_source("server", DeploymentLogSourceState::Unavailable)], + vec![log_entry("server", 10, b"loading weights")], + ); + + let unknown = run(&manager, &["show", "nothing", "--yaml"]); + let unavailable = run(&manager, &["logs", "Gemma", "--yaml"]); + + assert_eq!(unknown.status.code(), Some(1)); + assert_eq!(text(&unknown.stdout), ""); + assert_eq!( + text(&unknown.stderr), + "no model deployment is named or has id \"nothing\"; see `dotc model list`\n" + ); + assert_eq!(unavailable.status.code(), Some(1)); + assert_eq!(text(&unavailable.stdout), ""); + assert_eq!( + text(&unavailable.stderr), + "every log source of model deployment Gemma is unavailable; its node may be unreachable\n" + ); +} + +#[test] +fn yaml_lifecycle_verbs_print_the_accepted_deployment_with_its_names() { + let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); + let document = |id: &str, name: &str, state: serde_json::Value, desired: &str| { + json!({ + "modelDeploymentId": id, + "modelDeploymentName": name, + "intent": { + "placement": { + "siteNodeId": "node-1", + "executionTargetId": "node-1-model", + }, + }, + "snapshot": { + "local": { + "modelId": "gemma-4-e4b", + "modelDisplayName": "Gemma 4 E4B", + "profileId": "default", + "engineArtifact": { "engineReleaseId": "llama-cpp" }, + }, + }, + "state": state, + "desiredState": desired, + "siteNodeDisplayName": "gb10-host", + "executionTargetDisplayName": "Simulated models", + }) + }; + + let paused = run(&manager, &["pause", "Gemma", "--yaml"]); + let resumed = run(&manager, &["resume", "model-4", "--yaml"]); + let torn_down = run(&manager, &["--yaml", "teardown", "model-2", "--yes"]); + + for output in [&paused, &resumed, &torn_down] { + assert_eq!(text(&output.stderr), ""); + assert_eq!(output.status.code(), Some(0)); + } + assert_eq!( + support::yaml_documents(&text(&paused.stdout)), + [document( + "model-1", + "Gemma", + json!({ "status": "MODEL_DEPLOYMENT_STATUS_READY" }), + "MODEL_DEPLOYMENT_DESIRED_STATE_PAUSED" + )] + ); + assert_eq!( + support::yaml_documents(&text(&resumed.stdout)), + [document( + "model-4", + "Mistral", + json!({ "status": "MODEL_DEPLOYMENT_STATUS_PAUSED" }), + "MODEL_DEPLOYMENT_DESIRED_STATE_PRESENT" + )] + ); + assert_eq!( + support::yaml_documents(&text(&torn_down.stdout)), + [document( + "model-2", + "Qwen", + json!({ + "status": "MODEL_DEPLOYMENT_STATUS_UNLOADING", + "statusMessage": "Fetching weights", + "progress": { "percent": 42 }, + }), + "MODEL_DEPLOYMENT_DESIRED_STATE_TEARDOWN" + )] + ); + assert_eq!( + lifecycle_calls(&manager), + vec![ + call(Rpc::PauseModel, Some("model-1")), + call(Rpc::ResumeModel, Some("model-4")), + call(Rpc::RemoveModelDeployment, Some("model-2")), + ] + ); +} + +#[test] +fn yaml_lifecycle_masks_upstream_secrets() { + let mut upstream = local_model_deployment("model-9", "Remote", Ready, Present); + upstream.intent = None; + upstream.snapshot = Some(ModelDeploymentSnapshot { + source: Some(Source::Upstream(Default::default())), + }); + upstream.upstream_desired_configuration = Some(UpstreamModelDesiredConfiguration { + upstream_model_id: "gpt-remote".to_owned(), + api_key: "sk-remote".to_owned(), + ..Default::default() + }); + let manager = FakeManager::start(FakeState::with_models(vec![upstream])); + + let output = run(&manager, &["pause", "Remote", "--yaml"]); + + assert_eq!(text(&output.stderr), ""); + assert_eq!( + support::yaml_documents(&text(&output.stdout)), + [json!({ + "modelDeploymentId": "model-9", + "modelDeploymentName": "Remote", + "snapshot": { "upstream": {} }, + "state": { "status": "MODEL_DEPLOYMENT_STATUS_READY" }, + "desiredState": "MODEL_DEPLOYMENT_DESIRED_STATE_PAUSED", + "upstreamDesiredConfiguration": { + "upstreamModelId": "gpt-remote", + "apiKey": "********", + }, + })] + ); +} + +#[test] +fn yaml_teardown_without_yes_fails_naming_the_flag_without_calling_the_manager() { + let manager = FakeManager::start(FakeState::with_models(mixed_deployments())); + + let output = run(&manager, &["teardown", "Llama", "--yaml"]); + + assert_eq!(output.status.code(), Some(1)); + assert_eq!(text(&output.stdout), ""); + assert_eq!( + text(&output.stderr), + "tearing down a model deployment needs confirmation, which --yaml never asks for; pass --yes to tear it down\n" + ); + assert_eq!(manager.calls(), Vec::new()); +} + +#[test] +fn yaml_is_refused_by_the_commands_that_have_no_result_to_print() { + for arguments in [ + &["--yaml", "server", "start"][..], + &["--yaml", "code", "opencode"][..], + ] { + let output = isolated_dotc() + .args(arguments) + .output() + .expect("run a command without a YAML result"); + + assert_eq!(output.status.code(), Some(2), "{arguments:?}"); + assert_eq!(text(&output.stdout), "", "{arguments:?}"); + assert!( + text(&output.stderr).starts_with("error: --yaml is not available for this command\n"), + "{arguments:?}: {}", + text(&output.stderr) + ); + } +} + +const PARAMETER_ROWS_MASKED: [&str; 5] = [ + "Flash attention true", + "Parallel requests 4", + "Expert cap 24576 MiB", + "Tuned flag false", + "API key ********", ]; /// A local deployment whose schema has a default flag, a plain integer, a sized integer, a flag diff --git a/backend/cli/tests/site_reset_docker_integration.rs b/backend/cli/tests/site_reset_docker_integration.rs index a746c0ec..3c858f67 100644 --- a/backend/cli/tests/site_reset_docker_integration.rs +++ b/backend/cli/tests/site_reset_docker_integration.rs @@ -283,10 +283,7 @@ fn hw_docker_node_leave_removes_only_the_joined_nodes_resources_on_a_shared_daem assert_success("dotc node leave", &output); assert_eq!( String::from_utf8_lossy(&output.stdout), - format!( - "Node left\nDOTCORE_SITE_ID={}\nDOTCORE_NODE_ID={}\n", - fixture.site_id, fixture.worker_node_id - ) + format!("✔ Left {}\n", fixture.site_id) ); assert!(!fixture.node_dir.exists()); assert!(!docker_succeeds(&[ diff --git a/backend/cli/tests/support/mod.rs b/backend/cli/tests/support/mod.rs index 49211b27..f070a59f 100644 --- a/backend/cli/tests/support/mod.rs +++ b/backend/cli/tests/support/mod.rs @@ -41,15 +41,32 @@ pub fn canonical_tempdir() -> std::io::Result { tempfile::tempdir_in(canonical_temp_dir()) } -/// The lines of a record block whose key starts with the given prefix, such as one deployment's -/// parameters. +/// The rows under the `Parameters` heading of a shown deployment, one per parameter with its +/// whitespace collapsed, such as `Memory limit 2048 MB`. #[allow( dead_code, - reason = "only the deployment contracts read parameter records" + reason = "only the deployment contracts read parameter rows" )] -pub fn parameter_lines<'a>(stdout: &'a str, prefix: &str) -> Vec<&'a str> { +pub fn parameter_rows(stdout: &str) -> Vec { stdout .lines() - .filter(|line| line.starts_with(prefix)) + .skip_while(|line| *line != "Parameters") + .skip(1) + .map(|line| line.split_whitespace().collect::>().join(" ")) + .filter(|line| !line.is_empty()) + .collect() +} + +/// Parses stdout as a stream of YAML documents, each as the JSON value it maps to, so a test +/// compares whole documents field by field. +#[allow( + dead_code, + reason = "only the deployment contracts read YAML documents" +)] +pub fn yaml_documents(stdout: &str) -> Vec { + use serde::Deserialize; + + serde_yaml_ng::Deserializer::from_str(stdout) + .map(|document| serde_json::Value::deserialize(document).expect("YAML document")) .collect() } diff --git a/backend/cli/tests/support/pty.rs b/backend/cli/tests/support/pty.rs index ff2ba7a1..3fa6e242 100644 --- a/backend/cli/tests/support/pty.rs +++ b/backend/cli/tests/support/pty.rs @@ -2,8 +2,8 @@ //! an operator would: it waits for text on an emulated screen, answers cursor-position //! queries, and sends keystrokes. Waits and the whole-session view also see text that already //! scrolled off the screen, so assertions do not depend on how much the command printed. The -//! command's own stdout and stderr stay piped unless a session asks for stderr on the -//! terminal, so tests can prove that guided output reaches only the terminal. +//! command's own stdout and stderr stay piped unless a session puts them on the terminal, so +//! tests can tell what reaches stdout from what reaches only the terminal. use std::{ fs::File, @@ -56,6 +56,7 @@ pub enum Stdin { /// A scripted terminal session. pub struct Session { stdin: Stdin, + stdout_on_terminal: bool, stderr_on_terminal: bool, cursor_position_answers: usize, steps: Vec, @@ -66,6 +67,7 @@ impl Session { pub fn new(steps: impl IntoIterator) -> Self { Self { stdin: Stdin::Pty, + stdout_on_terminal: false, stderr_on_terminal: false, cursor_position_answers: usize::MAX, steps: steps.into_iter().collect(), @@ -78,6 +80,13 @@ impl Session { self } + /// Sends the command's stdout to the terminal, as an interactive shell would, instead of + /// piping it; `stdout()` is then empty and the text appears on the screen. + pub fn with_stdout_on_terminal(mut self) -> Self { + self.stdout_on_terminal = true; + self + } + /// Sends the command's stderr to the terminal, as an interactive shell would, instead of /// piping it; `stderr()` is then empty and the text appears on the screen. pub fn with_stderr_on_terminal(mut self) -> Self { @@ -220,7 +229,11 @@ pub fn run_in_pty(mut command: Command, session: Session) -> Option { // The test timing bounds the wait on a terminal that never answers a cursor query. command.env(TEST_TIMING_ENVIRONMENT, Timing::test().to_environment()); - command.stdout(Stdio::piped()); + if session.stdout_on_terminal { + command.stdout(Stdio::from(slave.try_clone().expect("clone pty slave"))); + } else { + command.stdout(Stdio::piped()); + } if session.stderr_on_terminal { command.stderr(Stdio::from(slave.try_clone().expect("clone pty slave"))); } else { @@ -237,23 +250,7 @@ pub fn run_in_pty(mut command: Command, session: Session) -> Option { slave_raw } }; - // SAFETY: the closure calls only async-signal-safe session and ioctl operations before - // exec. - unsafe { - command.pre_exec(move || { - #[cfg(target_os = "macos")] - let request: libc::c_ulong = libc::TIOCSCTTY.into(); - #[cfg(not(target_os = "macos"))] - let request = libc::TIOCSCTTY; - if libc::setsid() == -1 || libc::ioctl(controlling_fd, request, 0) == -1 { - return Err(std::io::Error::last_os_error()); - } - if controlling_fd != 0 { - libc::close(controlling_fd); - } - Ok(()) - }); - } + become_controlling_terminal(&mut command, controlling_fd); let command_line = command_line(&command); let terminal = Arc::new(Mutex::new(Terminal::new())); @@ -325,6 +322,47 @@ pub fn run_in_pty(mut command: Command, session: Session) -> Option { }) } +/// A pseudo-terminal given to a command as its controlling terminal; keep it until the command +/// exits. +pub struct ControllingTerminal { + _master: File, + _slave: File, +} + +/// Gives the command a pseudo-terminal as its controlling terminal and null stdin, while stdout +/// and stderr stay as configured; `None` when pseudo-terminals are unavailable. +pub fn attach_controlling_terminal(command: &mut Command) -> Option { + let (master, slave) = open_pty()?; + command.stdin(Stdio::null()); + become_controlling_terminal(command, slave.as_raw_fd()); + Some(ControllingTerminal { + _master: master, + _slave: slave, + }) +} + +/// Makes `controlling_fd`, a pty slave descriptor open in the child, the child's controlling +/// terminal in a new session, closing it unless it is stdin. +fn become_controlling_terminal(command: &mut Command, controlling_fd: RawFd) { + // SAFETY: the closure calls only async-signal-safe session and ioctl operations before + // exec. + unsafe { + command.pre_exec(move || { + #[cfg(target_os = "macos")] + let request: libc::c_ulong = libc::TIOCSCTTY.into(); + #[cfg(not(target_os = "macos"))] + let request = libc::TIOCSCTTY; + if libc::setsid() == -1 || libc::ioctl(controlling_fd, request, 0) == -1 { + return Err(std::io::Error::last_os_error()); + } + if controlling_fd != 0 { + libc::close(controlling_fd); + } + Ok(()) + }); + } +} + /// Opens a `ROWS` by `COLS` pseudo-terminal pair, or returns `None` after printing a skip /// notice when the environment forbids it. fn open_pty() -> Option<(File, File)> { diff --git a/backend/cli/tests/support/simulated_manager.rs b/backend/cli/tests/support/simulated_manager.rs index 59496d26..336dc575 100644 --- a/backend/cli/tests/support/simulated_manager.rs +++ b/backend/cli/tests/support/simulated_manager.rs @@ -206,7 +206,7 @@ fn initialize_site() -> PathBuf { std::fs::write( site.join("site.yaml"), format!( - "siteId: {SITE_ID}\nnodes:\n- nodeId: {NODE_ID}\n host: 127.0.0.2\n displayName: {NODE_NAME}\n siteManager: {{}}\nexecutionTargets:\n- executionTargetId: {APPLICATION_TARGET_ID}\n siteNodeId: {NODE_ID}\n displayName: {APPLICATION_TARGET_ID}\n platform: {{ operatingSystem: linux, architecture: amd64 }}\n applicationRuntime: {{ simulatedRuntime: {{}} }}\nmodelDeployments: []\nmodelDeploymentIdentityAllocator:\n namespace: 6c1a9f0e2b7d4c13\n nextSequence: '1'\ninferenceRoutes: []\napplicationDeployments: []\n" + "siteId: {SITE_ID}\nnodes:\n- nodeId: {NODE_ID}\n host: 127.0.0.2\n displayName: {NODE_NAME}\n siteManager: {{}}\nexecutionTargets:\n- executionTargetId: {APPLICATION_TARGET_ID}\n siteNodeId: {NODE_ID}\n displayName: {APPLICATION_TARGET_ID}\n platform: {{ operatingSystem: linux, architecture: amd64 }}\n applicationRuntime: {{ simulatedRuntime: {{}} }}\nmodelDeployments: []\ndeploymentIdentityAllocator:\n suffixKey: 6c1a9f0e2b7d4c13\n nextSequence: '1'\ninferenceRoutes: []\napplicationDeployments: []\n" ), ) .expect("desired site"); diff --git a/backend/site/src/membership/management.rs b/backend/site/src/membership/management.rs index 549d0dae..62aff6f9 100644 --- a/backend/site/src/membership/management.rs +++ b/backend/site/src/membership/management.rs @@ -178,8 +178,8 @@ impl SiteMembershipService for MembershipManagementService { } } -/// Projects what a removal changes. -fn removal_plan(plan: &NodeRemovalPlan) -> MachineRemovalPlan { +/// Projects what a removal changes as the management API reports it. +pub fn removal_plan(plan: &NodeRemovalPlan) -> MachineRemovalPlan { MachineRemovalPlan { node_id: plan.node.node_id.clone(), display_name: plan.node.display_name.clone(), diff --git a/backend/site/src/membership/mod.rs b/backend/site/src/membership/mod.rs index 5124688f..bc6733a6 100644 --- a/backend/site/src/membership/mod.rs +++ b/backend/site/src/membership/mod.rs @@ -22,7 +22,7 @@ pub use list::{ListedNode, ListedTarget, NodeListError, SiteNodeListing, list_si pub use live_removal::{ MachineRemoval, MachineRemovalError, MachineRemovalOutcome, NodeConnectivity, }; -pub use management::MembershipManagementService; +pub use management::{MembershipManagementService, removal_plan}; pub use offline::{OfflineSite, OfflineSiteError}; pub use recorder::MembershipRecorder; pub use removal::{ diff --git a/docs/usage.md b/docs/usage.md index fa425244..a1d8b4db 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -16,6 +16,11 @@ This guide starts with your first model and ends with a site on several machines - `dotc model` and `dotc app` list, pause, resume, observe and remove deployments. - `dotc hardware` prints this machine's hardware for bug reports (`show`) and recommends models for it (`recommend`), without a site. +Commands print results on stdout and errors on stderr, and ask questions on the terminal. + +- In scripts and agents, add `--yaml`: the result is one YAML document on stdout. The command never asks a question, so pass `--yes` where it would ask for confirmation. Commands with no result to print, such as `dotc server start`, `dotc code` and `dotc dev`, refuse `--yaml`. +- When a command fails, it says what went wrong and which commands can fix it. + ## Use it from your tools Each route is an OpenAI-compatible endpoint, and its route name is the `model` your client asks for. From 7992495a467974b31c94f6a09b5dd536e7b52ce5 Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 11:25:23 -0500 Subject: [PATCH 05/19] refactor(dev): read dotc --yaml output in cluster recipes and launcher --- dev/cluster/Justfile | 6 +++--- dev/cluster/cluster.test.mjs | 21 +++++++++++---------- nix/all-in-one/default.nix | 4 ++-- nix/all-in-one/launcher.sh | 13 ++++++------- 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/dev/cluster/Justfile b/dev/cluster/Justfile index 9c0d4bad..eb122e1a 100644 --- a/dev/cluster/Justfile +++ b/dev/cluster/Justfile @@ -58,7 +58,7 @@ join target *args: added="$(mktemp)" mkdir -p "$(dirname "$token_file")" rm -f "$token_file" - dotc node add --site-dir "$DOTCORE_SITE_DIR" --yes --token-file "$token_file" > "$added" & + dotc --yaml node add --site-dir "$DOTCORE_SITE_DIR" --yes --token-file "$token_file" > "$added" & add_pid=$! trap 'kill "$add_pid" 2>/dev/null || true; rm -f "$token_file" "$added"' EXIT for _ in $(seq 1 600); do @@ -86,7 +86,7 @@ join target *args: step 'wait for node add' wait "$add_pid" || fail 'node add' cat "$added" - record_node_id "$target" "$(sed -n 's/^DOTCORE_NODE_ID=//p' "$added")" + record_node_id "$target" "$(sed -n 's/^nodeId: //p' "$added")" trap - EXIT rm -f "$token_file" "$added" @@ -168,7 +168,7 @@ clean target="": # The worker stops first, so a running manager accepts forgetting its deployments. stop_worker "$target" leave_worker "$target" || { echo "cluster clean: the worker on $target did not leave" >&2; exit 1; } - if test -n "$node_id" && test -e "$DOTCORE_SITE_DIR" && dotc node list --site-dir "$DOTCORE_SITE_DIR" | grep -qx "DOTCORE_NODE_ID=$node_id"; then + if test -n "$node_id" && test -e "$DOTCORE_SITE_DIR" && dotc --yaml node list --site-dir "$DOTCORE_SITE_DIR" | grep -qx " nodeId: $node_id"; then dotc node remove --site-dir "$DOTCORE_SITE_DIR" "$node_id" --forget-deployments ${yes_args[@]+"${yes_args[@]}"} elif test -z "$node_id" && test -e "$DOTCORE_SITE_DIR"; then # Without a manager site there is no node left to remove, so only an existing site needs a check. diff --git a/dev/cluster/cluster.test.mjs b/dev/cluster/cluster.test.mjs index 9ed11262..6b045529 100644 --- a/dev/cluster/cluster.test.mjs +++ b/dev/cluster/cluster.test.mjs @@ -24,11 +24,11 @@ test("join local builds, records the target, hands the token over and records th const tokenFile = `${f.workerDir}.join-token`; assert.deepEqual(await f.calls(), [ "nix build .#dotc --no-link", - `dotc node add --site-dir ${f.site} --yes --token-file ${tokenFile}`, + `dotc --yaml node add --site-dir ${f.site} --yes --token-file ${tokenFile}`, `dotc node join --site-dir ${f.workerDir} --token-file ${tokenFile} --name Worker one --inference simulated --applications docker --host 127.0.0.2 --private-port 61053 --yes`, ]); assert.match(joined.stderr, /cluster join local: prepare\n(.*\n)*cluster join local: token\n(.*\n)*cluster join local: join on local\n(.*\n)*cluster join local: wait for node add/); - assert.match(joined.stdout, /^DOTCORE_NODE_ID=node-1$/m); + assert.match(joined.stdout, /^nodeId: node-1$/m); assert.equal(await f.record(), "local node-1\n"); assert.equal((await stat(f.workerDir)).mode & 0o777, 0o700); await assert.rejects(stat(tokenFile), { code: "ENOENT" }); @@ -87,7 +87,7 @@ test("join on a remote host resolves it, prepares through run and joins through assert.equal(joined.status, 0, joined.stderr); const calls = await f.calls(); assert.deepEqual(calls.slice(0, 2), ["remote resolve gb10", "remote run gb10:spark dev::cluster::_worker-prepare"]); - assert.match(calls[2], /^dotc node add .*--token-file /); + assert.match(calls[2], /^dotc --yaml node add .*--token-file /); assert.equal(calls[3], "remote exec gb10:spark just dev::cluster::_worker-join --token 'secret-token' '--name' 'Spark one' '--note' 'it'\\''s'"); assert.equal(calls.length, 4); // The remote shell re-parses the command, so every argument survives as one word. @@ -180,7 +180,7 @@ test("clean with a target makes that worker leave and removes its node while the "remote resolve gb10", "remote exec gb10:spark just dev::cluster::_worker-down", "remote exec gb10:spark DOTCORE_YES=1 just dev::cluster::_worker-leave", - `dotc node list --site-dir ${f.site}`, + `dotc --yaml node list --site-dir ${f.site}`, `dotc node remove --site-dir ${f.site} node-2 --forget-deployments --yes`, ]); assert.equal(await f.record(), "local node-1\n"); @@ -266,7 +266,7 @@ test("remote clean removes the host's worker through the cluster, then the remot "remote resolve gb10:spark", "remote exec gb10:spark just dev::cluster::_worker-down", "remote exec gb10:spark DOTCORE_YES=1 just dev::cluster::_worker-leave", - `dotc node list --site-dir ${f.site}`, + `dotc --yaml node list --site-dir ${f.site}`, `dotc node remove --site-dir ${f.site} node-2 --forget-deployments --yes`, "remote clean gb10:spark", ]); @@ -379,7 +379,7 @@ test("remote clean in a terminal shows what it removes and asks once before any "remote resolve gb10:spark", "remote exec gb10:spark just dev::cluster::_worker-down", "remote exec gb10:spark DOTCORE_YES=1 just dev::cluster::_worker-leave", - `dotc node list --site-dir ${f.site}`, + `dotc --yaml node list --site-dir ${f.site}`, `dotc node remove --site-dir ${f.site} node-2 --forget-deployments --yes`, "remote clean gb10:spark", ]); @@ -440,7 +440,7 @@ test("two-node-init joins a local worker, and the local worker stops and leaves const allCalls = await f.calls(); const started = allCalls.findIndex((call) => call.startsWith("process-compose") && call.endsWith("--detached")); assert.ok(started > allCalls.findIndex((call) => call.startsWith("dotc site init")), allCalls.join("\n")); - assert.ok(started < allCalls.findIndex((call) => call.startsWith("dotc node add")), allCalls.join("\n")); + assert.ok(started < allCalls.findIndex((call) => call.startsWith("dotc --yaml node add")), allCalls.join("\n")); const again = f.run("dev::cluster::two-node-init", "simulated", "docker"); assert.equal(again.status, 2); @@ -460,7 +460,7 @@ test("two-node-init joins a local worker, and the local worker stops and leaves // The worker's workloads stop through the node leave rather than being orphaned by a plain removal. assert.deepEqual((await f.calls()).filter((call) => call.startsWith("dotc")), [ `dotc node leave --site-dir ${f.workerDir}`, - `dotc node list --site-dir ${f.site}`, + `dotc --yaml node list --site-dir ${f.site}`, `dotc node remove --site-dir ${f.site} node-1 --forget-deployments`, ]); assert.equal(await f.exists(f.workerDir), false); @@ -524,6 +524,7 @@ async function fixture(t) { // node add publishes its token, waits for the join, then reports the next node id, as the real command does. await stub("dotc", `printf 'dotc %s\\n' "$*" >> "$TEST_CALLS" previous="" +test "$1" != --yaml || shift for argument in "$@"; do case "$previous" in --token-file) token_file="$argument" ;; @@ -539,13 +540,13 @@ case "$*" in rm -f "$TEST_JOINED" id="node-$(( $(cat "$TEST_NODES" 2>/dev/null | wc -l) + 1 ))" echo "$id" >> "$TEST_NODES" - printf 'Node added\\nDOTCORE_NODE_ID=%s\\n' "$id" ;; + printf 'outcome: added\\nnodeId: %s\\n' "$id" ;; "node join"*) printf '%s\\n' "\${DOTCORE_MACHINE_HOST-unset}" > "$TEST_JOIN_MACHINE_HOST" mkdir -m 700 -p "$site_dir" printf 'joined node\\n' > "$site_dir/worker.yaml" touch "$TEST_JOINED" ;; - "node list"*) sed 's/^/DOTCORE_NODE_ID=/' "$TEST_NODES" ;; + "node list"*) printf 'nodes:\\n'; sed 's/^/- node:\\n nodeId: /' "$TEST_NODES" ;; "node remove"*) id="$5"; grep -vx "$id" "$TEST_NODES" > "$TEST_NODES.tmp" || true; mv "$TEST_NODES.tmp" "$TEST_NODES" ;; "node leave"*|"site delete"*) rm -rf "$site_dir" ;; "site init"*) mkdir -p "$site_dir" ;; diff --git a/nix/all-in-one/default.nix b/nix/all-in-one/default.nix index f3d895ca..f2fada25 100644 --- a/nix/all-in-one/default.nix +++ b/nix/all-in-one/default.nix @@ -41,7 +41,7 @@ let caddy frontend.runtimeConfig pkgs.coreutils - pkgs.jq + pkgs.yq-go ]; derivationArgs = { postCheck = '' @@ -113,7 +113,7 @@ let set -euo pipefail if [[ " $* " == *" config show "* ]]; then printf '%s\n' "''${DOTCORE_PACKAGED_SOURCE_FLAKE-unset}" > "''${DOTCORE_PACKAGE_SOURCE_FILE:?}" - printf '%s\n' '{"role":"bogus","siteDir":"/site","masterCatalogDir":"/catalog","cacheDir":"/cache"}' + printf '%s\n' 'role: bogus' 'siteDir: /site' 'masterCatalogDir: /catalog' 'cacheDir: /cache' exit 0 fi printf '%s\n' "unexpected command: $*" >&2 diff --git a/nix/all-in-one/launcher.sh b/nix/all-in-one/launcher.sh index b16cbe3c..02972e7d 100644 --- a/nix/all-in-one/launcher.sh +++ b/nix/all-in-one/launcher.sh @@ -395,14 +395,13 @@ runtime_root="$(mktemp -d "$runtime_parent/dotcore.XXXXXXXX")" chmod 0700 "$runtime_root" umask "$old_umask" -config_file="$runtime_root/effective-config.json" -if ! run_tracked "$dotc_command" ${path_args[@]+"${path_args[@]}"} config show --format json >"$config_file"; then +config_file="$runtime_root/effective-config.yaml" +if ! run_tracked "$dotc_command" ${path_args[@]+"${path_args[@]}"} --yaml config show >"$config_file"; then echo "dotcore: cannot inspect effective process paths" >&2 exit 1 fi -config_json="$(cat "$config_file")" -site_dir="$(jq -er '.siteDir | strings' <<< "$config_json")" -role="$(jq -er '.role | strings' <<< "$config_json")" || role="" +site_dir="$(yq -e '.siteDir' "$config_file")" +role="$(yq -e '.role' "$config_file")" || role="" # The backend owns role detection. A joined node folder runs the backend alone: it has no console, # Caddy, or public listeners, only the private listener its folder declares. @@ -452,11 +451,11 @@ if [[ ! -f "$site_dir/site.yaml" || ! -f "$site_dir/node.yaml" ]]; then fi # The public listeners bind the node host the site records, which setup chooses on a first run. -if ! run_tracked "$dotc_command" ${path_args[@]+"${path_args[@]}"} config show --format json >"$config_file"; then +if ! run_tracked "$dotc_command" ${path_args[@]+"${path_args[@]}"} --yaml config show >"$config_file"; then echo "dotcore: cannot read the node host of the site" >&2 exit 1 fi -if ! node_host="$(jq -er '.nodeHost | strings' "$config_file")"; then +if ! node_host="$(yq -e '.nodeHost' "$config_file")"; then echo "dotcore: the site at $site_dir records no node host; run dotc site validate --site-dir $site_dir" >&2 exit 1 fi From 3a6583e0c414a08e597aa20087dc27285340a6f0 Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 11:25:23 -0500 Subject: [PATCH 06/19] refactor(installer): read dotc config through --yaml --- installer/install.sh | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/installer/install.sh b/installer/install.sh index f0dc8803..940878df 100755 --- a/installer/install.sh +++ b/installer/install.sh @@ -580,10 +580,10 @@ locate_site() { site_dir=$(default_site_dir) cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/dotcore" site_role=manager - if [ -n "$dotc_command" ] && config=$("$dotc_command" config show --format json 2>/dev/null); then - site_dir=$(json_field "$config" siteDir) - cache_dir=$(json_field "$config" cacheDir) - site_role=$(json_field "$config" role) + if [ -n "$dotc_command" ] && config=$("$dotc_command" --yaml config show 2>/dev/null); then + site_dir=$(yaml_field "$config" siteDir) + cache_dir=$(yaml_field "$config" cacheDir) + site_role=$(yaml_field "$config" role) elif [ -f "$site_dir/worker.yaml" ]; then site_role=joined-node fi @@ -685,10 +685,10 @@ dotcore_running() { pgrep -u "$(id -u)" -f '/bin/dotcore( |$)' >/dev/null 2>&1 } -# Prints a string field of a one-line JSON object; enough for dotc's own output, whose paths hold -# no escaped quotes. -json_field() { - printf '%s\n' "$1" | sed -n "s/.*\"$2\":\"\([^\"]*\)\".*/\1/p" +# Prints a top-level string field of a flat YAML document, without its quotes; enough for dotc's +# own output, whose paths hold no quote characters. +yaml_field() { + printf '%s\n' "$1" | sed -n "s/^$2: *//p" | sed -e "s/^'\(.*\)'\$/\1/" -e 's/^"\(.*\)"$/\1/' } folder_size() { From 423687e4cb7983e99d3d2cb7317b9353945dc5b0 Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 12:59:46 -0500 Subject: [PATCH 07/19] feat(backend): resolve dotc references by name, prefix or id part --- backend/AGENTS.md | 2 +- backend/cli/src/application/projection.rs | 8 +- backend/cli/src/code/mod.rs | 4 +- backend/cli/src/code/selection.rs | 67 ++- backend/cli/src/failure.rs | 150 +++++- backend/cli/src/hint.rs | 24 +- backend/cli/src/lib.rs | 1 + backend/cli/src/management/deployment.rs | 9 +- backend/cli/src/management/mod.rs | 193 +------ backend/cli/src/model/projection.rs | 8 +- backend/cli/src/node/remove.rs | 99 ++-- backend/cli/src/reference.rs | 482 ++++++++++++++++++ backend/cli/tests/application_contract.rs | 35 +- .../cli/tests/application_manager_contract.rs | 4 +- backend/cli/tests/code_contract.rs | 2 +- backend/cli/tests/command_contract.rs | 65 ++- backend/cli/tests/model_contract.rs | 40 +- docs/usage.md | 1 + 18 files changed, 880 insertions(+), 314 deletions(-) create mode 100644 backend/cli/src/reference.rs diff --git a/backend/AGENTS.md b/backend/AGENTS.md index 83ec0062..493a0361 100644 --- a/backend/AGENTS.md +++ b/backend/AGENTS.md @@ -121,7 +121,7 @@ backend/ - 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 (`management::resolve`); never match names or IDs by hand. A reference matching several objects fails and lists them. +- 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`. 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/code/mod.rs b/backend/cli/src/code/mod.rs index faca6d56..f4e00253 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, 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/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/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 3c4bb8dd..2ea4245e 100644 --- a/backend/cli/src/lib.rs +++ b/backend/cli/src/lib.rs @@ -33,6 +33,7 @@ mod node; mod output; mod parameters; mod paths; +mod reference; mod runtime_confirmation; mod server; mod site; diff --git a/backend/cli/src/management/deployment.rs b/backend/cli/src/management/deployment.rs index b1aa990e..c44c6892 100644 --- a/backend/cli/src/management/deployment.rs +++ b/backend/cli/src/management/deployment.rs @@ -11,18 +11,19 @@ use serde::Serialize; use tonic::Status; use super::{ - Addressable, DeploymentDocument, DeploymentGroup, ManagementError, Manager, ManagerArgs, - call_failed, resolve, single_line, + DeploymentDocument, DeploymentGroup, ManagementError, Manager, ManagerArgs, call_failed, + single_line, }; use crate::{ 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 + Serialize { +pub(crate) trait ManagedDeployment: Referable + Clone + Serialize { /// The command group the kind belongs to. const GROUP: DeploymentGroup; @@ -101,7 +102,7 @@ pub(crate) async fn find_deployment( reference: &str, ) -> anyhow::Result { 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. diff --git a/backend/cli/src/management/mod.rs b/backend/cli/src/management/mod.rs index b041e8cd..77967344 100644 --- a/backend/cli/src/management/mod.rs +++ b/backend/cli/src/management/mod.rs @@ -1,10 +1,8 @@ //! 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; @@ -278,56 +276,6 @@ impl DeploymentGroup { } } -/// 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 /// the request in operator words, for example `call_failed(DeploymentGroup::Model, "pause Gemma")`. pub(crate) fn call_failed( @@ -403,23 +351,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}; @@ -433,62 +364,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!( @@ -577,78 +458,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/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/node/remove.rs b/backend/cli/src/node/remove.rs index aca03fad..57f8b947 100644 --- a/backend/cli/src/node/remove.rs +++ b/backend/cli/src/node/remove.rs @@ -9,14 +9,16 @@ //! connected. Asked for YAML, the command never asks, so it needs `--yes`, and prints the //! manager's removal response, which the stopped site's removal reports in the same shape. +use std::path::Path; + use anyhow::Context; use clap::Args; use dotcore::model::engine::declaration_validator; use dotcore_proto::{ dotcore::site::v1::{ - ExecutionTarget, ListMachinesRequest, MachineRemovalDeployment, + ExecutionTarget, ListMachinesRequest, Machine, MachineRemovalDeployment, MachineRemovalDeploymentKind, MachineRemovalPlan, MachineRemovalRefusal, - RemoveMachineRequest, RemoveMachineResponse, execution_target::RuntimeBinding, + RemoveMachineRequest, RemoveMachineResponse, SiteNode, execution_target::RuntimeBinding, remove_machine_response, }, google::protobuf::Empty, @@ -25,8 +27,8 @@ use dotcore_site::{ SITE_FILE, initial::validation::SiteInputBundleValidator, membership::{ - NodeRemoval, NodeRemovalPlan, OfflineSite, OfflineSiteError, looks_like_node_id, - removal_plan, + NodeRemoval, NodeRemovalPlan, OfflineSite, OfflineSiteError, list_site_nodes, + looks_like_node_id, removal_plan, }, }; @@ -35,6 +37,7 @@ use crate::{ RootPathArgs, management::{ManagementError, ManagerArgs, single_line}, output::{OutputFormat, require_consent, write_yaml}, + reference::{Referable, ReferenceError, ReferenceKind, resolve}, terminal::{ConfirmPrompt, Message, PromptError, Terminal, open_terminal}, }; @@ -72,21 +75,21 @@ pub(crate) async fn node_remove( "removing a node needs a terminal; run in a terminal or pass --yes to remove it without confirmation", "removing a node needs confirmation, which --yaml never asks for; pass --yes to remove it", )?; - match open_stopped_site(paths)? { - Some(site) => remove_from_stopped_site(&site, &arguments, format), + let site_dir = paths.site_dir()?; + match open_stopped_site(&site_dir)? { + Some(site) => remove_from_stopped_site(&site, &site_dir, &arguments, format), None => remove_from_running_site(&arguments, format).await, } } /// Opens the stopped site under the exclusive lock; `None` when there is no site here or a /// running manager holds it, so the removal goes through the manager. -fn open_stopped_site(paths: &RootPathArgs) -> anyhow::Result> { - let site_dir = paths.site_dir()?; +fn open_stopped_site(site_dir: &Path) -> anyhow::Result> { if !site_dir.join(SITE_FILE).exists() { return Ok(None); } match OfflineSite::open( - &site_dir, + site_dir, &SiteInputBundleValidator::new( declaration_validator(), dotcore::model::site_declaration_rules(), @@ -104,11 +107,24 @@ fn open_stopped_site(paths: &RootPathArgs) -> anyhow::Result /// Plans, confirms and applies the removal on the stopped site. fn remove_from_stopped_site( site: &OfflineSite, + site_dir: &Path, arguments: &NodeRemoveArgs, format: OutputFormat, ) -> anyhow::Result<()> { + let nodes = list_site_nodes(site_dir, &dotcore::model::site_declaration_rules()) + .with_context(|| { + format!( + "cannot remove a node from the site at {}", + site_dir.display() + ) + })? + .nodes + .into_iter() + .map(|listed| listed.node) + .collect::>(); + let node_id = node_id(&arguments.node, &nodes)?; let plan = match site - .plan_node_removal(&arguments.node, arguments.forget_deployments) + .plan_node_removal(&node_id, arguments.forget_deployments) .with_context(|| format!("cannot remove node {:?}", arguments.node))? { NodeRemoval::Planned(plan) => plan, @@ -200,8 +216,7 @@ async fn remove_from_running_site( } } -/// Finds the node id of the machine named by `selector`, its id or its display name. An unknown -/// id is passed on, so a removal that already finished reports so; an unknown name is an error. +/// Finds the node id of the running site's machine that `selector` names. async fn resolve_node( manager: &crate::management::Manager, selector: &str, @@ -213,35 +228,39 @@ async fn resolve_node( .map_err(|status| call_failed("list the machines", &status))? .into_inner() .machines; - if machines - .iter() - .any(|machine| machine.machine_id == selector) - { - return Ok(selector.to_owned()); + Ok(node_id(selector, &machines)?) +} + +/// Finds the node id of the node `selector` names among the site's nodes. An unknown selector +/// shaped like a node id is passed on, so a removal that already finished reports so; any other +/// unknown selector is an error. +fn node_id(selector: &str, nodes: &[impl Referable]) -> Result { + match resolve(ReferenceKind::Node, selector, nodes) { + Ok(node) => Ok(node.id().to_owned()), + Err(ReferenceError::Unknown { .. }) if looks_like_node_id(selector) => { + Ok(selector.to_owned()) + } + Err(error) => Err(error), } - let named = machines - .iter() - .filter(|machine| machine.display_name == selector) - .collect::>(); - match named.as_slice() { - [machine] => Ok(machine.machine_id.clone()), - [] if looks_like_node_id(selector) => Ok(selector.to_owned()), - [] => anyhow::bail!( - "no node {selector:?} in this site; declared nodes: {}", - machines - .iter() - .map(|machine| format!("{:?} ({})", machine.display_name, machine.machine_id)) - .collect::>() - .join(", ") - ), - _ => anyhow::bail!( - "several nodes are named {selector:?}; select the node to remove by its id: {}", - named - .iter() - .map(|machine| machine.machine_id.as_str()) - .collect::>() - .join(", ") - ), +} + +impl Referable for Machine { + fn id(&self) -> &str { + &self.machine_id + } + + fn name(&self) -> &str { + &self.display_name + } +} + +impl Referable for SiteNode { + fn id(&self) -> &str { + &self.node_id + } + + fn name(&self) -> &str { + &self.display_name } } diff --git a/backend/cli/src/reference.rs b/backend/cli/src/reference.rs new file mode 100644 index 00000000..f6e4d483 --- /dev/null +++ b/backend/cli/src/reference.rs @@ -0,0 +1,482 @@ +//! How an operator names one object on the command line, such as a deployment, a node or an +//! inference route: by its id, its name, or a unique part of either. +//! +//! A reference is tried against the candidates in a fixed order of steps, and the first step that +//! finds anything decides: one match resolves, several fail and list them. Names and partial ids +//! ignore case, and a partial match needs a reference of at least two characters. +//! +//! 1. The exact id. +//! 2. The exact name. +//! 3. An id fragment: a prefix of the id, or one or more whole consecutive hyphen-separated parts +//! of it, such as `27b` or `8-27b` of `qwen3-8-27b-3cfmn`. +//! 4. A prefix of the name. +//! 5. Name words: the reference's words are consecutive words of the name, the last one possibly +//! cut short. Words are separated by any character that is not a letter or a digit, so `27b`, +//! `qwen`, `3.8` and `8 27` all name `Qwen 3.8 27B`. + +use crate::management::{DeploymentGroup, single_line}; + +/// The shortest reference that may match an id or a name partially. +const MIN_PARTIAL_CHARS: usize = 2; + +/// An object an operator can name by its id or its names. +pub(crate) trait Referable { + /// The stable id. + fn id(&self) -> &str; + + /// The name shown to the operator, which need not be unique. + fn name(&self) -> &str; + + /// Other names that also name the object, such as the name it was given when the shown name + /// comes from elsewhere. + fn aliases(&self) -> Vec<&str> { + Vec::new() + } +} + +/// Finds the one candidate that `reference` names, following the steps of this module's order. +pub(crate) fn resolve<'a, T: Referable>( + kind: ReferenceKind, + reference: &str, + candidates: &'a [T], +) -> Result<&'a T, ReferenceError> { + let lowered = reference.to_lowercase(); + let partial = reference.chars().count() >= MIN_PARTIAL_CHARS; + let steps: [&dyn Fn(&T) -> bool; 5] = [ + &|candidate| candidate.id() == reference, + &|candidate| names(candidate).any(|name| name == lowered), + &|candidate| partial && id_fragment_matches(&candidate.id().to_lowercase(), &lowered), + &|candidate| partial && names(candidate).any(|name| name.starts_with(&lowered)), + &|candidate| partial && names(candidate).any(|name| words_match(&name, &lowered)), + ]; + + for step in steps { + let found = candidates + .iter() + .filter(|candidate| step(candidate)) + .collect::>(); + match found.as_slice() { + [] => {} + [one] => return Ok(one), + several => { + return Err(ReferenceError::Ambiguous { + kind, + reference: reference.to_owned(), + matches: several + .iter() + .map(|candidate| Candidate::of(*candidate)) + .collect(), + }); + } + } + } + + Err(ReferenceError::Unknown { + kind, + reference: reference.to_owned(), + known: candidates.iter().map(Candidate::of).collect(), + }) +} + +/// The kind of object a reference names, which picks the words of its failures. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum ReferenceKind { + Deployment(DeploymentGroup), + + Node, + + Route, +} + +impl ReferenceKind { + /// The operator word for one object, for example `node`. + pub(crate) fn noun(self) -> &'static str { + match self { + Self::Deployment(group) => group.noun(), + Self::Node => "node", + Self::Route => "inference route", + } + } + + /// Whether the objects have an id apart from their name; a route is named by its name alone. + pub(crate) fn has_ids(self) -> bool { + !matches!(self, Self::Route) + } + + /// Whether an unknown reference lists the known objects, for kinds without a command that + /// lists them wherever the reference was given. + pub(crate) fn lists_known(self) -> bool { + !matches!(self, Self::Deployment(_)) + } +} + +/// One object a failed reference lists, its id and shown name made safe to print. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct Candidate { + pub(crate) id: String, + + pub(crate) name: String, +} + +impl Candidate { + fn of(object: &impl Referable) -> Self { + Self { + id: single_line(object.id()), + name: single_line(object.name()), + } + } + + /// The candidate on one line: its id followed by its name when that differs. + fn label(&self) -> String { + if self.name.is_empty() || self.name == self.id { + self.id.clone() + } else { + format!("{} ({})", self.id, self.name) + } + } +} + +/// An operator reference that names no object of its kind, or several. +#[derive(Debug, thiserror::Error)] +pub(crate) enum ReferenceError { + #[error("no {} matches {reference:?}{}", .kind.noun(), known_suffix(*.kind, .known))] + Unknown { + kind: ReferenceKind, + reference: String, + known: Vec, + }, + + #[error( + "{} {}s match {reference:?}: {}", + .matches.len(), + .kind.noun(), + labels(.matches) + )] + Ambiguous { + kind: ReferenceKind, + reference: String, + matches: Vec, + }, +} + +/// The candidate's shown name and aliases, lowercased, without empty ones. +fn names(candidate: &impl Referable) -> impl Iterator { + std::iter::once(candidate.name()) + .chain(candidate.aliases()) + .filter(|name| !name.is_empty()) + .map(str::to_lowercase) +} + +/// Whether `fragment` is a prefix of `id` or one or more whole consecutive hyphen-separated +/// parts of it; both are lowercase. +fn id_fragment_matches(id: &str, fragment: &str) -> bool { + if id.starts_with(fragment) { + return true; + } + let parts = id.split('-').collect::>(); + let wanted = fragment.split('-').collect::>(); + parts.windows(wanted.len()).any(|window| window == wanted) +} + +/// Whether the words of `reference` are consecutive words of `name`, the last one possibly cut +/// short; both are lowercase. +fn words_match(name: &str, reference: &str) -> bool { + let reference = words(reference); + let Some((last, leading)) = reference.split_last() else { + return false; + }; + words(name).windows(reference.len()).any(|window| { + window[..leading.len()] == *leading && window[leading.len()].starts_with(last) + }) +} + +/// Splits text into words at every character that is not a letter or a digit. +fn words(text: &str) -> Vec<&str> { + text.split(|character: char| !character.is_alphanumeric()) + .filter(|word| !word.is_empty()) + .collect() +} + +fn known_suffix(kind: ReferenceKind, known: &[Candidate]) -> String { + if kind.lists_known() && !known.is_empty() { + format!("; known {}s: {}", kind.noun(), labels(known)) + } else { + String::new() + } +} + +fn labels(candidates: &[Candidate]) -> String { + candidates + .iter() + .map(Candidate::label) + .collect::>() + .join(", ") +} + +#[cfg(test)] +mod tests { + use super::*; + + const MODELS: ReferenceKind = ReferenceKind::Deployment(DeploymentGroup::Model); + + struct Named { + id: &'static str, + name: &'static str, + alias: &'static str, + } + + impl Referable for Named { + fn id(&self) -> &str { + self.id + } + + fn name(&self) -> &str { + self.name + } + + fn aliases(&self) -> Vec<&str> { + vec![self.alias] + } + } + + fn named(id: &'static str, name: &'static str) -> Named { + Named { + id, + name, + alias: "", + } + } + + fn site() -> Vec { + vec![ + named("qwen3-8-27b-3cfmn", "Qwen 3.8 27B"), + Named { + alias: "Chat", + ..named("gemma-4-e4b-7tq2m", "Gemma 4 E4B") + }, + named("open-webui-m2rpw", "Open WebUI"), + named("tiny-k3f9x", "x"), + ] + } + + /// The id the reference resolves to, or the failure it reports. + fn resolved(candidates: &[Named], reference: &str) -> Result<&'static str, String> { + resolve(MODELS, reference, candidates) + .map(|candidate| candidate.id) + .map_err(|error| error.to_string()) + } + + fn unknown(reference: &str) -> Result<&'static str, String> { + Err(format!("no model deployment matches {reference:?}")) + } + + #[test] + fn an_exact_id_or_name_resolves_ignoring_case_for_names() { + let site = site(); + + assert_eq!( + resolved(&site, "qwen3-8-27b-3cfmn"), + Ok("qwen3-8-27b-3cfmn") + ); + assert_eq!(resolved(&site, "Qwen 3.8 27B"), Ok("qwen3-8-27b-3cfmn")); + assert_eq!(resolved(&site, "qwen 3.8 27b"), Ok("qwen3-8-27b-3cfmn")); + assert_eq!(resolved(&site, "chat"), Ok("gemma-4-e4b-7tq2m"), "an alias"); + assert_eq!( + resolved(&site, "X"), + Ok("tiny-k3f9x"), + "exact names may be short" + ); + } + + #[test] + fn an_id_fragment_is_an_id_prefix_or_whole_consecutive_id_parts() { + let site = site(); + + for fragment in ["3cfmn", "27b", "8-27b", "qwen3", "qwen3-8-2", "3CFMN"] { + assert_eq!( + resolved(&site, fragment), + Ok("qwen3-8-27b-3cfmn"), + "{fragment}" + ); + } + assert_eq!(resolved(&site, "webui-m2rpw"), Ok("open-webui-m2rpw")); + assert_eq!(resolved(&site, "OPEN-WEB"), Ok("open-webui-m2rpw")); + assert_eq!(resolved(&site, "cfmn"), unknown("cfmn"), "a partial suffix"); + assert_eq!(resolved(&site, "m2rp"), unknown("m2rp"), "a partial part"); + } + + #[test] + fn a_name_prefix_or_name_words_resolve() { + let site = site(); + + assert_eq!( + resolved(&site, "Qwen 3"), + Ok("qwen3-8-27b-3cfmn"), + "name prefix" + ); + assert_eq!( + resolved(&site, "open w"), + Ok("open-webui-m2rpw"), + "name prefix" + ); + assert_eq!(resolved(&site, "3.8"), Ok("qwen3-8-27b-3cfmn"), "two words"); + assert_eq!( + resolved(&site, "8 27"), + Ok("qwen3-8-27b-3cfmn"), + "word prefix" + ); + assert_eq!( + resolved(&site, "E4"), + Ok("gemma-4-e4b-7tq2m"), + "word prefix" + ); + assert_eq!( + resolved(&site, "web"), + Ok("open-webui-m2rpw"), + "word prefix" + ); + assert_eq!(resolved(&site, "ui"), unknown("ui"), "a word suffix"); + assert_eq!( + resolved(&site, "4 27b"), + unknown("4 27b"), + "words of two names" + ); + } + + #[test] + fn a_partial_match_needs_two_characters() { + let site = site(); + + // `8` is a whole id part and a name word of the Qwen deployment, `q` a prefix of both. + assert_eq!(resolved(&site, "8"), unknown("8")); + assert_eq!(resolved(&site, "q"), unknown("q")); + assert_eq!(resolved(&site, ""), unknown("")); + } + + #[test] + fn an_earlier_step_wins_over_a_later_one() { + let id_over_name = [ + named("gemma-aaaaa", "Gemma"), + named("other-bbbbb", "gemma-aaaaa"), + ]; + let name_over_fragment = [named("chat-aaaaa", "Coder"), named("qwen-bbbbb", "Chat")]; + let fragment_over_name = [ + named("coder-aaaaa", "Qwen"), + named("gemma-bbbbb", "Coder Large"), + ]; + let prefix_over_word = [ + named("a-aaaaa", "Coder Large"), + named("b-bbbbb", "Big Coder"), + ]; + + assert_eq!(resolved(&id_over_name, "gemma-aaaaa"), Ok("gemma-aaaaa")); + assert_eq!(resolved(&name_over_fragment, "chat"), Ok("qwen-bbbbb")); + assert_eq!(resolved(&fragment_over_name, "coder"), Ok("coder-aaaaa")); + assert_eq!(resolved(&prefix_over_word, "coder"), Ok("a-aaaaa")); + } + + #[test] + fn a_slug_id_part_that_is_also_a_name_word_resolves_at_the_id_step() { + let same = [ + named("qwen3-8-27b-3cfmn", "Qwen 3.8 27B"), + named("gemma-4-e4b-7tq2m", "Gemma 4 E4B"), + ]; + let other = [ + named("qwen3-8-27b-3cfmn", "Coder"), + named("gemma-4-e4b-7tq2m", "Gemma 27B"), + ]; + + assert_eq!(resolved(&same, "27b"), Ok("qwen3-8-27b-3cfmn")); + assert_eq!( + resolved(&other, "27b"), + Ok("qwen3-8-27b-3cfmn"), + "the id part wins over another deployment's name word" + ); + } + + #[test] + fn several_matches_at_a_step_fail_there_listing_them() { + let ids = [named("x-aaaaa", "One"), named("x-aaaaa", "Two")]; + let names = [named("gemma-aaaaa", "Gemma"), named("gemma-bbbbb", "gemma")]; + let fragments = [ + named("qwen3-8-27b-aaaaa", "Large"), + named("qwen3-8-8b-bbbbb", "Small"), + named("coder-ccccc", "Qwen3 coder"), + ]; + let prefixes = [ + named("a-aaaaa", "Open WebUI"), + named("b-bbbbb", "Open Notebook"), + named("c-ccccc", "Big open"), + ]; + let words = [ + named("a-aaaaa", "Qwen Coder"), + named("b-bbbbb", "Gemma Coder"), + ]; + + assert_eq!( + resolved(&ids, "x-aaaaa"), + Err("2 model deployments match \"x-aaaaa\": x-aaaaa (One), x-aaaaa (Two)".to_owned()) + ); + assert_eq!( + resolved(&names, "GEMMA"), + Err( + "2 model deployments match \"GEMMA\": gemma-aaaaa (Gemma), gemma-bbbbb (gemma)" + .to_owned() + ) + ); + assert_eq!( + resolved(&fragments, "qwen3-8"), + Err( + "2 model deployments match \"qwen3-8\": qwen3-8-27b-aaaaa (Large), \ + qwen3-8-8b-bbbbb (Small)" + .to_owned() + ) + ); + assert_eq!( + resolved(&prefixes, "open"), + Err( + "2 model deployments match \"open\": a-aaaaa (Open WebUI), b-bbbbb (Open \ + Notebook)" + .to_owned() + ) + ); + assert_eq!( + resolved(&words, "cod"), + Err( + "2 model deployments match \"cod\": a-aaaaa (Qwen Coder), b-bbbbb (Gemma Coder)" + .to_owned() + ) + ); + } + + #[test] + fn an_unknown_reference_lists_the_known_objects_for_kinds_without_a_list_command() { + let nodes = [named("node-00aa", "gpu1"), named("node-00bb", "")]; + + let error = resolve(ReferenceKind::Node, "gpu9", &nodes) + .err() + .expect("no node matches"); + + assert_eq!( + error.to_string(), + "no node matches \"gpu9\"; known nodes: node-00aa (gpu1), node-00bb" + ); + assert_eq!(resolved(&nodes, "gpu9"), unknown("gpu9")); + } + + #[test] + fn printed_candidates_are_single_lines() { + let deployments = [ + named("a-aaaaa", "Evil\n✔ forged"), + named("b-bbbbb", "Evil\ttwo"), + ]; + + assert_eq!( + resolved(&deployments, "evil"), + Err( + "2 model deployments match \"evil\": a-aaaaa (Evil ✔ forged), b-bbbbb (Evil two)" + .to_owned() + ) + ); + } +} diff --git a/backend/cli/tests/application_contract.rs b/backend/cli/tests/application_contract.rs index 07370d35..d15129fb 100644 --- a/backend/cli/tests/application_contract.rs +++ b/backend/cli/tests/application_contract.rs @@ -227,13 +227,13 @@ fn an_unknown_or_ambiguous_reference_fails_with_exit_code_1() { assert_eq!(text(&unknown.stdout), ""); assert_eq!( text(&unknown.stderr), - "no application deployment is named or has id \"nothing\"; see `dotc application list`\n" + "no application deployment matches \"nothing\"; see `dotc application list`\n" ); assert_eq!(ambiguous.status.code(), Some(1)); assert_eq!(text(&ambiguous.stdout), ""); assert_eq!( text(&ambiguous.stderr), - "2 application deployments are named \"Chat\": app-1, app-7; pass one of the ids instead\n" + "2 application deployments match \"Chat\": app-1 (Chat), app-7 (Chat); pass one of the ids instead\n" ); assert!( manager @@ -244,6 +244,37 @@ fn an_unknown_or_ambiguous_reference_fails_with_exit_code_1() { ); } +#[test] +fn a_name_word_or_an_id_fragment_names_one_deployment_and_a_shared_part_fails() { + let manager = FakeManager::start(FakeState::with_applications(vec![ + local_application_deployment("open-webui-3cfmn", "Team Chat", Running, Present), + local_application_deployment("open-webui-7tq2m", "Home Notes", Running, Present), + ])); + + let by_word = run(&manager, &["pause", "team"]); + let by_fragment = run(&manager, &["pause", "7tq2m"]); + let ambiguous = run(&manager, &["resume", "webui", "--yaml"]); + + for (output, name) in [(&by_word, "Team Chat"), (&by_fragment, "Home Notes")] { + assert_eq!(text(&output.stderr), ""); + assert_eq!(output.status.code(), Some(0)); + assert_eq!(text(&output.stdout), format!("✔ Pausing {name}\n")); + } + assert_eq!(ambiguous.status.code(), Some(1)); + assert_eq!(text(&ambiguous.stdout), ""); + assert_eq!( + text(&ambiguous.stderr), + "2 application deployments match \"webui\": open-webui-3cfmn (Team Chat), open-webui-7tq2m (Home Notes); pass one of the ids instead\n" + ); + assert_eq!( + lifecycle_calls(&manager), + [ + call(Rpc::PauseApplicationDeployment, Some("open-webui-3cfmn")), + call(Rpc::PauseApplicationDeployment, Some("open-webui-7tq2m")), + ] + ); +} + #[test] fn an_unreachable_manager_fails_with_exit_code_1() { let reserved = dotcore::testing::reserve_port(); diff --git a/backend/cli/tests/application_manager_contract.rs b/backend/cli/tests/application_manager_contract.rs index 8d6a2cbe..12da14fa 100644 --- a/backend/cli/tests/application_manager_contract.rs +++ b/backend/cli/tests/application_manager_contract.rs @@ -115,9 +115,7 @@ fn application_commands_drive_a_simulated_deployment_through_pause_resume_and_te assert_eq!(text(&removed_again.stdout), ""); assert_eq!( text(&removed_again.stderr), - format!( - "no application deployment is named or has id \"{id}\"; see `dotc application list`\n" - ) + format!("no application deployment matches \"{id}\"; see `dotc application list`\n") ); } diff --git a/backend/cli/tests/code_contract.rs b/backend/cli/tests/code_contract.rs index 4ad3d292..a54b0b6b 100644 --- a/backend/cli/tests/code_contract.rs +++ b/backend/cli/tests/code_contract.rs @@ -289,7 +289,7 @@ fn an_unknown_route_fails_listing_the_ready_routes() { assert_eq!( text(&output.stderr), - "no ready inference route is named \"disabled\"; ready routes: chat, code\n" + "no ready inference route matches \"disabled\"; ready routes: chat, code\n" ); assert_eq!(output.status.code(), Some(1)); assert!(!sandbox.agent_ran()); diff --git a/backend/cli/tests/command_contract.rs b/backend/cli/tests/command_contract.rs index 450728d0..a0d91f1d 100644 --- a/backend/cli/tests/command_contract.rs +++ b/backend/cli/tests/command_contract.rs @@ -3230,7 +3230,7 @@ fn node_remove_of_an_already_removed_node_id_succeeds_and_an_unknown_name_fails( assert_eq!(by_name.status.code(), Some(1)); assert_eq!( text(&by_name.stderr), - "cannot remove node \"Worker two\": no node \"Worker two\" in this site; declared nodes: \"CLI test node\" (cli-test-node)\n" + "no node matches \"Worker two\"; known nodes: cli-test-node (CLI test node)\n" ); let manager = node_remove_command(fixture.site_path(), "CLI test node") @@ -3326,10 +3326,65 @@ fn node_remove_goes_through_the_running_manager_and_reports_its_outcomes() { // An unknown name is an error, never an already removed node. let unknown = remove("Worker four", false); assert_eq!(unknown.status.code(), Some(1)); - assert!( - text(&unknown.stderr).starts_with("no node \"Worker four\" in this site; declared nodes: "), - "{}", - text(&unknown.stderr) + assert_eq!( + text(&unknown.stderr), + "no node matches \"Worker four\"; known nodes: node-00000000000000aa (Manager), node-00000000000000cc (Worker three)\n" + ); +} + +#[test] +fn node_remove_takes_a_name_word_or_an_id_fragment_and_refuses_a_shared_one() { + use support::fake_manager::{Call, FakeMachine, FakeManager, FakeState, Rpc}; + + let fake = FakeManager::start(FakeState { + machines: vec![ + FakeMachine::manager("node-00000000000000aa", "Manager"), + FakeMachine::worker("node-00000000000000bb", "Worker two"), + FakeMachine::worker("node-00000000000000cc", "Worker three"), + ], + ..FakeState::default() + }); + let no_site = TemporarySite::empty(); + let remove = |node: &str| { + let mut command = node_remove_command(&no_site.root.join("site"), node); + command.env("DOTCORE_MANAGEMENT_ADDR", fake.address().to_string()); + command.output().expect("run node remove") + }; + + let ambiguous = remove("worker"); + let by_word = remove("two"); + let by_fragment = remove("00000000000000cc"); + + assert_eq!(ambiguous.status.code(), Some(1)); + assert!(ambiguous.stdout.is_empty()); + assert_eq!( + text(&ambiguous.stderr), + "2 nodes match \"worker\": node-00000000000000bb (Worker two), node-00000000000000cc (Worker three); pass one of the ids instead\n" + ); + for (output, name) in [(&by_word, "Worker two"), (&by_fragment, "Worker three")] { + assert_eq!(output.status.code(), Some(0), "{}", text(&output.stderr)); + assert_eq!(text(&output.stdout), format!("✔ Removed {name}\n")); + } + assert_eq!( + fake.calls() + .into_iter() + .map(|Call { rpc, id }| (rpc, id)) + .collect::>(), + [ + (Rpc::ListMachines, None), + (Rpc::ListMachines, None), + ( + Rpc::PreviewMachineRemoval, + Some("node-00000000000000bb".to_owned()) + ), + (Rpc::RemoveMachine, Some("node-00000000000000bb".to_owned())), + (Rpc::ListMachines, None), + ( + Rpc::PreviewMachineRemoval, + Some("node-00000000000000cc".to_owned()) + ), + (Rpc::RemoveMachine, Some("node-00000000000000cc".to_owned())), + ] ); } diff --git a/backend/cli/tests/model_contract.rs b/backend/cli/tests/model_contract.rs index c3e6254e..95dceac4 100644 --- a/backend/cli/tests/model_contract.rs +++ b/backend/cli/tests/model_contract.rs @@ -171,13 +171,13 @@ fn an_unknown_or_ambiguous_reference_fails_with_exit_code_1() { assert_eq!(text(&unknown.stdout), ""); assert_eq!( text(&unknown.stderr), - "no model deployment is named or has id \"nothing\"; see `dotc model list`\n" + "no model deployment matches \"nothing\"; see `dotc model list`\n" ); assert_eq!(ambiguous.status.code(), Some(1)); assert_eq!(text(&ambiguous.stdout), ""); assert_eq!( text(&ambiguous.stderr), - "2 model deployments are named \"Gemma\": model-1, model-6; pass one of the ids instead\n" + "2 model deployments match \"Gemma\": model-1 (Gemma), model-6 (Gemma); pass one of the ids instead\n" ); assert!( manager @@ -188,6 +188,38 @@ fn an_unknown_or_ambiguous_reference_fails_with_exit_code_1() { ); } +#[test] +fn a_name_word_or_an_id_fragment_names_one_deployment_and_a_shared_part_fails() { + let manager = FakeManager::start(FakeState::with_models(vec![ + local_model_deployment("qwen3-8-27b-3cfmn", "Qwen 3.8 27B", Ready, Present), + local_model_deployment("qwen3-8-8b-7tq2m", "Qwen 3.8 8B", Ready, Present), + local_model_deployment("gemma-4-e4b-m2rpw", "", Ready, Present), + ])); + + let by_word = run(&manager, &["pause", "e4"]); + let by_fragment = run(&manager, &["pause", "7tq2m"]); + let ambiguous = run(&manager, &["teardown", "qwen", "--yes", "--yaml"]); + + for (output, name) in [(&by_word, "Gemma 4 E4B"), (&by_fragment, "Qwen 3.8 8B")] { + assert_eq!(text(&output.stderr), ""); + assert_eq!(output.status.code(), Some(0)); + assert_eq!(text(&output.stdout), format!("✔ Pausing {name}\n")); + } + assert_eq!(ambiguous.status.code(), Some(1)); + assert_eq!(text(&ambiguous.stdout), ""); + assert_eq!( + text(&ambiguous.stderr), + "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\n" + ); + assert_eq!( + lifecycle_calls(&manager), + [ + call(Rpc::PauseModel, Some("gemma-4-e4b-m2rpw")), + call(Rpc::PauseModel, Some("qwen3-8-8b-7tq2m")), + ] + ); +} + #[test] fn an_unreachable_manager_fails_with_exit_code_1() { let reserved = dotcore::testing::reserve_port(); @@ -610,7 +642,7 @@ fn logs_of_an_unknown_deployment_fail_before_reading_any_log() { assert_eq!(output.status.code(), Some(1)); assert_eq!( text(&output.stderr), - "no model deployment is named or has id \"missing\"; see `dotc model list`\n" + "no model deployment matches \"missing\"; see `dotc model list`\n" ); assert!(manager.state().model_logs.reads.is_empty()); } @@ -1200,7 +1232,7 @@ fn a_yaml_failure_prints_nothing_on_stdout_and_the_plain_failure_on_stderr() { assert_eq!(text(&unknown.stdout), ""); assert_eq!( text(&unknown.stderr), - "no model deployment is named or has id \"nothing\"; see `dotc model list`\n" + "no model deployment matches \"nothing\"; see `dotc model list`\n" ); assert_eq!(unavailable.status.code(), Some(1)); assert_eq!(text(&unavailable.stdout), ""); diff --git a/docs/usage.md b/docs/usage.md index a1d8b4db..4980bc1c 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -20,6 +20,7 @@ Commands print results on stdout and errors on stderr, and ask questions on the - In scripts and agents, add `--yaml`: the result is one YAML document on stdout. The command never asks a question, so pass `--yes` where it would ask for confirmation. Commands with no result to print, such as `dotc server start`, `dotc code` and `dotc dev`, refuse `--yaml`. - When a command fails, it says what went wrong and which commands can fix it. +- Name a deployment, node or route by its ID, its name, or any unique part of either: `27b` or `qwen` for `Qwen 3.8 27B`, or the last part of its ID. Case doesn't matter. If several match, the command lists them so you can pick one by ID. ## Use it from your tools From 14a2f322f8046c9008dc15157150abad4ffdc83f Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 13:15:52 -0500 Subject: [PATCH 08/19] fix(backend): offer --yaml in help only where dotc takes it --- backend/cli/src/lib.rs | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/backend/cli/src/lib.rs b/backend/cli/src/lib.rs index 2ea4245e..9960caad 100644 --- a/backend/cli/src/lib.rs +++ b/backend/cli/src/lib.rs @@ -307,7 +307,7 @@ 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); @@ -319,6 +319,25 @@ impl Cli { Ok(cli) } + /// The clap command, with `--yaml` hidden from the help of the groups that refuse it. Each of + /// those groups redeclares the global flag hidden, so it replaces the visible one in them and + /// their subcommands. + 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())); + } + 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()) { @@ -694,6 +713,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"); From dd3a6ee3d7e59f096e52344f7b5c259044f421b4 Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 13:15:52 -0500 Subject: [PATCH 09/19] refactor(backend): read one application deployment directly --- backend/cli/src/application/mod.rs | 14 +++++++++-- backend/cli/src/management/deployment.rs | 22 ++++++++++++++++- backend/cli/tests/application_contract.rs | 29 +++++++++++++++++++++++ backend/cli/tests/support/fake_manager.rs | 24 +++++++++++++++++-- 4 files changed, 84 insertions(+), 5 deletions(-) diff --git a/backend/cli/src/application/mod.rs b/backend/cli/src/application/mod.rs index bbfca626..8e309cf8 100644 --- a/backend/cli/src/application/mod.rs +++ b/backend/cli/src/application/mod.rs @@ -17,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, @@ -165,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, diff --git a/backend/cli/src/management/deployment.rs b/backend/cli/src/management/deployment.rs index c44c6892..c5d5fc47 100644 --- a/backend/cli/src/management/deployment.rs +++ b/backend/cli/src/management/deployment.rs @@ -8,7 +8,7 @@ use dotcore_proto::dotcore::deployment::v1::ExactPlacement; use serde::Serialize; -use tonic::Status; +use tonic::{Code, Status}; use super::{ DeploymentDocument, DeploymentGroup, ManagementError, Manager, ManagerArgs, call_failed, @@ -30,6 +30,13 @@ pub(crate) trait ManagedDeployment: Referable + Clone + Serialize { /// 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( @@ -97,10 +104,23 @@ 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(ReferenceKind::Deployment(T::GROUP), reference, &deployments)?.clone()) } diff --git a/backend/cli/tests/application_contract.rs b/backend/cli/tests/application_contract.rs index d15129fb..11c24a29 100644 --- a/backend/cli/tests/application_contract.rs +++ b/backend/cli/tests/application_contract.rs @@ -112,6 +112,35 @@ fn show_prints_every_key_for_a_running_deployment_with_its_endpoint() { ); } +#[test] +fn show_reads_one_deployment_by_exact_id_and_lists_to_resolve_a_name() { + let manager = FakeManager::start(FakeState::with_applications(mixed_deployments())); + + let by_id = run(&manager, &["show", "app-1"]); + let id_calls = manager.calls(); + let by_name = run(&manager, &["show", "Chat"]); + let name_calls = manager.calls()[id_calls.len()..].to_vec(); + + assert_eq!(by_id.status.code(), Some(0), "{}", text(&by_id.stderr)); + assert_eq!(by_name.status.code(), Some(0), "{}", text(&by_name.stderr)); + assert_eq!(text(&by_name.stdout), text(&by_id.stdout)); + assert_eq!( + id_calls, + vec![ + call(Rpc::GetApplicationDeployment, Some("app-1")), + call(Rpc::ListConfiguredExecutionTargets, None) + ] + ); + assert_eq!( + name_calls, + vec![ + call(Rpc::GetApplicationDeployment, Some("Chat")), + call(Rpc::ListApplicationDeployments, None), + call(Rpc::ListConfiguredExecutionTargets, None) + ] + ); +} + #[test] fn show_reports_stage_failure_and_stale_observation_by_id() { let manager = FakeManager::start(FakeState::with_applications(mixed_deployments())); diff --git a/backend/cli/tests/support/fake_manager.rs b/backend/cli/tests/support/fake_manager.rs index 0122719c..6fb83df9 100644 --- a/backend/cli/tests/support/fake_manager.rs +++ b/backend/cli/tests/support/fake_manager.rs @@ -258,6 +258,8 @@ pub enum Rpc { RemoveModelDeployment, + GetApplicationDeployment, + ListApplicationDeployments, PauseApplicationDeployment, @@ -736,9 +738,27 @@ impl ApplicationDeploymentService for FakeApplications { async fn get_application_deployment( &self, - _request: Request, + request: Request, ) -> Result, Status> { - Err(not_faked()) + let id = request.into_inner().application_deployment_id; + let mut state = self.state.lock().expect("fake manager state"); + record(&mut state, Rpc::GetApplicationDeployment, Some(&id))?; + if id.is_empty() || id.contains(char::is_whitespace) { + return Err(Status::invalid_argument( + "Application lifecycle request contains an invalid ID", + )); + } + let deployment = state + .application_deployments + .iter() + .find(|deployment| deployment.application_deployment_id == id) + .cloned() + .ok_or_else(|| Status::not_found("application deployment was not found"))?; + Ok(Response::new( + application::GetApplicationDeploymentResponse { + deployment: Some(deployment), + }, + )) } async fn create_application_deployment( From e3c7846c63a24dd175e53c2ad953add11deb7e28 Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 13:20:31 -0500 Subject: [PATCH 10/19] feat(backend): print an agent skill with dotc --skill --- backend/cli/src/code/mod.rs | 2 +- backend/cli/src/lib.rs | 47 +++++-- backend/cli/src/paths.rs | 5 +- backend/cli/src/site/mod.rs | 10 +- backend/cli/src/skill/guide.md | 17 +++ backend/cli/src/skill/mod.rs | 174 ++++++++++++++++++++++++++ backend/cli/src/workload/mod.rs | 6 +- backend/cli/tests/command_contract.rs | 92 ++++++++++++++ docs/specs/cli.md | 1 + docs/usage.md | 2 + nix/backend.nix | 1 + 11 files changed, 338 insertions(+), 19 deletions(-) create mode 100644 backend/cli/src/skill/guide.md create mode 100644 backend/cli/src/skill/mod.rs diff --git a/backend/cli/src/code/mod.rs b/backend/cli/src/code/mod.rs index f4e00253..1b223cda 100644 --- a/backend/cli/src/code/mod.rs +++ b/backend/cli/src/code/mod.rs @@ -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/lib.rs b/backend/cli/src/lib.rs index 9960caad..7cc9cbbe 100644 --- a/backend/cli/src/lib.rs +++ b/backend/cli/src/lib.rs @@ -37,6 +37,7 @@ mod reference; mod runtime_confirmation; mod server; mod site; +mod skill; mod telemetry; pub mod terminal; #[cfg(test)] @@ -51,7 +52,7 @@ pub use paths::RootPathArgs; name = "dotc", version, arg_required_else_help = true, - subcommand_required = true + override_usage = "dotc [OPTIONS] \n dotc --skill" )] pub struct Cli { /// Show the complete cause chain of a failure on a terminal. @@ -63,11 +64,16 @@ pub struct Cli { #[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, } /// Product CLI command groups. @@ -152,7 +158,10 @@ pub fn build_runtime() -> Result { pub async fn dispatch(cli: Cli) -> Result<()> { let paths = &cli.paths; let format = cli.output_format(); - match cli.command { + 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, format).await, @@ -225,6 +234,16 @@ 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) + }) +} + /// 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(); @@ -313,6 +332,12 @@ impl Cli { 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(message) = cli.argument_contract_error() { return Err(Self::command().error(clap::error::ErrorKind::ArgumentConflict, message)); } @@ -413,10 +438,13 @@ impl Cli { } fn argument_contract_error(&self) -> Option<&'static str> { - if self.yaml && !self.command.prints_yaml() { + 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 &self.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(), @@ -442,7 +470,7 @@ mod tests { #[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] @@ -457,7 +485,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!( @@ -568,7 +596,7 @@ mod tests { "simulated", ]) .expect("site init"); - assert!(matches!(command.command, super::Command::Site(_))); + assert!(matches!(command.command, Some(super::Command::Site(_)))); } #[test] @@ -581,7 +609,8 @@ 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:?}"), } } diff --git a/backend/cli/src/paths.rs b/backend/cli/src/paths.rs index 6b7bb304..1a9f26f8 100644 --- a/backend/cli/src/paths.rs +++ b/backend/cli/src/paths.rs @@ -269,7 +269,10 @@ mod tests { ]; for arguments in cases { let cli = Cli::try_parse_from(arguments).expect("parses"); - assert!(matches!(cli.command, Command::Node(_)), "{arguments:?}"); + assert!( + matches!(cli.command, Some(Command::Node(_))), + "{arguments:?}" + ); assert_eq!( cli.paths.site_dir, Some(PathBuf::from("/a")), diff --git a/backend/cli/src/site/mod.rs b/backend/cli/src/site/mod.rs index 2a21490e..31174a78 100644 --- a/backend/cli/src/site/mod.rs +++ b/backend/cli/src/site/mod.rs @@ -687,7 +687,7 @@ mod tests { fn init(arguments: &[&str]) -> super::SiteInitArgs { let cli = Cli::try_parse_from(arguments).expect("site init arguments"); - let Command::Site(site) = cli.command else { + let Some(Command::Site(site)) = cli.command else { panic!("Site command") }; let Some(SiteSubcommand::Init(arguments)) = site.command else { @@ -884,7 +884,7 @@ mod tests { fn interactive_flag_is_accepted_for_phase_six_guided_execution() { let command = Cli::try_parse_from(["dotc", "site", "init", "--interactive"]) .expect("interactive init arguments"); - assert!(matches!(command.command, crate::Command::Site(_))); + assert!(matches!(command.command, Some(crate::Command::Site(_)))); } #[test] @@ -996,10 +996,10 @@ mod tests { reset_arguments.extend(common); let init = Cli::try_parse_from(init_arguments).expect("init arguments"); let reset = Cli::try_parse_from(reset_arguments).expect("reset arguments"); - let Command::Site(init) = init.command else { + let Some(Command::Site(init)) = init.command else { panic!("Site init command") }; - let Command::Site(reset) = reset.command else { + let Some(Command::Site(reset)) = reset.command else { panic!("Site reset command") }; let Some(SiteSubcommand::Init(init)) = init.command else { @@ -1085,7 +1085,7 @@ mod tests { "/tmp/catalog", ]) .expect("site validate arguments"); - assert!(matches!(cli.command, Command::Site(_))); + assert!(matches!(cli.command, Some(Command::Site(_)))); } #[test] diff --git a/backend/cli/src/skill/guide.md b/backend/cli/src/skill/guide.md new file mode 100644 index 00000000..64ead467 --- /dev/null +++ b/backend/cli/src/skill/guide.md @@ -0,0 +1,17 @@ +# dotc + +Dotcore runs AI models and apps on hardware people own, and serves the models behind one +OpenAI-compatible endpoint. `dotc` is its command-line tool: it manages a site (one or more +machines), its nodes, and its model and application deployments. + +## Conventions + +- Output: a command prints its result on stdout for a person. Failures go to stderr with a + non-zero exit code. +- Scripts and agents: add `--yaml` to get exactly one YAML document on stdout. A command with + `--yaml` never prompts; pass `--yes` where it would ask for a confirmation. +- `--yaml` is the API's proto JSON mapping: keys are lowerCamelCase, 64-bit numbers are quoted + strings, absent fields mean zero, false or empty, and enums use their full names. +- A deployment, node or route reference is its ID, its name, a unique part of its ID (`3cfmn`) or + a unique word or prefix of its name (`27b`). An ambiguous reference fails and lists the + candidates; pick one by ID. Deployment IDs look like `-<5 chars>`. diff --git a/backend/cli/src/skill/mod.rs b/backend/cli/src/skill/mod.rs new file mode 100644 index 00000000..69f32f6f --- /dev/null +++ b/backend/cli/src/skill/mod.rs @@ -0,0 +1,174 @@ +//! The agent skill printed by `dotc --skill`. +//! +//! It renders a Markdown skill document: frontmatter naming the skill, a static guide to the +//! conventions every command shares, and the list of every command generated from the command +//! tree, so the list always matches the binary an agent runs. + +use anyhow::Result; + +use crate::output; + +const GUIDE: &str = include_str!("guide.md"); + +const DESCRIPTION: &str = "Manage a Dotcore site from the terminal. Inspect and control model and \ + application deployments, nodes and sites, and check this machine's hardware. Use when the \ + user asks to deploy, list, pause, resume, inspect or remove Dotcore models or apps, or to \ + run or debug Dotcore itself."; + +const COMPATIBILITY: &str = + "Requires dotc on PATH and, for site commands, a running Dotcore manager."; + +/// Prints the skill for `root` on stdout, as raw Markdown whatever the terminal. +pub(crate) fn print(root: &clap::Command) -> Result<()> { + output::write_text(&render(root)) +} + +/// Renders the complete skill document for the command tree `root`. +fn render(root: &clap::Command) -> String { + let mut root = root.clone(); + root.build(); + format!( + "---\nname: dotc\ndescription: {DESCRIPTION}\ncompatibility: {COMPATIBILITY}\nmetadata:\n version: \"{}\"\n---\n{GUIDE}\n## Commands\n\n{}", + env!("CARGO_PKG_VERSION"), + render_commands(&root) + ) +} + +/// Renders the visible leaf commands grouped by top-level command, one `dotc ` +/// line each with its one-line description, padded to the widest entry. +fn render_commands(root: &clap::Command) -> String { + let mut groups: Vec<(String, Vec<(String, String)>)> = Vec::new(); + for group in visible_subcommands(root) { + let mut entries = Vec::new(); + collect_leaves(group, "dotc", &mut entries); + groups.push((group.get_name().to_string(), entries)); + } + let width = groups + .iter() + .flat_map(|(_, entries)| entries) + .map(|(usage, _)| usage.len()) + .max() + .unwrap_or(0); + + let mut text = String::new(); + for (name, entries) in &groups { + text.push_str(&format!("--- {name} ---\n")); + for (usage, about) in entries { + text.push_str(&format!("{usage: --help` for flags.\n"); + text +} + +/// Adds `command` or, for a group, its leaves in declaration order. +fn collect_leaves(command: &clap::Command, path: &str, entries: &mut Vec<(String, String)>) { + let path = format!("{path} {}", command.get_name()); + let mut children = visible_subcommands(command).peekable(); + if children.peek().is_none() { + entries.push((usage(command, &path), about(command))); + return; + } + for child in children { + collect_leaves(child, &path, entries); + } +} + +/// The subcommands a reader can use: not hidden and not the generated `help`. +fn visible_subcommands(command: &clap::Command) -> impl Iterator { + command + .get_subcommands() + .filter(|subcommand| !subcommand.is_hide_set() && subcommand.get_name() != "help") +} + +/// The path followed by the command's positional arguments, required ones in angle brackets. +fn usage(command: &clap::Command, path: &str) -> String { + let mut usage = path.to_string(); + for positional in command.get_positionals().filter(|arg| !arg.is_hide_set()) { + let name = positional + .get_value_names() + .and_then(|names| names.first()) + .map_or_else( + || positional.get_id().as_str().to_uppercase(), + |n| n.to_string(), + ); + let dots = if is_repeated(positional) { "..." } else { "" }; + if positional.is_required_set() { + usage.push_str(&format!(" <{name}>{dots}")); + } else { + usage.push_str(&format!(" [{name}]{dots}")); + } + } + usage +} + +/// Reports whether the argument takes several values. +fn is_repeated(arg: &clap::Arg) -> bool { + matches!(arg.get_action(), clap::ArgAction::Append) + || arg.get_num_args().is_some_and(|n| n.max_values() > 1) +} + +/// The first paragraph of the command's description collapsed onto one line. +fn about(command: &clap::Command) -> String { + command + .get_about() + .map(|about| { + let text = about.to_string(); + let paragraph = text.split("\n\n").next().unwrap_or_default(); + paragraph.split_whitespace().collect::>().join(" ") + }) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use clap::{Arg, Command}; + + use super::render_commands; + + #[test] + fn commands_are_grouped_padded_and_skip_hidden_and_help() { + let mut root = Command::new("dotc") + .subcommand( + Command::new("model") + .about("Group about is not listed") + .subcommand(Command::new("list").about("List models")) + .subcommand( + Command::new("show") + .about("Show one model\n\nLong text") + .arg(Arg::new("model").required(true)), + ) + .subcommand(Command::new("old").about("Hidden").hide(true)), + ) + .subcommand( + Command::new("dev").subcommand( + Command::new("workload").subcommand( + Command::new("launch") + .about("Launch a workload") + .arg(Arg::new("name")), + ), + ), + ) + .subcommand(Command::new("gc").about("Clean up")) + .subcommand(Command::new("secret").about("Secret").hide(true)); + root.build(); + + assert_eq!( + render_commands(&root), + "\ +--- model --- +dotc model list # List models +dotc model show # Show one model + +--- dev --- +dotc dev workload launch [NAME] # Launch a workload + +--- gc --- +dotc gc # Clean up + +Run `dotc --help` for flags. +" + ); + } +} diff --git a/backend/cli/src/workload/mod.rs b/backend/cli/src/workload/mod.rs index 9e5559d8..fc2be00d 100644 --- a/backend/cli/src/workload/mod.rs +++ b/backend/cli/src/workload/mod.rs @@ -1016,7 +1016,7 @@ mod tests { "profile-one", ]) .expect("minimal direct workload launch"); - let crate::Command::Dev(command) = cli.command else { + let Some(crate::Command::Dev(command)) = cli.command else { panic!("expected development command"); }; let Some(DevSubcommand::Workload(command)) = command.command else { @@ -1140,7 +1140,7 @@ mod tests { "/cache", ]) .expect("default VRAM observation"); - let crate::Command::Dev(command) = cli.command else { + let Some(crate::Command::Dev(command)) = cli.command else { panic!("expected development command"); }; let Some(DevSubcommand::Workload(command)) = command.command else { @@ -1174,7 +1174,7 @@ mod tests { "30", ]) .expect("explicit VRAM observation"); - let crate::Command::Dev(command) = cli.command else { + let Some(crate::Command::Dev(command)) = cli.command else { panic!("expected development command"); }; let Some(DevSubcommand::Workload(command)) = command.command else { diff --git a/backend/cli/tests/command_contract.rs b/backend/cli/tests/command_contract.rs index a0d91f1d..51f85aad 100644 --- a/backend/cli/tests/command_contract.rs +++ b/backend/cli/tests/command_contract.rs @@ -41,6 +41,77 @@ fn version_command_runs_successfully() { ); } +#[test] +fn skill_prints_a_valid_agent_skill_listing_every_visible_leaf_command_once() { + let output = isolated_dotc() + .arg("--skill") + .output() + .expect("run dotc skill"); + assert!(output.status.success()); + assert_eq!(text(&output.stderr), ""); + let skill = text(&output.stdout); + + let (frontmatter, body) = skill + .strip_prefix("---\n") + .and_then(|rest| rest.split_once("\n---\n")) + .expect("frontmatter"); + let frontmatter: serde_json::Value = serde_yaml_ng::from_str(frontmatter).expect("YAML"); + let name = frontmatter["name"].as_str().expect("name"); + assert_eq!(name, "dotc"); + assert!(name.len() <= 64 && name.chars().all(|c| c.is_ascii_lowercase() || c == '-')); + let description = frontmatter["description"].as_str().expect("description"); + assert!( + !description.is_empty() && description.len() <= 1024, + "{description}" + ); + assert!( + frontmatter["compatibility"] + .as_str() + .expect("compatibility") + .len() + <= 500 + ); + assert_eq!( + frontmatter["metadata"]["version"], + serde_json::json!(env!("CARGO_PKG_VERSION")) + ); + assert!(body.lines().count() < 500); + + let mut leaves = Vec::new(); + collect_visible_leaves(&command_tree(), "dotc", &mut leaves); + assert!(leaves.len() > 30, "{leaves:?}"); + for leaf in &leaves { + let lines = body + .lines() + .filter(|line| { + line.strip_prefix(leaf.as_str()) + .is_some_and(|rest| rest.is_empty() || rest.starts_with([' '])) + && line.contains(" # ") + }) + .count(); + assert_eq!(lines, 1, "{leaf}"); + } + assert!(body.contains("\nRun `dotc --help` for flags.\n")); +} + +#[test] +fn skill_is_exclusive_with_commands_and_other_arguments() { + for arguments in [ + &["--skill", "model", "list"][..], + &["--skill", "--yaml"][..], + &["--yaml", "--skill"][..], + ] { + let output = isolated_dotc().args(arguments).output().expect("run dotc"); + assert_eq!(output.status.code(), Some(2), "{arguments:?}"); + assert_eq!(text(&output.stdout), "", "{arguments:?}"); + assert!( + text(&output.stderr).contains("--skill cannot be combined with other arguments"), + "{arguments:?}: {}", + text(&output.stderr) + ); + } +} + #[test] fn config_show_reports_explicit_xdg_and_home_paths_without_mutation() { let fixture = TemporarySite::empty(); @@ -7083,6 +7154,27 @@ const SIMULATED_MODEL_TARGET: &str = "- executionTargetId: model-target\n siteN /// Retained execution target bound to the Docker runtime, as a `site.yaml` list item. const DOCKER_APPLICATION_TARGET: &str = "- executionTargetId: application-target\n siteNodeId: retained-node\n displayName: application-target\n applicationRuntime: { dockerRuntime: {} }\n"; +fn command_tree() -> clap::Command { + let mut command = ::command(); + command.build(); + command +} + +/// Collects the path of every visible command without visible subcommands. +fn collect_visible_leaves(command: &clap::Command, path: &str, leaves: &mut Vec) { + let mut children = command + .get_subcommands() + .filter(|child| !child.is_hide_set() && child.get_name() != "help") + .peekable(); + if children.peek().is_none() { + leaves.push(path.to_string()); + return; + } + for child in children { + collect_visible_leaves(child, &format!("{path} {}", child.get_name()), leaves); + } +} + fn text(value: &[u8]) -> String { String::from_utf8_lossy(value).into_owned() } diff --git a/docs/specs/cli.md b/docs/specs/cli.md index af0ed577..69bfa0de 100644 --- a/docs/specs/cli.md +++ b/docs/specs/cli.md @@ -11,6 +11,7 @@ Code: `backend/cli/`. - Add machines to a running site, join a machine from that machine, and remove one. - Manage model and application deployments through the management API, from scripts. - Start coding agents that use the site's routes, and run one-off development workloads. +- Let coding agents discover its commands and conventions from the installed binary. - Run exclusive administration on a stopped site: node removal when the site manager can't start, site reset and destructive recovery. diff --git a/docs/usage.md b/docs/usage.md index 4980bc1c..a9164a87 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -22,6 +22,8 @@ Commands print results on stdout and errors on stderr, and ask questions on the - When a command fails, it says what went wrong and which commands can fix it. - Name a deployment, node or route by its ID, its name, or any unique part of either: `27b` or `qwen` for `Qwen 3.8 27B`, or the last part of its ID. Case doesn't matter. If several match, the command lists them so you can pick one by ID. +To teach a coding agent `dotc`, save `dotc --skill` as a skill, for example `dotc --skill > .claude/skills/dotc/SKILL.md` for Claude Code. It lists every command and the conventions above, and matches the installed version. + ## Use it from your tools Each route is an OpenAI-compatible endpoint, and its route name is the `model` your client asks for. diff --git a/nix/backend.nix b/nix/backend.nix index 84151ac3..b95152ad 100644 --- a/nix/backend.nix +++ b/nix/backend.nix @@ -16,6 +16,7 @@ let isEmbeddedSource = path: toString path == toString (root + "/backend/cli/src/code/dotcore-provider.ts") + || toString path == toString (root + "/backend/cli/src/skill/guide.md") || pkgs.lib.hasPrefix (toString (root + "/backend/node_hardware/simulated")) (toString path); # The protocol crate reaches the repository's contract tree through this link, so a packaged crate From 9e0e0c2922acf1183780dd1f4d015632ef90437e Mon Sep 17 00:00:00 2001 From: Andre-Philippe Paquet Date: Wed, 25 Nov 2026 22:48:46 -0500 Subject: [PATCH 11/19] feat(backend): deploy models from dotc with a payload --- backend/cli/src/deploy/mod.rs | 260 +++++++ backend/cli/src/lib.rs | 4 + backend/cli/src/management/mod.rs | 6 + backend/cli/src/model/catalog.rs | 204 ++++++ backend/cli/src/model/deploy.rs | 336 +++++++++ backend/cli/src/model/mod.rs | 26 + backend/cli/src/model/payload.rs | 588 ++++++++++++++++ backend/cli/src/model/selection.rs | 293 ++++++++ backend/cli/src/model/template.rs | 385 +++++++++++ backend/cli/src/model/view.rs | 594 ++++++++++++++++ backend/cli/src/reference.rs | 9 + backend/cli/tests/model_deploy_contract.rs | 754 +++++++++++++++++++++ backend/cli/tests/support/fake_manager.rs | 148 +++- 13 files changed, 3599 insertions(+), 8 deletions(-) create mode 100644 backend/cli/src/deploy/mod.rs create mode 100644 backend/cli/src/model/catalog.rs create mode 100644 backend/cli/src/model/deploy.rs create mode 100644 backend/cli/src/model/payload.rs create mode 100644 backend/cli/src/model/selection.rs create mode 100644 backend/cli/src/model/template.rs create mode 100644 backend/cli/src/model/view.rs create mode 100644 backend/cli/tests/model_deploy_contract.rs diff --git a/backend/cli/src/deploy/mod.rs b/backend/cli/src/deploy/mod.rs new file mode 100644 index 00000000..cd934d26 --- /dev/null +++ b/backend/cli/src/deploy/mod.rs @@ -0,0 +1,260 @@ +//! Inputs every deploy command shares: the payload text, `--set` overrides and the plain values +//! they carry. +//! +//! A payload or an override 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, + io::{self, Read}, + path::{Path, PathBuf}, +}; + +use anyhow::Context; +use serde::{Deserialize, Serialize}; + +/// A value as a payload or an override writes it, before it gets its parameter's type. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(untagged)] +pub(crate) enum PlainValue { + /// A YAML boolean. + Boolean(bool), + + /// A YAML number that is a non-negative integer. + Number(u64), + + /// Any other scalar, and every `--set` value. + 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 payload or 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()), + } + } +} + +/// Where a payload is read from: a file, or stdin for `-`. +#[derive(Clone, Debug)] +pub(crate) struct PayloadSource(PathBuf); + +impl PayloadSource { + /// Reads the whole payload text. + pub(crate) fn read(&self) -> anyhow::Result { + let mut text = String::new(); + if self.0 == Path::new("-") { + io::stdin() + .read_to_string(&mut text) + .context("read the payload from stdin")?; + } else { + text = std::fs::read_to_string(&self.0) + .with_context(|| format!("read the payload file {}", self.0.display()))?; + } + Ok(text) + } +} + +impl From for PayloadSource { + fn from(path: PathBuf) -> Self { + Self(path) + } +} + +#[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/lib.rs b/backend/cli/src/lib.rs index 7cc9cbbe..d449ddb3 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; @@ -704,6 +705,9 @@ mod tests { "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 template: Print a deploy payload for a catalog model, pre-filled with its starting values", + "dotc model deploy: Deploy a catalog model from a payload, or from its starting values with `--yes`", "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", diff --git a/backend/cli/src/management/mod.rs b/backend/cli/src/management/mod.rs index 77967344..d9a38994 100644 --- a/backend/cli/src/management/mod.rs +++ b/backend/cli/src/management/mod.rs @@ -14,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, @@ -152,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()) diff --git a/backend/cli/src/model/catalog.rs b/backend/cli/src/model/catalog.rs new file mode 100644 index 00000000..6c4bccfc --- /dev/null +++ b/backend/cli/src/model/catalog.rs @@ -0,0 +1,204 @@ +//! 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::{ListModelsRequest, Model}, + deployment::v1::MemoryFit, + model::v1::{ + ListModelProfileCompatibilityRequest, ListModelProfileCompatibilityResponse, + ModelCompatibilityStatus, ModelProfileCompatibility, + }, +}; +use serde::Serialize; + +use crate::{ + management::{DeploymentGroup, Manager, 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(manager: &Manager, reference: Option<&str>) -> anyhow::Result { + let mut models = manager + .catalog() + .list_models(ListModelsRequest {}) + .await + .map_err(call_failed( + DeploymentGroup::Model, + "read the model catalog", + ))? + .into_inner() + .models; + 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 = manager + .models() + .list_model_profile_compatibility(ListModelProfileCompatibilityRequest { + model_id, + target: None, + scenario: None, + }) + .await + .map_err(call_failed( + DeploymentGroup::Model, + "read where the catalog models fit", + ))? + .into_inner(); + Ok(Self { + models, + compatibility, + nodes: manager.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", + } +} + +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/deploy.rs b/backend/cli/src/model/deploy.rs new file mode 100644 index 00000000..4705d5e8 --- /dev/null +++ b/backend/cli/src/model/deploy.rs @@ -0,0 +1,336 @@ +//! Deploys one local model from a payload, or from its starting values, after confirmation. +//! +//! The payload comes from a file or stdin; without one, `--yes` deploys the model's starting +//! values. Flags and overrides apply on top. A dry run has the server estimate the result and +//! creates nothing: it reports the fit, what fits (for context per request, the value every +//! parallel request reaches at once), the values sizing derives and any reason a launch would +//! reject them. Only an invalid payload or a launch rejection fails it. + +use std::path::PathBuf; + +use clap::Args; +use dotcore_proto::dotcore::{ + catalog::v1::ParameterValues, + model::v1::{ + CreateLocalModelDeploymentRequest, CreateModelDeploymentRequest, + EstimateLocalModelResourcesResponse, LocalModelDeploymentAdvisory, + create_model_deployment_request, + }, +}; +use serde::Serialize; + +use super::{ + document, + payload::ModelPayload, + selection::{Choices, Selection, select}, + template::{ChoiceArgs, all_at_once, estimate, starting_payload}, + view::ParameterView, +}; +use crate::{ + deploy::PayloadSource, + management::{DeploymentGroup, ManagerArgs, call_failed}, + output::{OutputFormat, present, require_consent, write_yaml}, + terminal::{ConfirmPrompt, Message, PromptError, open_terminal}, +}; + +/// Arguments for deploying a model. +#[derive(Debug, Args)] +pub struct ModelDeployArgs { + /// Catalog model: its ID, name, or a unique part of either; replaces the payload's. + #[arg(value_name = "MODEL", required_unless_present = "file")] + model: Option, + + /// Payload file to deploy, or `-` for stdin. + #[arg(short = 'f', long = "file", value_name = "PATH")] + file: Option, + + #[command(flatten)] + choices: ChoiceArgs, + + /// Display name of the deployment. + #[arg(long)] + name: Option, + + /// Name of the route created with the deployment. + #[arg(long)] + route: Option, + + /// Estimate the deployment 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 the payload, or reports its estimate on a dry run. +pub(crate) async fn model_deploy( + arguments: ModelDeployArgs, + format: OutputFormat, +) -> anyhow::Result<()> { + let from_file = arguments.file.is_some(); + if !from_file && !arguments.yes && !arguments.dry_run { + anyhow::bail!( + "deploying needs a payload; pass -f , or --yes to deploy the starting values" + ); + } + let mut payload = match &arguments.file { + Some(path) => ModelPayload::parse(&PayloadSource::from(path.clone()).read()?)?, + None => ModelPayload::default(), + }; + if let Some(model) = &arguments.model { + payload.model = model.clone(); + } + let choices = &arguments.choices; + for (field, flag) in [ + (&mut payload.profile, &choices.profile), + (&mut payload.node, &choices.node), + (&mut payload.target, &choices.target), + (&mut payload.name, &arguments.name), + (&mut payload.route, &arguments.route), + ] { + if flag.is_some() { + field.clone_from(flag); + } + } + + let manager = arguments.manager.connect().await?; + let selection = select( + &manager, + &Choices { + model: &payload.model, + profile: payload.profile.as_deref(), + node: payload.node.as_deref(), + target: payload.target.as_deref(), + }, + ) + .await?; + if !from_file { + let flags = payload; + payload = starting_payload(&selection); + payload.name = flags.name.or(payload.name); + payload.route = flags.route.or(payload.route); + } + payload.apply(&choices.settings)?; + let configuration = payload.configuration(&selection.schema())?; + + 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 = payload + .name + .clone() + .unwrap_or_else(|| selection.model.display_name.clone()); + 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 + .models() + .create_model_deployment(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(configuration), + }, + )), + exposure: Some(payload.exposure()), + model_deployment_name: payload.name.clone(), + }) + .await + .map_err(call_failed( + DeploymentGroup::Model, + format!("deploy {name}"), + ))? + .into_inner() + .deployment + .unwrap_or_default(); + + 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 payload with every choice resolved, the values sizing +/// derived, the estimate as returned and the preview's advisories. +#[derive(Serialize)] +struct DryRunDocument<'a> { + payload: ModelPayload, + + 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, + mut payload: ModelPayload, + estimate: EstimateLocalModelResourcesResponse, + format: OutputFormat, +) -> anyhow::Result<()> { + payload.model.clone_from(&selection.model.model_id); + payload.profile = Some(selection.profile.profile_id.clone()); + payload.node = Some(selection.placement.site_node_id.clone()); + payload.target = Some(selection.placement.execution_target_id.clone()); + payload.normalize(&selection.schema()); + let parallel_requests = ParameterView::new( + &selection.model, + &selection.snapshot, + selection.compatibility.as_ref(), + ) + .parallel_requests(&payload.parameters); + 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 = estimate + .hardware_class_estimates + .iter() + .find_map(|entry| entry.launch_rejection.clone()); + + if format == OutputFormat::Yaml { + write_yaml(&DryRunDocument { + payload, + derived, + estimate: &estimate, + advisories, + })?; + } else { + present(&dry_run_messages( + selection, + &estimate, + parallel_requests, + &advisories_words(selection), + ))?; + } + match rejection { + Some(reason) => anyhow::bail!("a launch would reject these values: {reason}"), + None => Ok(()), + } +} + +fn dry_run_messages( + selection: &Selection, + estimate: &EstimateLocalModelResourcesResponse, + parallel_requests: Option, + 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")), + }]; + + let mut facts = Vec::new(); + if let Some(tokens) = estimate.largest_context_tokens_per_request { + facts.push(( + format!( + "Context per request fitting {}", + all_at_once(parallel_requests) + ), + tokens.to_string(), + )); + } + if let Some(tokens) = estimate.largest_total_context_tokens { + facts.push(("Largest total context".to_owned(), tokens.to_string())); + } + 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(dotcore_catalog::typed_parameters::canonical_text) + { + facts.push((format!("Derived {}", value.parameter_id), text)); + } + } + if !facts.is_empty() { + messages.push(Message::KeyValues(facts)); + } + messages.extend( + advisories + .iter() + .map(|advisory| Message::Warning((*advisory).to_owned())), + ); + messages +} + +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() +} diff --git a/backend/cli/src/model/mod.rs b/backend/cli/src/model/mod.rs index f1a37f8a..bbce0378 100644 --- a/backend/cli/src/model/mod.rs +++ b/backend/cli/src/model/mod.rs @@ -7,10 +7,16 @@ //! every command prints the //! manager's own message instead. +mod catalog; +mod deploy; mod list; mod parameters; +mod payload; mod projection; +mod selection; mod show; +mod template; +mod view; use clap::{Args, Subcommand}; use dotcore_proto::dotcore::{ @@ -33,9 +39,12 @@ use crate::{ }, output::OutputFormat, }; +use catalog::{ModelCatalogArgs, model_catalog}; +use deploy::{ModelDeployArgs, model_deploy}; use list::{ModelListArgs, model_list}; use projection::desired_state_label; use show::{ModelShowArgs, model_show}; +use template::{ModelTemplateArgs, model_template}; /// Commands that manage the model deployments of a running site. #[derive(Debug, Args)] @@ -57,6 +66,20 @@ enum ModelSubcommand { /// Show one model deployment by name or ID Show(ModelShowArgs), + /// List the catalog models you can deploy, with whether each profile fits each target + Catalog(ModelCatalogArgs), + + /// Print a deploy payload for a catalog model, pre-filled with its starting values + /// + /// Edit it and pass it to `deploy -f`. Comments say what each parameter accepts and the largest + /// value that fits the target. + Template(ModelTemplateArgs), + + /// Deploy a catalog model from a payload, or from its starting values with `--yes` + /// + /// `--dry-run` estimates the deployment and reports whether it fits, without creating it. + Deploy(ModelDeployArgs), + /// Pause a model deployment, without waiting for it to pause Pause(LifecycleArgs), @@ -80,6 +103,9 @@ impl ModelCommand { match self.command { 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::Template(arguments)) => model_template(arguments).await, + Some(ModelSubcommand::Deploy(arguments)) => model_deploy(arguments, format).await, Some(ModelSubcommand::Pause(arguments)) => { change_lifecycle::( &arguments.manager, diff --git a/backend/cli/src/model/payload.rs b/backend/cli/src/model/payload.rs new file mode 100644 index 00000000..fab37c49 --- /dev/null +++ b/backend/cli/src/model/payload.rs @@ -0,0 +1,588 @@ +//! The deploy payload of one local model: what to deploy, where, under which name and route, and +//! the parameter and option values to change. +//! +//! The payload is the CLI's own input contract, written by `template` and read by `deploy`. 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 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, + }, +}; +use serde::{Deserialize, Serialize}; + +use crate::deploy::{PlainValue, Setting, TypedValue, ValueError, ValueKind}; + +/// 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, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct ModelPayload { + /// Catalog model reference. + pub(super) model: String, + + /// Profile ID; the first that fits the target when left out. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) profile: Option, + + /// Node reference; the first node that fits when left out. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) node: Option, + + /// Execution target ID on the node; needed only when the node has several. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) target: Option, + + /// Display name of the deployment. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) name: Option, + + /// Name of the route created with the deployment; none keeps it hidden. + #[serde(default)] + pub(super) route: Option, + + /// Engine parameter values by parameter ID. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub(super) parameters: BTreeMap, + + /// Option parameter values by option ID, then option parameter ID. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub(super) options: BTreeMap>, + + /// Engine arguments appended to the launch as is. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(super) custom_arguments: Vec, +} + +impl ModelPayload { + /// Parses a payload from YAML (JSON is valid YAML too). + pub(super) fn parse(text: &str) -> Result { + dotcore_proto::yaml::from_str(text).map_err(PayloadError::Parse) + } + + /// 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, + }) + } + + /// Rewrites every value in its parameter's type, so a written payload carries plain numbers + /// and booleans. Values the schema doesn't type stay as written. + pub(super) fn normalize(&mut self, schema: &ParameterSchema<'_>) { + for (id, value) in &mut self.parameters { + if let Some(definition) = schema + .parameters + .iter() + .find(|definition| definition.parameter_id == *id) + && let Ok(typed) = value.typed(engine_kind(definition)) + { + *value = typed.into(); + } + } + for (option_id, values) in &mut self.options { + let Some(option) = schema + .options + .iter() + .find(|option| option.option_id == *option_id) + else { + continue; + }; + for (id, value) in values.iter_mut() { + if let Some(definition) = option + .parameters + .iter() + .find(|definition| definition.parameter_id == *id) + && let Ok(typed) = value.typed(option_kind(definition)) + { + *value = typed.into(); + } + } + } + } + + /// 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 { + /// The text is not a payload. + #[error("the payload is not valid")] + Parse(#[source] dotcore_proto::yaml::RestrictedYamlError), + + /// 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 payload = ModelPayload::parse( + "model: qwen\nprofile: balanced\nnode: gpu1\nname: Qwen\nroute: qwen\n\ + parameters:\n context-per-request: 32768\n flash-attention: true\n cache-type: q8_0\n\ + options:\n kv-cache-precision:\n precision: f16\n\ + customArguments: [--verbose]\n", + ) + .expect("payload"); + + 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::parse("model: qwen\nroute: null\n").expect("payload"); + + assert_eq!( + payload.configuration(&schema()).expect("configuration"), + LocalModelDeploymentConfiguration::default() + ); + assert_eq!( + payload.exposure(), + ModelDeploymentExposure { + kind: Some(model_deployment_exposure::Kind::Hidden( + HiddenDeploymentExposure {} + )), + } + ); + } + + #[test] + fn settings_override_payload_values_and_reach_option_parameters() { + let mut payload = + ModelPayload::parse("model: qwen\nparameters:\n context-per-request: 8192\n") + .expect("payload"); + payload + .apply(&[ + 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.." + ); + } + + #[test] + fn unknown_payload_fields_are_rejected() { + let error = ModelPayload::parse("model: qwen\nprofle: balanced\n").expect_err("typo"); + assert_eq!(error.to_string(), "the payload is not valid"); + + let chain = format!("{:#}", anyhow::Error::new(error)); + assert!( + chain.contains("unknown field `profle`, expected one of `model`, `profile`"), + "{chain}" + ); + } + + 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/selection.rs b/backend/cli/src/model/selection.rs new file mode 100644 index 00000000..b1753ed8 --- /dev/null +++ b/backend/cli/src/model/selection.rs @@ -0,0 +1,293 @@ +//! 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}; +use crate::{ + management::{DeploymentGroup, Manager, 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. +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(manager: &Manager, choices: &Choices<'_>) -> anyhow::Result { + let catalog = SiteCatalog::read(manager, Some(choices.model)).await?; + let Some(model) = catalog.models.first() else { + bail!("no catalog model matches {:?}", choices.model); + }; + + let targets = targets(&catalog, choices)?; + let profile = match choices.profile { + Some(reference) => resolve(ReferenceKind::Profile, reference, &model.profiles)?, + None => default_profile(&catalog, model, &targets)?, + }; + let entry = |target: &Target| entry(&catalog, model, profile, target); + let target = targets + .iter() + .find(|target| entry(target).is_some_and(fits_now)) + .or_else(|| { + targets + .iter() + .find(|target| entry(target).is_some_and(runs)) + }) + .unwrap_or(&targets[0]); + + let preview = manager + .models() + .preview_local_model_deployment(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), + ))? + .into_inner(); + + 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(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(), + }) +} + +/// One model target the deployment may use. +struct Target { + placement: ExactPlacement, + node_name: String, + target_name: String, +} + +/// The targets the choices allow, in node then target order: the named target of the named node, +/// every target of the named node, or every model target. +fn targets(catalog: &SiteCatalog, choices: &Choices<'_>) -> 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) = choices.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) = choices.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. +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(", ") + ) + }) +} + +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)) +} + +fn runs(entry: &ModelProfileCompatibility) -> bool { + entry.status() == ModelCompatibilityStatus::Runs +} + +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/template.rs b/backend/cli/src/model/template.rs new file mode 100644 index 00000000..e1a78e4b --- /dev/null +++ b/backend/cli/src/model/template.rs @@ -0,0 +1,385 @@ +//! Prints a deploy payload for one catalog model, pre-filled with what a deployment starts from, +//! ready to edit and pass to `deploy`. +//! +//! The payload names the model, profile, node, display name and route, then lists the parameters +//! with one comment each giving its catalog summary, what it accepts and, when the server knows +//! it, what fits: the largest value, or for context per request the value every parallel request +//! reaches at once. Basic parameters are written with their starting value; advanced ones, secrets and a +//! total context that still follows the others are commented out. Overrides change the written +//! values, and the fit comments follow them. + +use std::collections::BTreeMap; + +use clap::Args; +use dotcore_proto::dotcore::{ + deployment::v1::MemoryFit, + model::v1::{EstimateLocalModelResourcesRequest, EstimateLocalModelResourcesResponse}, +}; + +use super::{ + payload::ModelPayload, + selection::{Choices, Selection, select}, + view::{CONTEXT_PER_REQUEST, ParameterView, TOTAL_CONTEXT, ViewParameter}, +}; +use crate::{ + deploy::{PlainValue, Setting, ValueKind}, + management::{DeploymentGroup, Manager, ManagerArgs, call_failed}, + output::write_text, +}; + +/// Arguments for printing a deploy payload. +#[derive(Debug, Args)] +pub struct ModelTemplateArgs { + /// Catalog model: its ID, name, or a unique part of either. + #[arg(value_name = "MODEL")] + model: String, + + #[command(flatten)] + choices: ChoiceArgs, + + #[command(flatten)] + manager: ManagerArgs, +} + +/// The target, profile and overrides a deploy command may name. +#[derive(Debug, Args)] +pub(super) struct ChoiceArgs { + /// Profile ID or name; the first that fits the target by default. + #[arg(long)] + pub(super) profile: Option, + + /// Node to deploy on; the first where a profile fits by default. + #[arg(long)] + pub(super) node: Option, + + /// Execution target on the node, when it has several. + #[arg(long)] + pub(super) target: Option, + + /// Set a parameter, or an option parameter as `option..`. + #[arg(long = "set", value_name = "ID=VALUE", value_parser = Setting::parse)] + pub(super) settings: Vec, +} + +/// Prints the payload of one catalog model on the chosen target. +pub(crate) async fn model_template(arguments: ModelTemplateArgs) -> anyhow::Result<()> { + let manager = arguments.manager.connect().await?; + let choices = &arguments.choices; + let selection = select( + &manager, + &Choices { + model: &arguments.model, + profile: choices.profile.as_deref(), + node: choices.node.as_deref(), + target: choices.target.as_deref(), + }, + ) + .await?; + + let mut payload = starting_payload(&selection); + payload.apply(&choices.settings)?; + let estimate = estimate(&manager, &selection, &payload).await?; + write_text(&render(&selection, &payload, &estimate)) +} + +/// 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() + } +} + +/// Has the server estimate the payload's configuration on the selected target. +pub(super) async fn estimate( + manager: &Manager, + selection: &Selection, + payload: &ModelPayload, +) -> anyhow::Result { + let configuration = payload.configuration(&selection.schema())?; + Ok(manager + .models() + .estimate_local_model_resources(EstimateLocalModelResourcesRequest { + model_id: selection.model.model_id.clone(), + profile_id: selection.profile.profile_id.clone(), + configuration: Some(configuration), + placement: Some(selection.placement.clone()), + }) + .await + .map_err(call_failed( + DeploymentGroup::Model, + format!("estimate the memory of {}", selection.model.display_name), + ))? + .into_inner()) +} + +/// The payload text: a summary comment, the selection, then every shown parameter with its +/// guidance comment. +fn render( + selection: &Selection, + payload: &ModelPayload, + estimate: &EstimateLocalModelResourcesResponse, +) -> String { + let view = ParameterView::new( + &selection.model, + &selection.snapshot, + selection.compatibility.as_ref(), + ); + let hints = fit_hints(estimate, view.parallel_requests(&payload.parameters)); + let mut lines = vec![format!( + "# {} · {} on {} {} · {}", + selection.model.display_name, + selection.profile.profile_id, + selection.node_name, + selection.target_name, + fit_words(estimate), + )]; + lines.extend( + estimate + .hardware_class_estimates + .iter() + .filter_map(|entry| entry.launch_rejection.as_deref()) + .map(|reason| format!("# A launch would reject these values: {reason}")), + ); + + lines.push(format!("model: {}", payload.model)); + for (key, value) in [ + ("profile", &payload.profile), + ("node", &payload.node), + ("target", &payload.target), + ] { + if let Some(value) = value { + lines.push(format!("{key}: {}", quoted(value))); + } + } + if let Some(name) = &payload.name { + lines.push(format!("name: {}", quoted(name))); + } + match &payload.route { + Some(route) => lines.push(format!("route: {} # null keeps it hidden", quoted(route))), + None => lines.push("route: null".to_owned()), + } + + let (engine, options): (Vec<_>, Vec<_>) = view + .parameters + .iter() + .partition(|parameter| !parameter.option); + let entries = engine + .iter() + .map(|parameter| { + entry( + parameter, + payload.parameters.get(¶meter.key), + hints.get(parameter.key.as_str()).map(String::as_str), + " ", + ) + }) + .collect::>(); + section(&mut lines, "parameters", entries); + + let mut groups: Vec<(&str, &str, Vec)> = Vec::new(); + for parameter in options { + let (option, name) = parameter + .key + .split_once('.') + .unwrap_or((¶meter.key, "")); + let set = payload + .options + .get(option) + .and_then(|values| values.get(name)); + let entry = entry(parameter, set, None, " "); + match groups.last_mut() { + Some((last, _, entries)) if *last == option => entries.push(entry), + _ => groups.push((option, parameter.summary.as_str(), vec![entry])), + } + } + let option_entries = groups + .into_iter() + .map(|(option, summary, entries)| { + let active = entries.iter().any(|entry| entry.active); + let mut lines = Vec::new(); + if !summary.is_empty() { + lines.push(format!(" # {summary}")); + } + lines.push(format!(" {}{option}:", if active { "" } else { "# " })); + for entry in entries { + lines.extend(entry.lines); + } + Entry { active, lines } + }) + .collect::>(); + section(&mut lines, "options", option_entries); + + if !payload.custom_arguments.is_empty() { + lines.push("customArguments:".to_owned()); + lines.extend( + payload + .custom_arguments + .iter() + .map(|argument| format!(" - {}", quoted(argument))), + ); + } + + lines.push(String::new()); + lines.join("\n") +} + +/// The lines of one parameter, and whether its value is written rather than commented out. +struct Entry { + active: bool, + lines: Vec, +} + +fn entry( + parameter: &ViewParameter, + set: Option<&PlainValue>, + hint: Option<&str>, + indent: &str, +) -> Entry { + let mut comment = format!("{indent}# {}.", parameter.name); + if !parameter.option && !parameter.summary.is_empty() { + comment.push(' '); + comment.push_str(parameter.summary.trim_end_matches('.')); + comment.push('.'); + } + comment.push(' '); + comment.push_str(¶meter.accepts); + if parameter.follows && set.is_none() { + comment.push_str(". Follows context per request and parallel requests unless set"); + } + if let Some(hint) = hint { + comment.push_str(". "); + comment.push_str(hint); + } + if parameter.advanced && set.is_none() { + comment.push_str(". Advanced"); + } + + let value = set + .map(|value| plain_text(value, parameter.kind)) + .or_else(|| { + parameter + .starting + .as_deref() + .map(|text| typed_text(text, parameter.kind)) + }); + let active = set.is_some() || (!parameter.advanced && !parameter.follows && value.is_some()); + let marker = if active { "" } else { "# " }; + let key = parameter + .key + .split_once('.') + .filter(|_| parameter.option) + .map_or(parameter.key.as_str(), |(_, name)| name); + let line = match value { + Some(value) => format!("{indent}{marker}{key}: {value}"), + None => format!("{indent}# {key}:"), + }; + Entry { + active, + lines: vec![comment, line], + } +} + +/// Adds a section of entries under its key, commenting the key out when no entry is written. +fn section(lines: &mut Vec, key: &str, entries: Vec) { + if entries.is_empty() { + return; + } + let active = entries.iter().any(|entry| entry.active); + lines.push(format!("{}{key}:", if active { "" } else { "# " })); + for entry in entries { + lines.extend(entry.lines); + } +} + +/// What the estimate says fits for each parameter it bounds, by parameter ID, in the words the +/// template and the dry run show. +fn fit_hints( + estimate: &EstimateLocalModelResourcesResponse, + parallel_requests: Option, +) -> BTreeMap<&str, String> { + let mut hints: BTreeMap<&str, String> = estimate + .memory_parameter_fits + .iter() + .map(|fit| { + ( + fit.parameter_id.as_str(), + format!("Largest fit: {}", fit.largest_fit), + ) + }) + .collect(); + if let Some(tokens) = estimate.largest_context_tokens_per_request { + // The estimate's per-request value is the one every parallel request reaches at once, + // not the most one request may use, so the hint says so. + hints.insert( + CONTEXT_PER_REQUEST, + format!("Fits {}: {tokens}", all_at_once(parallel_requests)), + ); + } + if let Some(tokens) = estimate.largest_total_context_tokens { + hints.insert(TOTAL_CONTEXT, format!("Largest fit: {tokens}")); + } + hints +} + +/// The words for every parallel request running at once, naming their count when it is known. +pub(super) fn all_at_once(parallel_requests: Option) -> String { + match parallel_requests { + Some(count) => format!("all {count} at once"), + None => "all requests at once".to_owned(), + } +} + +fn fit_words(estimate: &EstimateLocalModelResourcesResponse) -> &'static str { + match estimate + .placement_preview + .as_ref() + .map(|preview| preview.free_memory_fit()) + { + Some(MemoryFit::Fits) => "fits now", + Some(MemoryFit::Exceeds) => "exceeds free memory", + _ => "fit unknown", + } +} + +/// A written value as YAML: text quoted, booleans and numbers as they are. +fn typed_text(text: &str, kind: ValueKind) -> String { + match kind { + ValueKind::Text => quoted(text), + ValueKind::Boolean | ValueKind::UnsignedInteger => text.to_owned(), + } +} + +fn plain_text(value: &PlainValue, kind: ValueKind) -> String { + match value { + PlainValue::Boolean(value) => value.to_string(), + PlainValue::Number(value) => value.to_string(), + PlainValue::Text(text) => typed_text(text, kind), + } +} + +/// Text as a YAML scalar: plain when it reads back as the same text, else a JSON string. +fn quoted(text: &str) -> String { + let plain = !text.is_empty() + && text + .chars() + .all(|character| character.is_ascii_alphanumeric() || "-_.".contains(character)) + && text.parse::().is_err() + && !matches!( + text, + "true" | "false" | "null" | "yes" | "no" | "on" | "off" | "~" + ); + if plain { + text.to_owned() + } else { + serde_json::to_string(text).expect("a string serializes as JSON") + } +} diff --git a/backend/cli/src/model/view.rs b/backend/cli/src/model/view.rs new file mode 100644 index 00000000..645d2187 --- /dev/null +++ b/backend/cli/src/model/view.rs @@ -0,0 +1,594 @@ +//! 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 std::collections::BTreeMap; + +use super::payload::{engine_kind, option_kind}; +use crate::deploy::{PlainValue, 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(Debug, Eq, PartialEq)] +pub(super) struct ViewParameter { + /// The key a payload and `--set` use: the engine parameter ID, or `