diff --git a/.config/nextest.toml b/.config/nextest.toml index 674826e7b25..40fd53943e3 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -43,7 +43,7 @@ default-filter = ''' | test(/^export_observations::/) | test(/^fabric_deployment::/) | test(/^multiple_providers::/) | test(/^remote_service::/) | test(/^inference_discovery::/) | test(/^helm_recovery::/) - | test(/^travel_example::/) + | test(/^travel_example::/) | test(/^cluster_models::/) | test(/^travel_team_example::/) )) ''' diff --git a/crates/nemoclaw-authoring/tests/deployment_journey.rs b/crates/nemoclaw-authoring/tests/deployment_journey.rs index 497655dadd0..be589776eea 100644 --- a/crates/nemoclaw-authoring/tests/deployment_journey.rs +++ b/crates/nemoclaw-authoring/tests/deployment_journey.rs @@ -290,7 +290,7 @@ fn single_sandbox_examples_offer_existing_sdk_values_without_changing_them() { ); covered += 1; } - assert_eq!(covered, 39); + assert_eq!(covered, 41); } #[test] diff --git a/crates/nemoclaw-backend/src/error.rs b/crates/nemoclaw-backend/src/error.rs index 201152582d1..4ae6e1427f1 100644 --- a/crates/nemoclaw-backend/src/error.rs +++ b/crates/nemoclaw-backend/src/error.rs @@ -17,6 +17,10 @@ pub enum Error { "Docker model service '{service}' is preserved by updatePolicy: Preserve; replacing a running or incompletely observed container requires explicit updatePolicy: Recreate, which permits downtime if the replacement cannot start; resources retained" )] DockerModelUpdateRefused { service: String }, + #[error( + "cluster model service '{service}' is preserved by updatePolicy: Preserve; replacing its model Pod requires explicit updatePolicy: Recreate, which permits downtime if the replacement cannot start; resources retained" + )] + ClusterModelUpdateRefused { service: String }, #[error("gateway is incompatible with this configuration: {0}")] GatewayIncompatible(String), #[error( diff --git a/crates/nemoclaw-build/src/hashicorp_provider.rs b/crates/nemoclaw-build/src/hashicorp_provider.rs new file mode 100644 index 00000000000..aaf3ed666fe --- /dev/null +++ b/crates/nemoclaw-build/src/hashicorp_provider.rs @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::{collections::BTreeMap, fs, path::Path}; + +/// Install a HashiCorp provider release's binary at `path` and its unchanged +/// upstream license at `license`, both from a checksum-verified archive. +pub(crate) fn install( + root: &Path, + archive: &[u8], + path: &str, + license: &str, +) -> Result, Box> { + let name = path.rsplit('/').next().ok_or("missing provider name")?; + let binary = crate::extract_entry(archive, name, 256 << 20)?; + let license_text = crate::extract_entry(archive, "LICENSE.txt", 1 << 20)?; + let mut files = BTreeMap::new(); + for (relative, bytes) in [ + (path, binary.as_slice()), + (license, license_text.as_slice()), + ] { + let destination = root.join(relative); + fs::create_dir_all(destination.parent().ok_or("missing bundle parent")?)?; + fs::write(&destination, bytes)?; + files.insert( + relative.to_owned(), + nemoclaw_sdk::bundle::hash_file(&destination)?, + ); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(root.join(path), fs::Permissions::from_mode(0o755))?; + } + Ok(files) +} diff --git a/crates/nemoclaw-build/src/helm_provider.rs b/crates/nemoclaw-build/src/helm_provider.rs index 7ba44846cd1..7e4ef0ac59e 100644 --- a/crates/nemoclaw-build/src/helm_provider.rs +++ b/crates/nemoclaw-build/src/helm_provider.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use std::{collections::BTreeMap, fs, path::Path}; +use std::{collections::BTreeMap, path::Path}; // Release v3.3.0, source revision 0e0a60f31821ab5d2948daecb882a1ac27a98405. // On 2026-10-06, versions.json archive pins were verified against the official @@ -17,27 +17,10 @@ pub fn install( if version != nemoclaw_sdk::kubernetes::gateway::PROVIDER_VERSION { return Err("unsupported Helm provider version".into()); } - let path = nemoclaw_sdk::bundle::helm_provider_path(platform)?; - let name = path.rsplit('/').next().ok_or("missing provider name")?; - let binary = crate::extract_entry(archive, name, 256 << 20)?; - let license = crate::extract_entry(archive, "LICENSE.txt", 1 << 20)?; - let mut files = BTreeMap::new(); - for (relative, bytes) in [ - (path.as_str(), binary.as_slice()), - ("licenses/helm-provider-LICENSE", license.as_slice()), - ] { - let destination = root.join(relative); - fs::create_dir_all(destination.parent().ok_or("missing bundle parent")?)?; - fs::write(&destination, bytes)?; - files.insert( - relative.to_owned(), - nemoclaw_sdk::bundle::hash_file(&destination)?, - ); - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(root.join(path), fs::Permissions::from_mode(0o755))?; - } - Ok(files) + crate::hashicorp_provider::install( + root, + archive, + &nemoclaw_sdk::bundle::helm_provider_path(platform)?, + "licenses/helm-provider-LICENSE", + ) } diff --git a/crates/nemoclaw-build/src/kubernetes_provider.rs b/crates/nemoclaw-build/src/kubernetes_provider.rs new file mode 100644 index 00000000000..3add6b49400 --- /dev/null +++ b/crates/nemoclaw-build/src/kubernetes_provider.rs @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::{collections::BTreeMap, path::Path}; + +// Release v3.3.0, source revision a612b9cfce0fd1321cf2d25084b07b8fccd79737. +// On 2026-10-19, versions.json archive pins were verified against the official +// SHA256SUMS signature using HashiCorp's published signing key fingerprint +// C874011F0AB405110D02105534365D9472D7468F. Upstream binary and license are unchanged. +/// Install the binary and unchanged upstream license from a checksum-verified release. +pub fn install( + root: &Path, + archive: &[u8], + version: &str, + platform: &str, +) -> Result, Box> { + if version != nemoclaw_sdk::kubernetes::models::PROVIDER_VERSION { + return Err("unsupported Kubernetes provider version".into()); + } + crate::hashicorp_provider::install( + root, + archive, + &nemoclaw_sdk::bundle::kubernetes_provider_path(platform)?, + "licenses/kubernetes-provider-LICENSE", + ) +} diff --git a/crates/nemoclaw-build/src/lib.rs b/crates/nemoclaw-build/src/lib.rs index 77bf5cc22a4..7b693f52c04 100644 --- a/crates/nemoclaw-build/src/lib.rs +++ b/crates/nemoclaw-build/src/lib.rs @@ -10,9 +10,13 @@ pub mod docs; #[cfg(feature = "sdk")] pub mod fern; #[cfg(feature = "sdk")] +mod hashicorp_provider; +#[cfg(feature = "sdk")] pub mod helm_provider; pub mod images; #[cfg(feature = "sdk")] +pub mod kubernetes_provider; +#[cfg(feature = "sdk")] pub mod schema; mod source; pub use source::{hex, source_inputs, source_version}; diff --git a/crates/nemoclaw-build/src/main.rs b/crates/nemoclaw-build/src/main.rs index 823c8219119..54a5ac12b3a 100644 --- a/crates/nemoclaw-build/src/main.rs +++ b/crates/nemoclaw-build/src/main.rs @@ -206,6 +206,9 @@ struct Pins { #[cfg(feature = "sdk")] #[serde(rename = "helmProvider")] helm_provider: String, + #[cfg(feature = "sdk")] + #[serde(rename = "kubernetesProvider")] + kubernetes_provider: String, platforms: std::collections::BTreeMap>, /// Pinned OpenShell images; the Docker live tests pull these. #[serde(default)] @@ -366,6 +369,13 @@ async fn bundle(pins: &Pins, platform: &str) -> Result<()> { .ok_or("missing Helm provider platform pin")?, ) .await?; + let kubernetes_archive = download( + pins.platforms + .get(platform) + .and_then(|p| p.get("kubernetesProvider")) + .ok_or("missing Kubernetes provider platform pin")?, + ) + .await?; let version = nemoclaw_build::BUILDER_SOURCE_VERSION.to_owned(); nemoclaw_build::verify_source_version(&version, &sources()?)?; let target = target(platform)?; @@ -478,6 +488,14 @@ async fn bundle(pins: &Pins, platform: &str) -> Result<()> { &pins.helm_provider, platform, )?); + manifest + .files + .extend(nemoclaw_build::kubernetes_provider::install( + root, + &kubernetes_archive, + &pins.kubernetes_provider, + platform, + )?); nemoclaw_build::schema::add_to_bundle(root, &mut manifest)?; nemoclaw_build::verify_source_version(&version, &sources()?)?; fs::write( diff --git a/crates/nemoclaw-build/tests/artifacts.rs b/crates/nemoclaw-build/tests/artifacts.rs index 03a07aff87e..3263a7a6c1a 100644 --- a/crates/nemoclaw-build/tests/artifacts.rs +++ b/crates/nemoclaw-build/tests/artifacts.rs @@ -43,29 +43,32 @@ fn pinned_archive_extracts_only_the_exact_native_binary() { } #[test] -fn every_bundle_platform_pins_the_official_helm_provider_archive() { +fn every_bundle_platform_pins_the_official_hashicorp_provider_archives() { let pins: serde_json::Value = serde_json::from_str(include_str!("../../../versions.json")).unwrap(); - let version = pins["helmProvider"] - .as_str() - .expect("pinned Helm provider version"); - for platform in [ - "linux_arm64", - "linux_amd64", - "darwin_arm64", - "darwin_amd64", - "windows_amd64", + for (pin, name) in [ + ("helmProvider", "helm"), + ("kubernetesProvider", "kubernetes"), ] { - let artifact = &pins["platforms"][platform]["helmProvider"]; - assert_eq!( - artifact["url"], - format!( - "https://releases.hashicorp.com/terraform-provider-helm/{version}/terraform-provider-helm_{version}_{platform}.zip" - ) - ); - let checksum = artifact["sha256"].as_str().unwrap(); - assert_eq!(checksum.len(), 64); - assert!(checksum.bytes().all(|byte| byte.is_ascii_hexdigit())); + let version = pins[pin].as_str().expect("pinned provider version"); + for platform in [ + "linux_arm64", + "linux_amd64", + "darwin_arm64", + "darwin_amd64", + "windows_amd64", + ] { + let artifact = &pins["platforms"][platform][pin]; + assert_eq!( + artifact["url"], + format!( + "https://releases.hashicorp.com/terraform-provider-{name}/{version}/terraform-provider-{name}_{version}_{platform}.zip" + ) + ); + let checksum = artifact["sha256"].as_str().unwrap(); + assert_eq!(checksum.len(), 64); + assert!(checksum.bytes().all(|byte| byte.is_ascii_hexdigit())); + } } } @@ -181,101 +184,115 @@ fn docker_provider_bundle_retains_the_verified_binary_and_license() { ); } +/// A bundled HashiCorp provider: its name and installer. +#[cfg(feature = "sdk")] +type Installer = + fn( + &std::path::Path, + &[u8], + &str, + &str, + ) -> Result, Box>; +#[cfg(feature = "sdk")] +const HASHICORP_PROVIDERS: [(&str, Installer); 2] = [ + ("helm", nemoclaw_build::helm_provider::install), + ("kubernetes", nemoclaw_build::kubernetes_provider::install), +]; + #[cfg(feature = "sdk")] #[test] -fn helm_provider_bundle_retains_the_native_binary_and_upstream_license() { - for platform in [ - "linux_arm64", - "linux_amd64", - "darwin_arm64", - "darwin_amd64", - "windows_amd64", - ] { - let extension = if platform == "windows_amd64" { - ".exe" - } else { - "" - }; - let name = format!("terraform-provider-helm_v3.3.0_x5{extension}"); - let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); - for (entry, bytes) in [ - (name.as_str(), "native provider"), - ("LICENSE.txt", "unchanged upstream MPL license"), +fn hashicorp_provider_bundles_retain_the_native_binary_and_upstream_license() { + for (provider, install) in HASHICORP_PROVIDERS { + for platform in [ + "linux_arm64", + "linux_amd64", + "darwin_arm64", + "darwin_amd64", + "windows_amd64", ] { - zip.start_file(entry, zip::write::SimpleFileOptions::default()) - .unwrap(); - zip.write_all(bytes.as_bytes()).unwrap(); - } - let archive = zip.finish().unwrap().into_inner(); - let root = tempfile::tempdir().unwrap(); - let files = - nemoclaw_build::helm_provider::install(root.path(), &archive, "3.3.0", platform) - .unwrap(); - let binary = - format!("providers/registry.opentofu.org/hashicorp/helm/3.3.0/{platform}/{name}"); - assert_eq!( - std::fs::read(root.path().join(&binary)).unwrap(), - b"native provider" - ); - assert_eq!( - std::fs::read(root.path().join("licenses/helm-provider-LICENSE")).unwrap(), - b"unchanged upstream MPL license" - ); - assert_eq!(files.len(), 2); - for (path, hash) in files { + let extension = if platform == "windows_amd64" { + ".exe" + } else { + "" + }; + let name = format!("terraform-provider-{provider}_v3.3.0_x5{extension}"); + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + for (entry, bytes) in [ + (name.as_str(), "native provider"), + ("LICENSE.txt", "unchanged upstream MPL license"), + ] { + zip.start_file(entry, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(bytes.as_bytes()).unwrap(); + } + let archive = zip.finish().unwrap().into_inner(); + let root = tempfile::tempdir().unwrap(); + let files = install(root.path(), &archive, "3.3.0", platform).unwrap(); + let binary = format!( + "providers/registry.opentofu.org/hashicorp/{provider}/3.3.0/{platform}/{name}" + ); assert_eq!( - hash, - nemoclaw_sdk::bundle::hash_file(&root.path().join(path)).unwrap() + std::fs::read(root.path().join(&binary)).unwrap(), + b"native provider" ); - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; assert_eq!( - std::fs::metadata(root.path().join(binary)) - .unwrap() - .permissions() - .mode() - & 0o777, - 0o755 + std::fs::read( + root.path() + .join(format!("licenses/{provider}-provider-LICENSE")) + ) + .unwrap(), + b"unchanged upstream MPL license" ); + assert_eq!(files.len(), 2); + for (path, hash) in files { + assert_eq!( + hash, + nemoclaw_sdk::bundle::hash_file(&root.path().join(path)).unwrap() + ); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(root.path().join(binary)) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o755 + ); + } } } } #[cfg(feature = "sdk")] #[test] -fn helm_provider_rejects_incomplete_or_substituted_inputs_before_writing() { - for (name, version, platform) in [ - ("terraform-provider-helm_v3.3.0_x5", "3.3.0", "linux_amd64"), - ("LICENSE.txt", "3.3.0", "linux_amd64"), - ("terraform-provider-helm_v3.3.0_x5", "3.2.0", "linux_amd64"), - ( - "terraform-provider-helm_v3.3.0_x5", - "3.3.0", - "../../outside", - ), - ( - "terraform-provider-helm_v3.3.0_x5", - "3.3.0", - "windows_amd64", - ), - ( - "nested/terraform-provider-helm_v3.3.0_x5", - "3.3.0", - "linux_amd64", - ), - ] { - let root = tempfile::tempdir().unwrap(); - assert!( - nemoclaw_build::helm_provider::install( - root.path(), - &archive(name, b"fixture"), - version, - platform - ) - .is_err() - ); - assert!(std::fs::read_dir(root.path()).unwrap().next().is_none()); +fn hashicorp_providers_reject_incomplete_or_substituted_inputs_before_writing() { + for (provider, install) in HASHICORP_PROVIDERS { + let binary = format!("terraform-provider-{provider}_v3.3.0_x5"); + let other = if provider == "helm" { + "kubernetes" + } else { + "helm" + }; + let substituted = format!("terraform-provider-{other}_v3.3.0_x5"); + let nested = format!("nested/{binary}"); + for (name, version, platform) in [ + (binary.as_str(), "3.3.0", "linux_amd64"), + ("LICENSE.txt", "3.3.0", "linux_amd64"), + (substituted.as_str(), "3.3.0", "linux_amd64"), + (binary.as_str(), "3.2.0", "linux_amd64"), + (binary.as_str(), "3.3.0", "../../outside"), + (binary.as_str(), "3.3.0", "windows_amd64"), + (nested.as_str(), "3.3.0", "linux_amd64"), + ] { + let root = tempfile::tempdir().unwrap(); + assert!( + install(root.path(), &archive(name, b"fixture"), version, platform).is_err(), + "{provider}: {name} {version} {platform}" + ); + assert!(std::fs::read_dir(root.path()).unwrap().next().is_none()); + } } } diff --git a/crates/nemoclaw-build/tests/ci.rs b/crates/nemoclaw-build/tests/ci.rs index 29cc990b08e..d45611aa78c 100644 --- a/crates/nemoclaw-build/tests/ci.rs +++ b/crates/nemoclaw-build/tests/ci.rs @@ -46,7 +46,7 @@ fn live_kind_requires_its_bundle_before_downloading_tools_or_creating_a_cluster( root.path().join("versions.json"), serde_json::json!({ "rust":"1.98.1", "protobuf":"36.1", "nextest":"0.9.144", - "opentofu":"1.12.6", "dockerProvider":"4.6.0", "helmProvider":"3.3.0", + "opentofu":"1.12.6", "dockerProvider":"4.6.0", "helmProvider":"3.3.0", "kubernetesProvider":"3.3.0", "platforms":{}, "images":{"kindNode":"kindest/node@sha256:fixture"} }) .to_string(), @@ -99,7 +99,7 @@ fn cargo_steps_do_not_inherit_the_package_description_from_cargo_run() { root.path().join("versions.json"), serde_json::json!({ "rust":"1.98.1", "protobuf":"36.1", "nextest":"0.9.144", - "opentofu":"1.12.6", "dockerProvider":"4.6.0", "helmProvider":"3.3.0", + "opentofu":"1.12.6", "dockerProvider":"4.6.0", "helmProvider":"3.3.0", "kubernetesProvider":"3.3.0", "platforms":{} }) .to_string(), diff --git a/crates/nemoclaw-cli/src/formatting.rs b/crates/nemoclaw-cli/src/formatting.rs index b85c6960c1f..8decfe594ad 100644 --- a/crates/nemoclaw-cli/src/formatting.rs +++ b/crates/nemoclaw-cli/src/formatting.rs @@ -588,6 +588,9 @@ pub(crate) fn render_error( Some(Error::DockerModelUpdateRefused { service }) => Some(Cow::Owned(format!( "To replace the running model container, set spec.services.{service}.updatePolicy: Recreate and apply again; the model is unavailable until the replacement starts. See docs/inference.md#set-container-limits-and-update-policy." ))), + Some(Error::ClusterModelUpdateRefused { service }) => Some(Cow::Owned(format!( + "To replace the model Pod, set spec.services.{service}.updatePolicy: Recreate and apply again; the model is unavailable until the replacement is ready. See docs/kubernetes.md#run-a-managed-model-service." + ))), _ => None, }; if let Some(help) = &help { diff --git a/crates/nemoclaw-e2e/tests/cluster_models.rs b/crates/nemoclaw-e2e/tests/cluster_models.rs new file mode 100644 index 00000000000..b5d8999d76b --- /dev/null +++ b/crates/nemoclaw-e2e/tests/cluster_models.rs @@ -0,0 +1,209 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +//! Managed cluster model services, compiled by the SDK, validate and plan +//! with the bundled Kubernetes, vLLM and Ollama providers: the objects match +//! the Kubernetes provider's schema, and their containers run what the runtime +//! contract says. Planning their creation contacts no cluster. + +use nemoclaw_sdk::{bundle::Bundle, compile, config::Document}; +use serde_json::{Value, json}; +use std::{fs, path::Path, time::Duration}; + +const OBJECTS: [&str; 4] = [ + "kubernetes_persistent_volume_claim_v1", + "kubernetes_deployment_v1", + "kubernetes_service_v1", + "kubernetes_network_policy_v1", +]; + +async fn tofu(bundle: &Bundle, directory: &Path, arguments: &[&str]) -> std::process::Output { + let mut command = tokio::process::Command::new(bundle.tofu()); + command + .args(arguments) + .current_dir(directory) + .env_clear() + .env("PATH", directory.join("empty-path")) + .env("HOME", directory.join("home")) + .env("TF_IN_AUTOMATION", "1") + .env("TF_INPUT", "0") + .env("CHECKPOINT_DISABLE", "1") + .env("TF_CLI_CONFIG_FILE", directory.join("providers.tfrc")) + .kill_on_drop(true); + // Go plugins on Windows need the system's own settings to start, as the + // SDK passes them to its providers. + for name in [ + "SYSTEMROOT", + "SYSTEMDRIVE", + "WINDIR", + "TEMP", + "TMP", + "USERPROFILE", + "APPDATA", + "LOCALAPPDATA", + "PROGRAMDATA", + ] { + if let Some(value) = std::env::var_os(name) { + command.env(name, value); + } + } + tokio::time::timeout(Duration::from_secs(180), command.output()) + .await + .expect("OpenTofu timed out") + .expect("cannot execute the verified bundle's OpenTofu") +} + +/// The model objects of a compiled graph and the runtime contracts they read, +/// with the Kubernetes provider pointed at a cluster that does not exist. +fn model_objects(graph: &Value, kubeconfig: &Path) -> Value { + let mut objects = json!({ + "terraform": {"required_providers": {}}, + "provider": {"kubernetes": { + "config_path": kubeconfig.to_string_lossy(), + "config_context": graph["provider"]["kubernetes"]["config_context"], + }}, + "data": graph["data"], + "resource": {}, + }); + for name in ["kubernetes", "vllm", "ollama"] { + objects["terraform"]["required_providers"][name] = + graph["terraform"]["required_providers"][name].clone(); + } + for kind in OBJECTS { + let mut resources = graph["resource"][kind].clone(); + for body in resources.as_object_mut().unwrap().values_mut() { + // The gateway's namespace storage is not part of this graph. + body["depends_on"] + .as_array_mut() + .unwrap() + .retain(|address| { + OBJECTS + .iter() + .any(|kind| address.as_str().unwrap().starts_with(kind)) + }); + } + objects["resource"][kind] = resources; + } + objects +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "requires NEMOCLAW_TEST_BUNDLE; no cluster"] +async fn cluster_model_objects_plan_with_the_bundled_providers() { + let input = std::env::var_os("NEMOCLAW_TEST_BUNDLE") + .expect("NEMOCLAW_TEST_BUNDLE names a verified bundle"); + let bundle = Bundle::open(Path::new(&input)).unwrap(); + for (kind, source) in [ + ( + "vllm", + include_str!("../../test-support/cluster-models/vllm.yaml"), + ), + ( + "ollama", + include_str!("../../test-support/cluster-models/ollama.yaml"), + ), + ] { + let document = Document::parse(source.as_bytes()).unwrap(); + let generations = [ + "workspace", + "provider", + "sandbox", + "kubernetes_storage", + "kubernetes_gateway", + "inference_service", + "ollama_service", + ] + .map(|kind| (kind.into(), "a".repeat(32))) + .into(); + let graph = + compile::compile_runtime(&document, &generations, &bundle.manifest.version).unwrap(); + let directory = tempfile::tempdir().unwrap(); + for name in ["empty-path", "home"] { + fs::create_dir(directory.path().join(name)).unwrap(); + } + let mirror = serde_json::to_string( + &bundle + .directory + .join("providers") + .to_string_lossy() + .replace('\\', "/"), + ) + .unwrap(); + fs::write( + directory.path().join("providers.tfrc"), + format!("provider_installation {{ filesystem_mirror {{ path = {mirror} }} }}\n"), + ) + .unwrap(); + // Nothing listens on port 9, so any cluster request fails the plan. + let kubeconfig = directory.path().join("kubeconfig"); + fs::write( + &kubeconfig, + json!({"apiVersion":"v1", "kind":"Config", + "clusters":[{"name":"none", "cluster":{"server":"https://127.0.0.1:9"}}], + "contexts":[{"name":"replace-with-explicit-context", "context":{"cluster":"none", "user":"none"}}], + "users":[{"name":"none", "user":{}}]}) + .to_string(), + ) + .unwrap(); + fs::write( + directory.path().join("main.tf.json"), + serde_json::to_vec(&model_objects(&graph, &kubeconfig)).unwrap(), + ) + .unwrap(); + for arguments in [ + &["init", "-input=false", "-no-color"][..], + &["validate", "-no-color"], + &["plan", "-input=false", "-no-color", "-out=plan"], + ] { + let output = tofu(&bundle, directory.path(), arguments).await; + assert!( + output.status.success(), + "{kind}: tofu {arguments:?}\n{}", + String::from_utf8_lossy(&output.stderr) + ); + } + let shown = tofu(&bundle, directory.path(), &["show", "-json", "plan"]).await; + let plan: Value = serde_json::from_slice(&shown.stdout).unwrap(); + let changes = plan["resource_changes"].as_array().unwrap(); + assert_eq!(changes.len(), 4, "{kind}"); + assert!( + changes + .iter() + .all(|change| change["change"]["actions"] == json!(["create"])) + ); + let deployment = changes + .iter() + .find(|change| change["type"] == "kubernetes_deployment_v1") + .unwrap(); + let container = + &deployment["change"]["after"]["spec"][0]["template"][0]["spec"][0]["container"][0]; + assert_eq!( + container["command"], + json!(["/usr/local/bin/nemoclaw-runtime"]) + ); + assert_eq!( + container["readiness_probe"][0]["exec"][0]["command"], + json!([nemoclaw_runtime::READY_ENTRYPOINT]) + ); + let port = match &document.spec.services["qwen"] { + nemoclaw_sdk::services::ServiceDefinition::Vllm(service) => service.serving.port, + nemoclaw_sdk::services::ServiceDefinition::Ollama(service) => service.serving.port, + _ => unreachable!(), + }; + assert_eq!(container["port"][0]["container_port"], port); + let environment: Vec<&str> = container["env"] + .as_array() + .unwrap() + .iter() + .map(|variable| variable["name"].as_str().unwrap()) + .collect(); + assert!( + environment.contains(&"NEMOCLAW_RUNTIME_SPEC"), + "{environment:?}" + ); + assert_eq!( + environment.contains(&nemoclaw_runtime::INFERENCE_KEY_ENV), + kind == "vllm", + "{environment:?}" + ); + } +} diff --git a/crates/nemoclaw-e2e/tests/main.rs b/crates/nemoclaw-e2e/tests/main.rs index e0d9732e3dd..504efb723ea 100644 --- a/crates/nemoclaw-e2e/tests/main.rs +++ b/crates/nemoclaw-e2e/tests/main.rs @@ -25,6 +25,8 @@ mod fabric_deployment; #[path = "fabric_live.rs"] mod fabric_live; // Unix only, as before it moved here from nemoclaw-sdk. +#[path = "cluster_models.rs"] +mod cluster_models; #[cfg(target_os = "linux")] mod docker_registry; #[cfg(unix)] diff --git a/crates/nemoclaw-sdk/build.rs b/crates/nemoclaw-sdk/build.rs index 16842868238..9b15567f056 100644 --- a/crates/nemoclaw-sdk/build.rs +++ b/crates/nemoclaw-sdk/build.rs @@ -18,6 +18,7 @@ fn main() { ("DEVELOPMENT_ISSUER_IMAGE", "/images/developmentIssuer"), ("OPENTOFU_VERSION", "/opentofu"), ("HELM_PROVIDER_VERSION", "/helmProvider"), + ("KUBERNETES_PROVIDER_VERSION", "/kubernetesProvider"), ] { let value = pins .pointer(pointer) diff --git a/crates/nemoclaw-sdk/src/bundle/mod.rs b/crates/nemoclaw-sdk/src/bundle/mod.rs index f8bff362054..b1786b9436e 100644 --- a/crates/nemoclaw-sdk/src/bundle/mod.rs +++ b/crates/nemoclaw-sdk/src/bundle/mod.rs @@ -270,26 +270,50 @@ pub fn required_files(version: &str) -> Result, Error> { ), helm_provider_path(&platform()?)?, "licenses/helm-provider-LICENSE".into(), + kubernetes_provider_path(&platform()?)?, + "licenses/kubernetes-provider-LICENSE".into(), crate::config::schema::SCHEMA_PATH.into(), ]) } pub fn helm_provider_path(platform: &str) -> Result { + hashicorp_provider_path( + "helm", + crate::kubernetes::gateway::PROVIDER_ADDRESS, + crate::kubernetes::gateway::PROVIDER_VERSION, + platform, + ) +} + +pub fn kubernetes_provider_path(platform: &str) -> Result { + hashicorp_provider_path( + "kubernetes", + crate::kubernetes::models::PROVIDER_ADDRESS, + crate::kubernetes::models::PROVIDER_VERSION, + platform, + ) +} + +/// Where the bundle keeps a HashiCorp release of provider `name`. +fn hashicorp_provider_path( + name: &str, + address: &str, + version: &str, + platform: &str, +) -> Result { if !matches!( platform, "linux_arm64" | "linux_amd64" | "darwin_arm64" | "darwin_amd64" | "windows_amd64" ) { - return Err(Error::Bundle("unsupported Helm provider platform")); + return Err(Error::Bundle("unsupported HashiCorp provider platform")); } let extension = if platform.starts_with("windows") { ".exe" } else { "" }; - let address = crate::kubernetes::gateway::PROVIDER_ADDRESS; - let version = crate::kubernetes::gateway::PROVIDER_VERSION; Ok(format!( - "providers/{address}/{version}/{platform}/terraform-provider-helm_v{version}_x5{extension}" + "providers/{address}/{version}/{platform}/terraform-provider-{name}_v{version}_x5{extension}" )) } diff --git a/crates/nemoclaw-sdk/src/bundle/tests.rs b/crates/nemoclaw-sdk/src/bundle/tests.rs index 5fa34ec0bce..8d8f4398e20 100644 --- a/crates/nemoclaw-sdk/src/bundle/tests.rs +++ b/crates/nemoclaw-sdk/src/bundle/tests.rs @@ -4,46 +4,52 @@ use super::*; #[test] -fn bundle_rejects_a_missing_or_tampered_helm_provider() { - let directory = tempfile::tempdir().unwrap(); - let helm = format!( - "providers/registry.opentofu.org/hashicorp/helm/3.3.0/{}/{}", - platform().unwrap(), - executable("terraform-provider-helm_v3.3.0_x5") - ); - let mut manifest = Manifest { - version: "0.1.0".into(), - rust: "1.98.1".into(), - opentofu: crate::compile::OPENTOFU_VERSION.into(), - files: Default::default(), - }; - for name in required_files(&manifest.version).unwrap() { - if name == helm { - continue; +fn bundle_rejects_a_missing_or_tampered_hashicorp_provider() { + for provider in [ + helm_provider_path(&platform().unwrap()).unwrap(), + kubernetes_provider_path(&platform().unwrap()).unwrap(), + ] { + let directory = tempfile::tempdir().unwrap(); + let mut manifest = Manifest { + version: "0.1.0".into(), + rust: "1.98.1".into(), + opentofu: crate::compile::OPENTOFU_VERSION.into(), + files: Default::default(), + }; + for name in required_files(&manifest.version).unwrap() { + if name == provider { + continue; + } + let path = directory.path().join(&name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, b"fixture binary").unwrap(); + manifest.files.insert(name, hash_file(&path).unwrap()); } - let path = directory.path().join(&name); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(&path, b"fixture binary").unwrap(); - manifest.files.insert(name, hash_file(&path).unwrap()); - } - let manifest_path = directory.path().join("manifest.json"); - fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap(); - assert!( - Bundle::open(directory.path()).is_err(), - "a bundle without its pinned Helm provider must be rejected" - ); + let manifest_path = directory.path().join("manifest.json"); + fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap(); + assert!( + Bundle::open(directory.path()).is_err(), + "a bundle without its pinned {provider} must be rejected" + ); - let helm_path = directory.path().join(&helm); - fs::create_dir_all(helm_path.parent().unwrap()).unwrap(); - fs::write(&helm_path, b"provider binary").unwrap(); - manifest.files.insert(helm, hash_file(&helm_path).unwrap()); - fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap(); - Bundle::open(directory.path()).unwrap(); + let provider_path = directory.path().join(&provider); + fs::create_dir_all(provider_path.parent().unwrap()).unwrap(); + fs::write(&provider_path, b"provider binary").unwrap(); + manifest + .files + .insert(provider.clone(), hash_file(&provider_path).unwrap()); + fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap(); + Bundle::open(directory.path()).unwrap(); - fs::write(&helm_path, b"tampered provider").unwrap(); - assert!(Bundle::open(directory.path()).is_err()); - fs::remove_file(&helm_path).unwrap(); - assert!(Bundle::open(directory.path()).is_err()); + fs::write(&provider_path, b"tampered provider").unwrap(); + assert!(Bundle::open(directory.path()).is_err()); + fs::remove_file(&provider_path).unwrap(); + assert!(Bundle::open(directory.path()).is_err()); + } + assert_eq!( + kubernetes_provider_path("linux_arm64").unwrap(), + "providers/registry.opentofu.org/hashicorp/kubernetes/3.3.0/linux_arm64/terraform-provider-kubernetes_v3.3.0_x5" + ); } #[test] diff --git a/crates/nemoclaw-sdk/src/compile_runtime.rs b/crates/nemoclaw-sdk/src/compile_runtime.rs index 36b7b4835e1..3e9ea69208e 100644 --- a/crates/nemoclaw-sdk/src/compile_runtime.rs +++ b/crates/nemoclaw-sdk/src/compile_runtime.rs @@ -79,6 +79,7 @@ fn runtime_targets_with_plans( ("chart".into(), crate::kubernetes::gateway::CHART.into()), ]), }); + targets.extend(service_plans.targets().cloned()); return Ok(targets); } let Some(settings) = document.spec.gateway.as_managed() else { @@ -143,10 +144,11 @@ pub(crate) fn runtime_graph( graph.as_object_mut().unwrap().remove("output"); graph["resource"] = json!({}); let targets = runtime_targets_with_plans(document, generations, &service_plans)?; - for target in targets - .iter() - .filter(|target| target.kind != "helm_release") - { + // The Helm release and model service objects get their bodies below. + for target in targets.iter().filter(|target| { + target.kind != "helm_release" + && !crate::services::cluster::is_cluster_kind(&target.kind) + }) { // The environment list travels as JSON in the target row. let mut attributes = json!({}); for (name, value) in &target.values { @@ -179,6 +181,7 @@ pub(crate) fn runtime_graph( "managed Kubernetes gateway settings are missing", ))?; crate::kubernetes::gateway::configure(&mut graph, &spec)?; + crate::kubernetes::models::configure(&mut graph, document, generations)?; return Ok((graph, targets)); } // Readiness follows gateway reconciliation, including restart or replacement. diff --git a/crates/nemoclaw-sdk/src/config/inference.rs b/crates/nemoclaw-sdk/src/config/inference.rs index 462fa2cff98..fbcb0ab8675 100644 --- a/crates/nemoclaw-sdk/src/config/inference.rs +++ b/crates/nemoclaw-sdk/src/config/inference.rs @@ -39,12 +39,12 @@ impl Document { endpoint: endpoint.into(), credential: credential.cloned(), }), - InferenceTarget::Service { .. } => { + InferenceTarget::Service { credential, .. } => { let service = crate::services::resolve(self, provider)? .ok_or(ConfigError::new("missing inference service"))?; Ok(InferenceConnection { endpoint: service.endpoint, - credential: None, + credential: credential.cloned(), }) } } @@ -61,6 +61,8 @@ pub enum InferenceTarget<'a> { }, Service { name: &'a str, + /// The key of an authenticated cluster service, where OpenTofu runs. + credential: Option<&'a SecretRef>, }, } @@ -68,17 +70,18 @@ impl InferenceProvider { /// Borrow the connection choice without changing the authored representation. pub fn target(&self) -> Result, ConfigError> { match self.service_ref.as_deref() { - Some(name) - if !name.is_empty() && self.endpoint.is_empty() && self.credential.is_none() => - { - Ok(InferenceTarget::Service { name }) + Some(name) if !name.is_empty() && self.endpoint.is_empty() => { + Ok(InferenceTarget::Service { + name, + credential: self.credential.as_ref(), + }) } None if !self.endpoint.is_empty() => Ok(InferenceTarget::External { endpoint: &self.endpoint, credential: self.credential.as_ref(), }), _ => Err(ConfigError::new( - "declare an external endpoint or serviceRef without endpoint or credential", + "declare an external endpoint or serviceRef without endpoint", )), } } diff --git a/crates/nemoclaw-sdk/src/config/schema/validation.rs b/crates/nemoclaw-sdk/src/config/schema/validation.rs index cf9c4d894db..03f1e1754af 100644 --- a/crates/nemoclaw-sdk/src/config/schema/validation.rs +++ b/crates/nemoclaw-sdk/src/config/schema/validation.rs @@ -383,7 +383,10 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { let provider = &mut defs["InferenceProvider"]; property(provider, "serviceRef", json!({"pattern": c::SLUG})); provider["if"] = json!({"required": ["serviceRef"]}); - provider["then"] = json!({"properties": {"provider":{"const":"openai"},"endpoint": {"const": ""}}, "allOf": [forbid(&["credential"])]}); + // A credential with serviceRef names the key of an authenticated cluster + // service; Rust checks that against the service it references. + provider["then"] = + json!({"properties": {"provider":{"const":"openai"},"endpoint": {"const": ""}}}); provider["else"] = json!({"required": ["endpoint"], "properties": {"endpoint": {"pattern": "^https?://"}}}); provider["allOf"] = json!([ @@ -423,15 +426,61 @@ pub(super) fn constrain(root: &mut Value, normalized: bool) { at("spec/gateway/management", json!({"const":"external"}), true), at("spec/gateway", json!({"required":["management","kubernetes"], "properties":{"management":{"const":"managed"}}}), true) ]}, - at("spec/services", json!({"maxProperties":0}), false) ], - "x-nemoclaw-error": "Kubernetes requires an external gateway or an explicit managed Kubernetes target, and external inference endpoints; managed services are not supported" + "x-nemoclaw-error": "Kubernetes requires an external gateway or an explicit managed Kubernetes target" + } + })); + // On a cluster, Kubernetes runs managed vLLM and Ollama from the service's + // kubernetes settings, beside a managed gateway only; elsewhere those + // settings have no meaning. + let cluster_service = json!({ + "required": ["kubernetes"], + "properties": {"kind": {"enum": ["vllm", "ollama"]}} + }); + root["allOf"].as_array_mut().unwrap().push(json!({ + "if": at("spec/gateway/runtime/provider", json!({"enum":["kubernetes", "openshift"]}), true), + "then": { + "allOf": [ + {"if": at("spec/gateway/management", json!({"const":"external"}), true), + "then": at("spec/services", json!({"maxProperties":0}), false)}, + at("spec/services", json!({"additionalProperties": cluster_service}), false) + ], + "x-nemoclaw-error": "Kubernetes and OpenShift services require a managed gateway, kind vllm or ollama, and kubernetes settings" + }, + "else": { + "allOf": [at("spec/services", json!({"additionalProperties": forbid(&["kubernetes"])}), false)], + "x-nemoclaw-error": "service kubernetes settings require a managed Kubernetes or OpenShift gateway and are not supported with Docker or Podman" + } + })); + // A credential with serviceRef is the key of an authenticated cluster + // service, so it needs a cluster gateway wherever a provider is declared. + let service_key = json!({"if": {"required": ["serviceRef"]}, "then": forbid(&["credential"])}); + let each = |path: &str| { + path.split('/') + .rev() + .fold(service_key.clone(), |child, segment| match segment { + "[]" => json!({"items": child}), + "*" => json!({"additionalProperties": child}), + _ => json!({"properties": {segment: child}}), + }) + }; + root["allOf"].as_array_mut().unwrap().push(json!({ + "if": {"not": at("spec/gateway/runtime/provider", json!({"enum":["kubernetes", "openshift"]}), true)}, + "then": { + "allOf": [ + each("spec/inferenceProviders/[]"), + each("spec/sandboxes/[]/inferenceProviders/[]"), + each("spec/inferences/*/routes/[]/provider"), + each("spec/sandboxes/[]/inferences/*/routes/[]/provider"), + each("spec/sandboxes/[]/agent/inference/routes/[]/provider") + ], + "x-nemoclaw-error": "credential with serviceRef is the key of an authenticated cluster vLLM service and requires a managed Kubernetes or OpenShift gateway" } })); root["x-nemoclaw-parser-checks"] = json!([ "Document::parse rejects YAML aliases, anchors, merge keys, all explicit tags (including core tags such as !!binary), duplicate keys, multiple documents, and input larger than 1 MiB. It applies the compiled input schema before defaulting; Document::validate applies the normalized schema and semantic checks, including for directly constructed Rust values.", "The parser checks the shape of every endpoint URL and the gateway endpoint's transport and address policy; OpenShell checks inference destinations when sandboxes connect. It also checks managed gateway port bounds, canonical private IPv4 /24 networks, local engine socket syntax, and publication address/port/network agreement.", - "Managed Kubernetes requires explicit kubeconfig environment, context, namespace, and authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. Local engine fields and managed inference services are excluded; gateway.runtime.provider is kubernetes or openshift. OpenShift uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations.", + "Managed Kubernetes requires explicit kubeconfig environment, context, namespace, and authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. Local engine fields are excluded; gateway.runtime.provider is kubernetes or openshift. Managed vLLM and Ollama services require kubernetes settings and explicit container limits, and exclude Docker placement, publication, and host IPC; Kubernetes runs them from the bundled Kubernetes provider's objects. OpenShift uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations.", "Explicit sandbox policies are also checked by the pinned OpenShell policy parser and validator, including protocol-specific rule semantics, process identities, filesystem paths, and destination address restrictions.", "Explicit filesystem grants must permit reads of the paths the selected image's runtime requires, such as Fabric's /opt/fabric; parent and read-write grants count. Planning checks them against the image's metadata; it does not resolve symlinks or establish runtime permissions.", "The schema requires an explicit default for multiple model choices. Rust checks unique route names, that the default names a route, and that native model and tool fields have valid structural shapes. Fabric validates adapter-specific combinations.", diff --git a/crates/nemoclaw-sdk/src/config/types.rs b/crates/nemoclaw-sdk/src/config/types.rs index 1d187d5cc64..2905cceeae9 100644 --- a/crates/nemoclaw-sdk/src/config/types.rs +++ b/crates/nemoclaw-sdk/src/config/types.rs @@ -176,7 +176,7 @@ pub struct ManagedGateway { pub network_cidr: String, #[serde(skip_serializing_if = "Option::is_none")] #[schemars(default, with = "super::ManagedKubernetes")] - /// Explicit Kubernetes provisioning target. Excludes local engine, imagePullPolicy, and networkCIDR settings and requires Kubernetes sandboxes without managed inference services. + /// Explicit Kubernetes provisioning target. Excludes local engine, imagePullPolicy, and networkCIDR settings and requires Kubernetes sandboxes. Managed vLLM and Ollama services run in this namespace. pub kubernetes: Option>, #[serde(rename = "config", skip_serializing_if = "Option::is_none")] #[schemars(default, extend("additionalProperties" = {"anyOf": [{"type": "object"}, {"type": "array", "items": {"type": "object"}}]}))] @@ -230,7 +230,7 @@ pub struct InferenceProvider { pub endpoint: String, #[serde(rename = "credential", skip_serializing_if = "Option::is_none")] #[schemars(default, with = "SecretRef")] - /// Optional API credential reference for an external HTTPS endpoint. Excluded by serviceRef. + /// Optional API credential reference for an external endpoint, or, with serviceRef, the key of an authenticated cluster vLLM service, the same key as its kubernetes.keySecret. pub credential: Option, #[serde( rename = "serviceRef", @@ -238,7 +238,7 @@ pub struct InferenceProvider { skip_serializing_if = "Option::is_none" )] #[schemars(default, with = "String")] - /// Name of a managed service in spec.services. Excludes endpoint and credential. + /// Name of a managed service in spec.services. Excludes endpoint, and credential except for an authenticated cluster vLLM service. pub service_ref: Option, } diff --git a/crates/nemoclaw-sdk/src/deployment/export.rs b/crates/nemoclaw-sdk/src/deployment/export.rs index a6bd2c0ddf3..1447a4c7c84 100644 --- a/crates/nemoclaw-sdk/src/deployment/export.rs +++ b/crates/nemoclaw-sdk/src/deployment/export.rs @@ -391,11 +391,18 @@ fn export_provider(document: &mut Document, expected: &Row, observed: &Row) -> R provider.target()?, crate::config::InferenceTarget::Service { .. } ); - if managed - && (observed["endpoint"] != document.provider_connection(provider)?.endpoint - || !observed["credential_env"].is_empty()) - { - return Err(Error::Conflict("managed inference registration drifted")); + if managed { + // Only an authenticated cluster service names a credential variable. + let connection = document.provider_connection(provider)?; + let credential_env = connection + .credential + .as_ref() + .map_or("", |credential| credential.env.as_str()); + if observed["endpoint"] != connection.endpoint + || observed["credential_env"] != credential_env + { + return Err(Error::Conflict("managed inference registration drifted")); + } } let provider = document.selected_provider_mut(&expected["name"])?; provider.credential = (!observed["credential_env"].is_empty()).then(|| SecretRef { diff --git a/crates/nemoclaw-sdk/src/deployment/mod.rs b/crates/nemoclaw-sdk/src/deployment/mod.rs index 22daf7fb79a..9dccb71204c 100644 --- a/crates/nemoclaw-sdk/src/deployment/mod.rs +++ b/crates/nemoclaw-sdk/src/deployment/mod.rs @@ -196,6 +196,32 @@ impl Deployment { if cancel.is_cancelled() { return Err(Error::Cancelled); } + for (name, service) in &document.spec.services { + let authentication_boundary = match service { + crate::services::ServiceDefinition::Ollama(service) + if service.kubernetes.is_some() => + { + Some("has no bearer authentication") + } + crate::services::ServiceDefinition::Vllm(service) + if service.kubernetes.is_some() => + { + Some(if service.authentication.is_some() { + "requires an image that restricts inference to authenticated /v1 routes" + } else { + "has no bearer authentication" + }) + } + _ => None, + }; + if let Some(authentication_boundary) = authentication_boundary { + (self.progress)(Progress::Warning { + message: format!( + "Cluster service {name} {authentication_boundary}. Network isolation depends on NetworkPolicy enforcement, which the Kubernetes API cannot verify. Verify that the network plugin enforces the supervisor-only policy." + ), + }); + } + } let (bundle, store) = self.open()?; let prior = store.load()?; let fresh = prior.is_none(); @@ -242,12 +268,24 @@ impl Deployment { self.initialize(&bundle, &store, &compiled.graph, cancel) .await?; let bindings = store.bindings(&bundle.tofu(), cancel).await?; + // A model volume kept by an earlier destroy is reused, not recreated. + let imports = crate::kubernetes::models::retained_claim_imports( + &document, + self.secrets.as_ref(), + &bindings.keys().cloned().collect(), + ) + .await?; + if !imports.is_empty() { + let mut graph = compiled.graph.clone(); + graph["import"] = json!(imports); + self.prepare(&bundle, &store, &graph)?; + } let expected = expected_bindings(&compiled, &bindings)?; (self.progress)(Progress::Planning); let plan = self .saved_plan(&bundle, &store, &document, "apply.plan", cancel) .await?; - runtime::preserve_docker_models(&document, &plan)?; + runtime::preserve_models(&document, &plan)?; let changes = check_plan( &plan, &with_observations(&expected, &compile::observations(&compiled.graph)), diff --git a/crates/nemoclaw-sdk/src/deployment/plan.rs b/crates/nemoclaw-sdk/src/deployment/plan.rs index fd5c7bd7209..a05497361f4 100644 --- a/crates/nemoclaw-sdk/src/deployment/plan.rs +++ b/crates/nemoclaw-sdk/src/deployment/plan.rs @@ -19,6 +19,8 @@ pub(super) struct ResourceChange { pub mode: Option, pub address: String, pub deposed: Option, + /// Why OpenTofu plans the action, such as `replace_because_tainted`. + pub action_reason: Option, pub change: PlannedChange, } #[derive(Deserialize)] @@ -28,6 +30,8 @@ struct PlannedResourceChange { address: String, #[serde(default)] deposed: Option, + #[serde(default)] + action_reason: Option, change: PlannedChange, } impl From for ResourceChange { @@ -45,6 +49,7 @@ impl From for ResourceChange { mode: planned.mode, address: planned.address, deposed: planned.deposed, + action_reason: planned.action_reason, change, } } @@ -82,6 +87,9 @@ pub(super) struct PlannedChange { pub before: Value, #[serde(default)] pub after: Value, + /// The parts of `after` known only after apply, marked `true`. + #[serde(default)] + pub after_unknown: Value, } /// Sandboxes to replace so each newly created agent gets a new sandbox. /// @@ -206,7 +214,7 @@ pub(super) fn check_plan( return Err(Error::Conflict("plan contains an undeclared resource")); } let resource = if let Some(key) = &change.deposed { - if change.address.starts_with("docker_volume.") + if crate::docker_compute::is_retained_storage(&change.address) || !cleanup_seen.insert((change.address.clone(), key.clone())) { return Err(Error::Conflict("plan contains invalid replacement cleanup")); @@ -371,7 +379,7 @@ pub(super) fn check_destroy_plan( ))?; if delegated(&change.address) { let resource = if let Some(key) = &change.deposed { - if change.address.starts_with("docker_volume.") + if crate::docker_compute::is_retained_storage(&change.address) || !cleanup_seen.insert((change.address.clone(), key.clone())) { return Err(Error::Conflict("plan contains invalid replacement cleanup")); diff --git a/crates/nemoclaw-sdk/src/deployment/runtime.rs b/crates/nemoclaw-sdk/src/deployment/runtime.rs index 15b6257fd9b..633028c6f13 100644 --- a/crates/nemoclaw-sdk/src/deployment/runtime.rs +++ b/crates/nemoclaw-sdk/src/deployment/runtime.rs @@ -77,7 +77,8 @@ pub(super) fn runtime_bindings( ) -> Result, Error> { let mut expected = allowed(targets); if bindings.keys().any(|key| { - !expected.contains_key(key) && (!plan::disposable(key) || key.starts_with("docker_volume.")) + !expected.contains_key(key) + && (!plan::disposable(key) || crate::docker_compute::is_retained_storage(key)) }) { return Err(Error::Conflict("apply cannot remove a managed runtime")); } @@ -132,7 +133,9 @@ pub(super) fn runtime_saved( .collect()) } -pub(super) fn preserve_docker_models(document: &Document, plan: &Plan) -> Result<(), Error> { +/// Refuse a plan that would disrupt a serving model under the default +/// `updatePolicy: Preserve`. +pub(super) fn preserve_models(document: &Document, plan: &Plan) -> Result<(), Error> { use crate::services::ServiceUpdatePolicy; for (name, service) in &document.spec.services { @@ -143,6 +146,10 @@ pub(super) fn preserve_docker_models(document: &Document, plan: &Plan) -> Result if policy == ServiceUpdatePolicy::Recreate { continue; } + if service.kubernetes().is_some() { + preserve_cluster_model(name, plan)?; + continue; + } let address = crate::docker_compute::address(&logical); if plan.resource_changes.iter().any(|change| { let (before, after) = (&change.change.before, &change.change.after); @@ -174,3 +181,41 @@ pub(super) fn preserve_docker_models(document: &Document, plan: &Plan) -> Result } Ok(()) } + +/// Kubernetes replaces the model Pod whenever its Deployment's Pod template +/// changes, and deleting the Deployment stops it. Replacing a tainted +/// Deployment, whose rollout never completed, has no serving Pod to keep. +fn preserve_cluster_model(name: &str, plan: &Plan) -> Result<(), Error> { + use crate::services::cluster::{DEPLOYMENT, address}; + let deployment = address(DEPLOYMENT, name); + let disrupts = plan.resource_changes.iter().any(|change| { + let detail = &change.change; + let template = |value: &Value| value["spec"][0]["template"].clone(); + // OpenTofu mirrors `after` with empty lists and objects, marking only + // the values known after apply `true`. + fn unknown(value: &Value) -> bool { + match value { + Value::Bool(known_after_apply) => *known_after_apply, + Value::Array(values) => values.iter().any(unknown), + Value::Object(values) => values.values().any(unknown), + _ => false, + } + } + change.address == deployment + && change.deposed.is_none() + && !detail.before.is_null() + && (if detail.actions.iter().any(|action| action == "delete") { + change.action_reason.as_deref() != Some("replace_because_tainted") + } else { + detail.actions == ["update"] + && (template(&detail.before) != template(&detail.after) + || unknown(&template(&detail.after_unknown))) + }) + }); + if disrupts { + return Err(Error::ClusterModelUpdateRefused { + service: name.into(), + }); + } + Ok(()) +} diff --git a/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs b/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs index 2987eb0b009..7abaa043f8a 100644 --- a/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs +++ b/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs @@ -20,10 +20,122 @@ fn runtime_observations( plan: &Plan, ) -> Result { let expected = runtime_bindings(targets, bindings)?; - preserve_docker_models(document, plan)?; + preserve_models(document, plan)?; Ok(Checked { expected }) } +#[test] +fn cluster_model_pod_changes_require_recreate_unless_its_rollout_never_completed() { + for source in [ + include_str!("../../../../../crates/test-support/cluster-models/vllm.yaml"), + include_str!("../../../../../crates/test-support/cluster-models/ollama.yaml"), + ] { + let preserved = Document::parse(source.as_bytes()).unwrap(); + let mut input = serde_json::to_value(&preserved).unwrap(); + input["spec"]["services"]["qwen"]["updatePolicy"] = json!("Recreate"); + let recreate = Document::parse(input.to_string().as_bytes()).unwrap(); + let deployment = |image: &str, label: &str| { + json!({ + "metadata": [{"labels": {"nemoclaw.nvidia.com/generation": label}}], + "spec": [{"template": [{"spec": [{"container": [{"image": image}]}]}]}] + }) + }; + let running = deployment("model@sha256:a", "one"); + let plan = |actions: Value, after: Value, unknown: Value, reason: Option<&str>| -> Plan { + serde_json::from_value(json!({"resource_changes": [{ + "address": "kubernetes_deployment_v1.qwen", + "action_reason": reason, + "change": {"actions": actions, "before": running, "after": after, "after_unknown": unknown} + }]})) + .unwrap() + }; + let refused = |plan: &Plan| { + matches!( + preserve_models(&preserved, plan), + Err(Error::ClusterModelUpdateRefused { service }) if service == "qwen" + ) + }; + for (change, disrupts) in [ + // A new image changes the Pod template, which replaces the Pod. + ( + plan( + json!(["update"]), + deployment("model@sha256:b", "one"), + Value::Null, + None, + ), + true, + ), + // So does any template value known only during apply. + ( + plan( + json!(["update"]), + running.clone(), + json!({"spec": [{"template": [{"spec": [{"container": [{"image": true}]}]}]}]}), + None, + ), + true, + ), + ( + plan( + json!(["delete", "create"]), + deployment("model@sha256:b", "one"), + Value::Null, + Some("replace_because_cannot_update"), + ), + true, + ), + ( + plan(json!(["delete"]), Value::Null, Value::Null, None), + true, + ), + // A label outside the template leaves the Pod running, even with + // OpenTofu's structure of known template values beside it. + ( + plan( + json!(["update"]), + deployment("model@sha256:a", "two"), + json!({"spec": [{"template": [{"spec": [{"container": [{"env": [{"value_from": []}]}]}]}]}]}), + None, + ), + false, + ), + ( + plan(json!(["no-op"]), running.clone(), Value::Null, None), + false, + ), + // A tainted Deployment never completed its rollout. + ( + plan( + json!(["delete", "create"]), + deployment("model@sha256:b", "one"), + Value::Null, + Some("replace_because_tainted"), + ), + false, + ), + ] { + assert_eq!( + refused(&change), + disrupts, + "{:?}", + change.resource_changes[0].change.actions + ); + preserve_models(&recreate, &change).unwrap(); + } + // The same service on Docker would be a container; a cluster service + // has none, so a Docker change at that address is not its update. + let docker: Plan = serde_json::from_value(json!({"resource_changes": [{ + "address": crate::docker_compute::address( + &preserved.spec.services["qwen"].model_address("qwen").unwrap() + ), + "change": {"actions": ["delete"], "before": {"id": "x", "must_run": true}} + }]})) + .unwrap(); + preserve_models(&preserved, &docker).unwrap(); + } +} + #[test] fn docker_model_updates_preserve_running_containers_unless_recreation_is_explicit() { for (source, name, kind) in [ @@ -366,6 +478,131 @@ fn kubernetes_bindings(targets: &[Target]) -> BTreeMap { .collect() } +#[tokio::test] +async fn plan_and_apply_warn_about_cluster_network_boundaries_even_with_bearer_authentication() { + for (source, remove_authentication, warning_detail) in [ + ( + include_bytes!("../../../../../crates/test-support/cluster-models/ollama.yaml") + .as_slice(), + false, + Some("no bearer authentication"), + ), + ( + include_bytes!("../../../../../crates/test-support/cluster-models/vllm.yaml") + .as_slice(), + false, + Some("requires an image that restricts inference to authenticated /v1 routes"), + ), + ( + include_bytes!("../../../../../crates/test-support/cluster-models/vllm.yaml") + .as_slice(), + true, + Some("no bearer authentication"), + ), + ( + include_bytes!("../../../../../examples/managed-ollama-gpu.yaml").as_slice(), + false, + None, + ), + ] { + let mut document = Document::parse(source).unwrap(); + if remove_authentication { + let crate::services::ServiceDefinition::Vllm(service) = + document.spec.services.get_mut("qwen").unwrap() + else { + unreachable!() + }; + // Without authentication there is no key Secret or provider key. + service.authentication = None; + service.kubernetes.as_mut().unwrap().key_secret = None; + document.spec.inference_providers[0].credential = None; + } + for apply in [false, true] { + let directory = tempfile::tempdir().unwrap(); + let events = Arc::new(std::sync::Mutex::new(Vec::new())); + let saved = events.clone(); + let deployment = Deployment::new( + &directory.path().join("state"), + &directory.path().join("missing-bundle"), + ) + .with_progress(Arc::new(move |event| saved.lock().unwrap().push(event))); + let result = if apply { + deployment.apply(&document, &CancellationToken::new()).await + } else { + deployment.plan(&document, &CancellationToken::new()).await + }; + assert!(result.is_err()); + let events = events.lock().unwrap(); + let warnings: Vec<_> = events + .iter() + .filter_map(|event| match event { + Progress::Warning { message } if message.contains("NetworkPolicy") => { + Some(message) + } + _ => None, + }) + .collect(); + assert_eq!(warnings.len(), usize::from(warning_detail.is_some())); + if let Some(detail) = warning_detail { + for required in [ + "qwen", + detail, + "NetworkPolicy enforcement", + "Kubernetes API cannot verify", + "supervisor-only policy", + ] { + assert!(warnings[0].contains(required), "{}", warnings[0]); + } + } + assert!(!events.contains(&Progress::MutationStarted)); + } + } +} + +#[test] +fn apply_keeps_a_bound_cluster_model_volume_but_may_drop_its_server() { + let document = Document::parse( + include_bytes!("../../../../../crates/test-support/cluster-models/vllm.yaml").as_slice(), + ) + .unwrap(); + let record = Record::new(document.clone()).unwrap(); + let targets = compile::runtime_targets(&document, &record.generations).unwrap(); + let bindings = kubernetes_bindings(&targets); + runtime_bindings(&targets, &bindings).unwrap(); + let without = |address: &str| -> Vec { + targets + .iter() + .filter(|target| target.address != address) + .cloned() + .collect() + }; + assert!(matches!( + runtime_bindings( + &without("kubernetes_persistent_volume_claim_v1.qwen"), + &bindings + ), + Err(Error::Conflict("apply cannot remove a managed runtime")) + )); + for disposable in [ + "kubernetes_deployment_v1.qwen", + "kubernetes_service_v1.qwen", + "kubernetes_network_policy_v1.qwen", + ] { + runtime_bindings(&without(disposable), &bindings).unwrap(); + } + // OpenTofu never cleans up an old model volume as a replacement. + let plan: Plan = serde_json::from_value(json!({"resource_changes": [{ + "address": "kubernetes_persistent_volume_claim_v1.qwen", "deposed": "old", + "change": {"actions": ["delete"], "before": {"id": "models/old"}} + }]})) + .unwrap(); + let expected = runtime_bindings(&targets, &bindings).unwrap(); + assert!(matches!( + check_runtime_plan(&plan, &expected, &bindings), + Err(Error::Conflict("plan contains invalid replacement cleanup")) + )); +} + #[test] fn kubernetes_helm_binding_requires_auth_and_the_same_release() { let (document, generations) = kubernetes_context(); diff --git a/crates/nemoclaw-sdk/src/docker_compute.rs b/crates/nemoclaw-sdk/src/docker_compute.rs index 8a3d8c0516e..474454b40b5 100644 --- a/crates/nemoclaw-sdk/src/docker_compute.rs +++ b/crates/nemoclaw-sdk/src/docker_compute.rs @@ -45,16 +45,28 @@ pub(crate) fn address(logical: &str) -> String { } logical.into() } +/// Objects whose identity OpenTofu and their platform own: Docker's, and the +/// Kubernetes objects of cluster model services. pub(crate) fn is_disposable(address: &str) -> bool { [ "docker_container.", "docker_image.", "docker_network.", "docker_volume.", + "kubernetes_persistent_volume_claim_v1.", + "kubernetes_deployment_v1.", + "kubernetes_service_v1.", + "kubernetes_network_policy_v1.", ] .iter() .any(|prefix| address.starts_with(prefix)) } +/// Model data that only teardown or the user removes: Docker volumes and +/// cluster model volumes. No plan may replace one or drop its declaration. +pub(crate) fn is_retained_storage(address: &str) -> bool { + address.starts_with("docker_volume.") + || address.starts_with("kubernetes_persistent_volume_claim_v1.") +} fn digest(engine: &str, name: &str) -> String { Sha256::digest(format!("{engine}\0{name}").as_bytes())[..16] .iter() diff --git a/crates/nemoclaw-sdk/src/kubernetes/cluster.rs b/crates/nemoclaw-sdk/src/kubernetes/cluster.rs index 6bab32bc48a..4831fcd33ee 100644 --- a/crates/nemoclaw-sdk/src/kubernetes/cluster.rs +++ b/crates/nemoclaw-sdk/src/kubernetes/cluster.rs @@ -65,7 +65,7 @@ fn resource(api_version: &str, kind: &str) -> ApiResource { ApiResource::from_gvk(&GroupVersionKind::gvk(group, version, kind)) } -fn failure(error: kube::Error) -> ObservationError { +pub(crate) fn failure(error: kube::Error) -> ObservationError { match error { kube::Error::Api(status) => match status.code { 401 => ObservationError::Authentication, diff --git a/crates/nemoclaw-sdk/src/kubernetes/mod.rs b/crates/nemoclaw-sdk/src/kubernetes/mod.rs index 860bc424151..58bba913efd 100644 --- a/crates/nemoclaw-sdk/src/kubernetes/mod.rs +++ b/crates/nemoclaw-sdk/src/kubernetes/mod.rs @@ -12,6 +12,7 @@ pub mod cluster; pub mod connection; pub mod gateway; pub mod issuer; +pub mod models; pub mod operations; pub mod receipt; pub mod storage; diff --git a/crates/nemoclaw-sdk/src/kubernetes/models.rs b/crates/nemoclaw-sdk/src/kubernetes/models.rs new file mode 100644 index 00000000000..a95e3e66a93 --- /dev/null +++ b/crates/nemoclaw-sdk/src/kubernetes/models.rs @@ -0,0 +1,390 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +//! Managed model services on a managed Kubernetes gateway's cluster. This +//! module builds configuration only: the bundled Kubernetes provider creates +//! the objects, and Kubernetes runs, restarts and schedules them. The runtime +//! data source supplies what any platform runs; this placement chooses only +//! the namespace, requests, limits, storage and scheduling. + +use super::gateway::{KUBECONFIG_VARIABLE, literal}; +use crate::artifact_pins as pins; +use crate::{ + Error, + compile::Generations, + config::Document, + services::{ + ServiceDefinition, + cluster::{CLAIM, DEPLOYMENT, NETWORK_POLICY, SERVICE, claim_name, name}, + installers::{ollama, vllm}, + }, +}; +use serde_json::{Value, json}; + +pub const PROVIDER_ADDRESS: &str = "registry.opentofu.org/hashicorp/kubernetes"; +pub use pins::KUBERNETES_PROVIDER_VERSION as PROVIDER_VERSION; +/// Labels a model Pod and its selector carry with the deployment's owner label. +pub const SERVICE_LABEL: &str = "nemoclaw.nvidia.com/service"; +/// Model downloads and preparation are part of a rollout, so a Deployment may +/// take as long as Docker readiness waits. +const ROLLOUT_SECONDS: u32 = 9 * 3600; + +/// A Kubernetes quantity in the canonical form the API server returns, so an +/// unchanged plan reads back unchanged. +fn gibibytes(value: u64) -> String { + format!("{value}Gi") +} +fn millicores(value: u32) -> String { + if value.is_multiple_of(1000) { + (value / 1000).to_string() + } else { + format!("{value}m") + } +} + +/// Declare the Kubernetes provider and every cluster model service's objects. +pub(crate) fn configure( + graph: &mut Value, + document: &Document, + generations: &Generations, +) -> Result<(), Error> { + let target = document.spec.gateway.as_kubernetes().ok_or(Error::State( + "managed Kubernetes gateway settings are missing", + ))?; + // Configured whenever the gateway is, so state that names these objects + // always refreshes against the authored cluster. + graph["terraform"]["required_providers"]["kubernetes"] = json!({ + "source": PROVIDER_ADDRESS, "version": format!("= {PROVIDER_VERSION}") + }); + graph["provider"]["kubernetes"] = json!({ + "config_path": format!("${{var.{KUBECONFIG_VARIABLE}}}"), + "config_context": literal(&target.context), + }); + for (service, definition) in &document.spec.services { + let Some(settings) = definition.kubernetes() else { + continue; + }; + let (source, generation_kind, runtime, image, pull_policy, container, architecture) = + match definition { + ServiceDefinition::Vllm(service) => ( + vllm::RUNTIME_DATA_SOURCE, + vllm::SERVICE_KIND, + crate::hcl_schema::to_hcl( + &vllm::runtime_fields().map_err(|_| { + Error::State("the vLLM runtime contract has no OpenTofu schema") + })?, + &serde_json::to_value(service.runtime_settings()) + .map_err(|_| Error::State("cannot encode runtime settings"))?, + ), + service.image.clone(), + service.image_pull_policy, + service.container.as_ref(), + service.architecture()?.to_owned(), + ), + ServiceDefinition::Ollama(service) => ( + ollama::RUNTIME_DATA_SOURCE, + ollama::SERVICE_KIND, + crate::hcl_schema::to_hcl( + &ollama::runtime_fields().map_err(|_| { + Error::State("the Ollama runtime contract has no OpenTofu schema") + })?, + &serde_json::to_value(service.runtime_settings()) + .map_err(|_| Error::State("cannot encode runtime settings"))?, + ), + service.image.clone(), + service.image_pull_policy, + service.container.as_ref(), + service.architecture()?.to_owned(), + ), + ServiceDefinition::OllamaProxy(_) | ServiceDefinition::Container(_) => { + return Err(Error::State("only vLLM and Ollama run on the cluster")); + } + }; + let mut runtime = runtime; + crate::services::literal(&mut runtime); + let source = crate::compile::data_source_type(source); + graph["data"][&source][service] = runtime; + let launch = |field: &str| format!("${{data.{source}.{service}.launch.{field}}}"); + let resources = vllm::ServiceContainer::resources(container); + let (cpu_limit, memory_limit) = container + .and_then(|container| Some((container.cpu_limit_millis?, container.memory_limit_gib?))) + .ok_or(Error::State( + "cluster model services require container limits", + ))?; + let object = name(document, service); + let namespace = literal(&target.namespace); + let owner = literal(&document.metadata.uid); + let generation = generations + .get(generation_kind) + .ok_or(Error::State("missing cluster service generation"))?; + let pod_labels = json!({ + super::cluster::OWNER_LABEL: owner, + SERVICE_LABEL: literal(&object), + }); + let metadata = |name: String| { + json!([{ + "name": literal(&name), + "namespace": namespace, + "labels": {super::cluster::OWNER_LABEL: owner}, + }]) + }; + let storage = "openshell_kubernetes_storage.runtime"; + + // The model volume outlives the server and the deployment. + let mut claim_spec = json!({ + "access_modes": ["ReadWriteOnce"], + "volume_mode": "Filesystem", + "resources": [{"requests": {"storage": gibibytes(settings.storage_gib)}}], + }); + if let Some(class) = &settings.storage_class { + claim_spec["storage_class_name"] = json!(literal(class)); + } + graph["resource"][CLAIM][service] = json!({ + "metadata": metadata(claim_name(document, service)), + "spec": [claim_spec], + // A WaitForFirstConsumer class binds only once the Pod uses it. + "wait_until_bound": false, + "lifecycle": {"prevent_destroy": true}, + "depends_on": [storage], + }); + + // Only supervisors, which carry sandbox traffic, reach the server. + graph["resource"][NETWORK_POLICY][service] = json!({ + "metadata": metadata(object.clone()), + "spec": [{ + "pod_selector": [{"match_labels": pod_labels}], + "policy_types": ["Ingress"], + "ingress": [{ + "from": [{"pod_selector": [{"match_labels": { + "openshell.ai/managed-by": "openshell", + "openshell.ai/boundary-role": "supervisor", + }}]}], + "ports": [{"port": launch("port"), "protocol": "TCP"}], + }], + }], + "depends_on": [storage], + }); + + graph["resource"][SERVICE][service] = json!({ + "metadata": metadata(object.clone()), + "spec": [{ + "type": "ClusterIP", + "selector": pod_labels, + "port": [{"name": "http", "port": launch("port"), "target_port": launch("port"), "protocol": "TCP"}], + }], + "wait_for_load_balancer": false, + "depends_on": [storage], + }); + + let mut environment = vec![ + json!({"name": "HOME", "value": "/data"}), + json!({"name": "XDG_CACHE_HOME", "value": "/data/.cache"}), + // Kubernetes restarts exited containers; memory protection must not + // start the model again under the same pressure. + json!({"name": nemoclaw_runtime::ON_STOP_ENV, "value": "hold"}), + ]; + if let Some(secret) = &settings.key_secret { + environment.push(json!({ + "name": launch("key_env"), + "value_from": [{"secret_key_ref": [{ + "name": literal(&secret.name), "key": literal(&secret.key), + }]}], + })); + } + let mut node_selector = serde_json::Map::new(); + for (key, value) in &settings.node_selector { + node_selector.insert(literal(key), json!(literal(value))); + } + node_selector.insert("kubernetes.io/os".into(), json!("linux")); + node_selector.insert("kubernetes.io/arch".into(), json!(literal(&architecture))); + let tolerations: Vec = settings + .tolerations + .iter() + .map(|toleration| { + let mut value = json!({ + "key": literal(&toleration.key), + "operator": format!("{:?}", toleration.operator), + "value": literal(&toleration.value), + }); + if let Some(effect) = toleration.effect { + value["effect"] = json!(format!("{effect:?}")); + } + if let Some(seconds) = toleration.toleration_seconds { + value["toleration_seconds"] = json!(seconds.to_string()); + } + value + }) + .collect(); + let mut pod = json!({ + "automount_service_account_token": false, + "enable_service_links": false, + "termination_grace_period_seconds": 60, + "node_selector": node_selector, + "toleration": tolerations, + "image_pull_secrets": target + .image_pull_secrets + .iter() + .map(|secret| json!({"name": literal(secret)})) + .collect::>(), + // The pod runs as the image's user with every capability dropped, + // as Docker placement does; OpenShift assigns its own user. + "security_context": [{"seccomp_profile": [{"type": "RuntimeDefault"}]}], + "container": [{ + "name": "runtime", + "image": literal(&image), + "image_pull_policy": pull_policy.map_or("IfNotPresent", |policy| policy.as_str()), + "command": launch("entrypoint"), + "args": launch("command"), + "env": environment, + "dynamic": {"env": { + "for_each": launch("environment"), + "content": {"name": "${env.key}", "value": "${env.value}"}, + }}, + "port": [{"name": "http", "container_port": launch("port"), "protocol": "TCP"}], + "resources": [{ + "requests": { + "cpu": millicores(settings.cpu_request_millis), + "memory": gibibytes(settings.memory_request_gib), + }, + "limits": { + "cpu": millicores(cpu_limit), + "memory": gibibytes(memory_limit), + // The runtime contract requires one visible GPU. + "nvidia.com/gpu": "1", + }, + }], + "volume_mount": [ + {"name": "data", "mount_path": launch("data_path")}, + {"name": "shm", "mount_path": "/dev/shm"}, + {"name": "tmp", "mount_path": "/tmp"}, + ], + "security_context": [{ + "allow_privilege_escalation": false, + "capabilities": [{"drop": ["ALL"]}], + }], + "termination_message_policy": "FallbackToLogsOnError", + // The runtime reports ready only once the model is served. + "readiness_probe": [{ + "exec": [{"command": launch("ready_command")}], + "period_seconds": 10, + "timeout_seconds": 5, + "failure_threshold": 3, + }], + }], + "volume": [ + {"name": "data", "persistent_volume_claim": [{"claim_name": literal(&claim_name(document, service))}]}, + {"name": "shm", "empty_dir": [{ + "medium": "Memory", + "size_limit": gibibytes(resources.shared_memory_bytes >> 30), + }]}, + {"name": "tmp", "empty_dir": [{}]}, + ], + }); + if let Some(class) = &settings.runtime_class_name { + pod["runtime_class_name"] = json!(literal(class)); + } + let mut deployment_metadata = metadata(object.clone()); + deployment_metadata[0]["labels"][super::cluster::GENERATION_LABEL] = + json!(literal(generation)); + graph["resource"][DEPLOYMENT][service] = json!({ + "metadata": deployment_metadata, + "spec": [{ + "replicas": "1", + // One GPU server per model volume: stop the old Pod first. + "strategy": [{"type": "Recreate"}], + "progress_deadline_seconds": ROLLOUT_SECONDS, + "selector": [{"match_labels": pod_labels}], + "template": [{ + "metadata": [{"labels": pod_labels}], + "spec": [pod], + }], + }], + "wait_for_rollout": true, + "timeouts": {"create": "9h", "update": "9h", "delete": "10m"}, + // The policy exists before the server can accept connections. + "depends_on": [ + storage, + format!("{CLAIM}.{service}"), + format!("{NETWORK_POLICY}.{service}"), + ], + }); + } + Ok(()) +} + +/// Flatten a Kubernetes object in OpenTofu state to the identity bindings +/// compare: its name, namespace and owner label. +pub(crate) fn flatten(kind: &str, values: &mut Value) { + if !crate::services::cluster::is_cluster_kind(kind) { + return; + } + let metadata = &values["metadata"][0]; + let flattened = json!({ + "id": values["id"], + "name": metadata["name"], + "namespace": metadata["namespace"], + "owner": metadata["labels"][super::cluster::OWNER_LABEL], + }); + *values = flattened; +} + +/// Import blocks for model volumes this deployment created and its state no +/// longer records, as after destroy, so a reapply reuses their data. Reads +/// only the volumes' metadata, and only for services without a bound volume. +/// A volume another deployment or anyone else owns is never adopted. +#[doc(hidden)] +pub async fn retained_claim_imports( + document: &Document, + secrets: &dyn nemoclaw_backend::Secrets, + bound: &std::collections::BTreeSet, +) -> Result, Error> { + use crate::services::cluster::address; + let Some(target) = document.spec.gateway.as_kubernetes() else { + return Ok(Vec::new()); + }; + let unbound: Vec<&String> = document + .spec + .services + .iter() + .filter(|(service, definition)| { + definition.kubernetes().is_some() && !bound.contains(&address(CLAIM, service)) + }) + .map(|(service, _)| service) + .collect(); + if unbound.is_empty() { + return Ok(Vec::new()); + } + let kubeconfig = super::kubeconfig_path(&secrets.resolve(&target.kubeconfig.env)?)?; + let client = super::connect(&super::ClusterTarget { + kubeconfig, + context: target.context.clone(), + }) + .await?; + let claims: kube::Api = + kube::Api::namespaced(client, &target.namespace); + let mut imports = Vec::new(); + for service in unbound { + let claim = claim_name(document, service); + let Some(existing) = claims + .get_opt(&claim) + .await + .map_err(super::cluster::failure)? + else { + continue; + }; + let owner = existing + .metadata + .labels + .as_ref() + .and_then(|labels| labels.get(super::cluster::OWNER_LABEL)); + if owner != Some(&document.metadata.uid) { + return Err(Error::Conflict( + "a model volume with a cluster service's name exists but belongs to another owner; NemoClaw never adopts it", + )); + } + imports.push(json!({ + "to": address(CLAIM, service), + "id": format!("{}/{claim}", target.namespace), + })); + } + Ok(imports) +} diff --git a/crates/nemoclaw-sdk/src/process.rs b/crates/nemoclaw-sdk/src/process.rs index de109f0eddb..b7d335f5575 100644 --- a/crates/nemoclaw-sdk/src/process.rs +++ b/crates/nemoclaw-sdk/src/process.rs @@ -436,6 +436,12 @@ fn kubernetes_connection_environment_requires_explicit_operation_overrides() { "HELM_REGISTRY_CONFIG", "KUBE_HOST", "KUBE_TOKEN", + // The Kubernetes provider's own settings. + "KUBE_CONFIG_PATH", + "KUBE_CONFIG_PATHS", + "KUBE_CTX", + "KUBE_CTX_CLUSTER", + "KUBE_INSECURE", "KUBECONFIG", ] { assert!(!inherited_variable(name)); diff --git a/crates/nemoclaw-sdk/src/services/cluster.rs b/crates/nemoclaw-sdk/src/services/cluster.rs new file mode 100644 index 00000000000..e3d2a35a989 --- /dev/null +++ b/crates/nemoclaw-sdk/src/services/cluster.rs @@ -0,0 +1,111 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +//! Managed vLLM and Ollama on a managed Kubernetes gateway's cluster: the +//! objects NemoClaw declares for each service and the endpoint sandboxes reach. +//! `kubernetes::models` writes their bodies; Kubernetes runs them. + +use super::contract::{InstallPlan, RemovePlan}; +use crate::{ + Error, + backend::Row, + compile::{Generations, Target}, + config::{ConfigError, Document}, +}; +use sha2::{Digest, Sha256}; + +/// The retained model volume. +pub const CLAIM: &str = "kubernetes_persistent_volume_claim_v1"; +/// The server Pod's controller. +pub const DEPLOYMENT: &str = "kubernetes_deployment_v1"; +/// The address sandboxes reach. +pub const SERVICE: &str = "kubernetes_service_v1"; +/// The supervisor-only ingress rule. +pub const NETWORK_POLICY: &str = "kubernetes_network_policy_v1"; + +/// The Kubernetes name of a service's objects, unique in the deployment's +/// namespace and valid as a Service name. +pub fn name(document: &Document, service: &str) -> String { + let digest = Sha256::digest(service.as_bytes()); + let suffix: String = digest[..8] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(); + format!("{}-model-{suffix}", document.workspace()) +} + +/// The name of a service's retained model volume. +pub fn claim_name(document: &Document, service: &str) -> String { + format!("{}-data", name(document, service)) +} + +/// The OpenTofu address of a service's object of `kind`. +pub fn address(kind: &str, service: &str) -> String { + format!("{kind}.{service}") +} + +pub(crate) fn namespace(document: &Document) -> Result<&str, ConfigError> { + document + .spec + .gateway + .as_kubernetes() + .map(|kubernetes| kubernetes.namespace.as_str()) + .ok_or(ConfigError::new( + "cluster model services require a managed Kubernetes gateway", + )) +} + +/// The in-cluster address of a service, resolved when sandboxes connect. +pub(super) fn endpoint( + document: &Document, + service: &str, + port: i64, +) -> Result { + Ok(format!( + "http://{}.{}.svc.cluster.local:{port}/v1", + name(document, service), + namespace(document)? + )) +} + +/// Identity rows for the objects of service `service`; the bodies come from +/// `kubernetes::models::configure`. +pub(super) fn install( + document: &Document, + service: &str, + _generations: &Generations, +) -> Result { + let namespace = namespace(document)?.to_owned(); + let object = name(document, service); + let target = |kind: &str, name: String| Target { + kind: kind.into(), + address: address(kind, service), + values: Row::from([ + ("name".into(), name), + ("namespace".into(), namespace.clone()), + ("owner".into(), document.metadata.uid.clone()), + ]), + }; + Ok(InstallPlan { + targets: vec![ + target(CLAIM, claim_name(document, service)), + target(DEPLOYMENT, object.clone()), + target(SERVICE, object.clone()), + target(NETWORK_POLICY, object), + ], + ..InstallPlan::default() + }) +} + +/// Teardown keeps the model volume, and destroying the server requires it. +pub(super) fn remove(service: &str) -> RemovePlan { + let claim = address(CLAIM, service); + RemovePlan { + retained: vec![claim.clone()], + required_storage: vec![(address(DEPLOYMENT, service), claim)], + } +} + +/// Whether `kind` is an object this module declares. +pub fn is_cluster_kind(kind: &str) -> bool { + matches!(kind, CLAIM | DEPLOYMENT | SERVICE | NETWORK_POLICY) +} diff --git a/crates/nemoclaw-sdk/src/services/cluster_config.rs b/crates/nemoclaw-sdk/src/services/cluster_config.rs new file mode 100644 index 00000000000..93852229e45 --- /dev/null +++ b/crates/nemoclaw-sdk/src/services/cluster_config.rs @@ -0,0 +1,247 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +//! Requests, scheduling and retained storage for a model service on the +//! managed gateway's cluster. Kubernetes schedules and runs the server; these +//! settings only describe the objects NemoClaw declares for it. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +use super::installers::vllm::ServiceContainer; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// One GPU model service in the managed gateway's namespace. Its model volume survives destroy. +pub struct KubernetesService { + /// Requested CPU capacity in millicores. Must not exceed container.cpuLimitMillis. + #[schemars(range(min = 1))] + pub cpu_request_millis: u32, + /// Requested container memory in GiB. Must not exceed container.memoryLimitGiB. + #[serde(rename = "memoryRequestGiB")] + #[schemars(range(min = 1))] + pub memory_request_gib: u64, + /// Retained model-volume capacity in GiB. Must cover prepared data plus a 16 GiB working reserve; allow additional space for model downloads and retained snapshots. + #[serde(rename = "storageGiB")] + #[schemars(range(min = 16))] + pub storage_gib: u64, + /// StorageClass for the retained model volume. Omission selects the cluster default. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub storage_class: Option, + /// Required node labels in addition to Linux and the model's declared CPU architecture. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub node_selector: BTreeMap, + /// Node taints the model Pod may tolerate. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tolerations: Vec, + /// Existing RuntimeClass to use for the model Pod. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub runtime_class_name: Option, + /// The Secret in the gateway namespace whose key holds the API key of an authenticated vLLM service. The platform owns the Secret; NemoClaw never reads or writes it. Required with authentication and rejected without. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(with = "KeySecret")] + pub key_secret: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +/// A key of an existing Secret in the gateway namespace. +pub struct KeySecret { + /// Secret name. + pub name: String, + /// Key within the Secret's data. + pub key: String, +} + +impl KubernetesService { + pub fn validate(&self) -> Result<(), crate::config::ConfigError> { + crate::config::schema::validate_definition("KubernetesService", self) + } + + /// Check requests, limits, shared memory and storage against the runtime's + /// budgets without contacting the cluster. + pub(crate) fn validate_runtime( + &self, + container: Option<&ServiceContainer>, + runtime: &nemoclaw_runtime::RuntimeSpec, + ) -> Result<(), crate::config::ConfigError> { + use crate::config::validation::require; + self.validate()?; + let (cpu_limit, memory_limit) = container + .and_then(|container| Some((container.cpu_limit_millis?, container.memory_limit_gib?))) + .ok_or_else(|| { + crate::config::ConfigError::new( + "cluster model services require container.cpuLimitMillis and container.memoryLimitGiB", + ) + })?; + require( + memory_limit <= (i64::MAX as u64) >> 30, + "container.memoryLimitGiB must fit signed 64-bit bytes", + )?; + require( + self.cpu_request_millis <= cpu_limit && self.memory_request_gib <= memory_limit, + "cluster service CPU and memory requests must not exceed their limits", + )?; + let (prepared, preparation_memory, authenticated) = match runtime { + nemoclaw_runtime::RuntimeSpec::Vllm(service) => { + let (prepared, preparation) = service.recipe.as_ref().map_or((0, 0), |recipe| { + ( + recipe.resources.prepared_bytes, + recipe.resources.preparation_memory_gi_b, + ) + }); + (prepared, preparation, service.authentication.is_some()) + } + nemoclaw_runtime::RuntimeSpec::Ollama(_) => (0, 0, false), + }; + require( + container.map_or(8, |container| container.shared_memory_gi_b) <= memory_limit, + "container.memoryLimitGiB must cover container.sharedMemoryGiB", + )?; + require( + preparation_memory <= memory_limit, + "container.memoryLimitGiB must cover recipe preparationMemoryGiB", + )?; + let invalid = + || crate::config::ConfigError::new("cluster storage capacity exceeds supported bounds"); + let required = prepared + .checked_add(16 * nemoclaw_runtime::hardware::GIB) + .ok_or_else(invalid)?; + let capacity = self + .storage_gib + .checked_mul(nemoclaw_runtime::hardware::GIB) + .ok_or_else(invalid)?; + require( + capacity >= required, + "cluster storageGiB must cover recipe preparedBytes plus a 16 GiB working reserve; allow additional space for model downloads and retained snapshots", + )?; + require( + authenticated == self.key_secret.is_some(), + if authenticated { + "an authenticated cluster vLLM service requires kubernetes.keySecret, the platform Secret holding its key" + } else { + "kubernetes.keySecret applies only to an authenticated vLLM service" + }, + ) + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// One explicit Kubernetes node-taint toleration. +pub struct ServiceToleration { + /// Taint key. An empty key requires Exists and matches every key. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub key: String, + /// Match the taint's value with Equal, or its presence with Exists. + pub operator: TolerationOperator, + /// Value matched by Equal; Exists requires an empty value. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub value: String, + /// Omission matches all taint effects. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(with = "TolerationEffect")] + pub effect: Option, + /// Optional eviction delay, valid only for NoExecute tolerations. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(with = "u64")] + pub toleration_seconds: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +/// How a toleration matches a node taint. +pub enum TolerationOperator { + Equal, + Exists, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +/// Node-taint effect matched by a toleration. +pub enum TolerationEffect { + NoSchedule, + PreferNoSchedule, + NoExecute, +} + +pub(crate) fn constrain(defs: &mut serde_json::Map) { + use crate::config::schema::validation::{at, property}; + const DNS_SUBDOMAIN: &str = + r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*"; + const LABEL_NAME: &str = r"[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?"; + let key = json!({ + "pattern": format!(r"^(?:(?=[^/]{{1,253}}/){DNS_SUBDOMAIN}/)?{LABEL_NAME}$(?![\s\S])") + }); + let value = json!({"type":"string", "pattern": format!(r"^(?:{LABEL_NAME})?$(?![\s\S])")}); + let dns_subdomain = json!({"type":"string", "maxLength":253, "pattern":format!(r"^{DNS_SUBDOMAIN}$(?![\s\S])")}); + let settings = &mut defs["KubernetesService"]; + // Kubernetes quantities must fit signed 64-bit bytes after conversion from GiB. + for field in ["memoryRequestGiB", "storageGiB"] { + property(settings, field, json!({"maximum": (i64::MAX as u64) >> 30})); + } + for field in ["storageClass", "runtimeClassName"] { + property(settings, field, dns_subdomain.clone()); + } + property( + settings, + "nodeSelector", + json!({"propertyNames":key.clone(), "additionalProperties":value.clone()}), + ); + let secret = &mut defs["KeySecret"]; + property(secret, "name", dns_subdomain); + property( + secret, + "key", + json!({"type":"string", "maxLength":253, "pattern":r"^[-._a-zA-Z0-9]+$(?![\s\S])"}), + ); + let toleration = &mut defs["ServiceToleration"]; + property(toleration, "key", json!({"anyOf":[{"const":""},key]})); + property(toleration, "value", value); + property( + toleration, + "tolerationSeconds", + json!({"type":"integer", "minimum":0, "maximum":i64::MAX}), + ); + toleration["allOf"] = json!([ + {"if":at("operator",json!({"const":"Exists"}),true), + "then":at("value",json!({"const":""}),false), + "else":at("key",json!({"minLength":1}),true)}, + {"if":{"required":["tolerationSeconds"]}, + "then":at("effect",json!({"const":"NoExecute"}),true)} + ]); + + for service in defs["ServiceDefinition"]["oneOf"].as_array_mut().unwrap() { + if !matches!( + service["properties"]["kind"]["const"].as_str(), + Some("vllm" | "ollama") + ) { + continue; + } + // Docker defaults omitted limits, but a cluster Pod needs both. Name the + // missing field instead of reporting only the failed keyword. + let mut rules: Vec = ["cpuLimitMillis", "memoryLimitGiB"] + .into_iter() + .map(|field| { + let mut rule = at(&format!("container/{field}"), json!({}), true); + rule["x-nemoclaw-error"] = + json!(format!("cluster model services require container.{field}")); + rule + }) + .collect(); + // OpenShell refuses these destinations, so sandboxes could never reach them. + let mut port = at( + "serving/port", + json!({"not":{"enum":[2379, 2380, 6443, 10250, 10255]}}), + false, + ); + port["x-nemoclaw-error"] = json!( + "a cluster model service's serving.port must not be 2379, 2380, 6443, 10250, or 10255, which OpenShell refuses as destinations" + ); + rules.push(port); + let rule = json!({"if":{"required":["kubernetes"]}, "then":{"allOf":rules}}); + if let Some(existing) = service["allOf"].as_array_mut() { + existing.push(rule); + } else { + service["allOf"] = json!([rule]); + } + } +} diff --git a/crates/nemoclaw-sdk/src/services/installers/ollama/config.rs b/crates/nemoclaw-sdk/src/services/installers/ollama/config.rs index ebd807eb67f..09d58fe4e85 100644 --- a/crates/nemoclaw-sdk/src/services/installers/ollama/config.rs +++ b/crates/nemoclaw-sdk/src/services/installers/ollama/config.rs @@ -11,14 +11,19 @@ use serde::{Deserialize, Serialize}; #[serde(default, deny_unknown_fields)] /// Managed GPU Ollama service with an immutable runtime and model snapshot. pub struct ManagedOllama { - /// Preserve refuses replacement of a running Docker model container. Recreate permits sequential replacement and possible downtime until removed or changed. + /// Preserve refuses replacement of a running Docker model container or a cluster model Pod. Recreate permits sequential replacement and possible downtime until removed or changed. #[serde( rename = "updatePolicy", default, skip_serializing_if = "crate::services::ServiceUpdatePolicy::is_preserve" )] pub update_policy: crate::services::ServiceUpdatePolicy, - /// Container CPU and memory limits, IPC, and shared memory for Docker. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory. + /// Scheduling requests, retained-volume settings and the key Secret for a managed Kubernetes or OpenShift gateway only. Rejected for Docker and Podman. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(with = "crate::services::KubernetesService")] + #[schemars(extend("x-nemoclaw-required" = "With a managed Kubernetes or OpenShift gateway"))] + pub kubernetes: Option, + /// Container CPU and memory limits, IPC, and shared memory for Docker, Kubernetes, and OpenShift. Kubernetes and OpenShift require both limits. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory. #[serde(default, skip_serializing_if = "Option::is_none")] #[schemars(with = "ServiceContainer")] pub container: Option, diff --git a/crates/nemoclaw-sdk/src/services/installers/vllm/config.rs b/crates/nemoclaw-sdk/src/services/installers/vllm/config.rs index c2a3355e4a2..05e6ef4b48d 100644 --- a/crates/nemoclaw-sdk/src/services/installers/vllm/config.rs +++ b/crates/nemoclaw-sdk/src/services/installers/vllm/config.rs @@ -10,14 +10,19 @@ use serde::{Deserialize, Serialize}; #[serde(default, deny_unknown_fields)] /// Managed vLLM service. Explicit placement and publication must appear together. pub struct Service { - /// Preserve refuses replacement of a running Docker model container. Recreate permits sequential replacement and possible downtime until removed or changed. + /// Preserve refuses replacement of a running Docker model container or a cluster model Pod. Recreate permits sequential replacement and possible downtime until removed or changed. #[serde( rename = "updatePolicy", default, skip_serializing_if = "crate::services::ServiceUpdatePolicy::is_preserve" )] pub update_policy: crate::services::ServiceUpdatePolicy, - /// Container CPU and memory limits, IPC, and shared memory for Docker. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory. + /// Scheduling requests, retained-volume settings and the key Secret for a managed Kubernetes or OpenShift gateway only. Rejected for Docker and Podman. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(with = "crate::services::KubernetesService")] + #[schemars(extend("x-nemoclaw-required" = "With a managed Kubernetes or OpenShift gateway"))] + pub kubernetes: Option, + /// Container CPU and memory limits, IPC, and shared memory for Docker, Kubernetes, and OpenShift. Kubernetes and OpenShift require both limits. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory. #[serde(default, skip_serializing_if = "Option::is_none")] #[schemars(with = "ServiceContainer")] pub container: Option, diff --git a/crates/nemoclaw-sdk/src/services/mod.rs b/crates/nemoclaw-sdk/src/services/mod.rs index db5b6563b67..cc509620780 100644 --- a/crates/nemoclaw-sdk/src/services/mod.rs +++ b/crates/nemoclaw-sdk/src/services/mod.rs @@ -8,6 +8,11 @@ #[doc(hidden)] pub mod authentication; +pub mod cluster; +pub(crate) mod cluster_config; +pub use cluster_config::{ + KeySecret, KubernetesService, ServiceToleration, TolerationEffect, TolerationOperator, +}; mod contract; pub mod installers; pub mod placement; diff --git a/crates/nemoclaw-sdk/src/services/registry.rs b/crates/nemoclaw-sdk/src/services/registry.rs index 4f1a19b2dc6..489466966c6 100644 --- a/crates/nemoclaw-sdk/src/services/registry.rs +++ b/crates/nemoclaw-sdk/src/services/registry.rs @@ -153,6 +153,7 @@ pub(crate) fn constrain_schema( installers::ollama::constrain_schema(defs, normalized); installers::vllm::schema::constrain(defs, normalized); installers::container::constrain_schema(defs); + super::cluster_config::constrain(defs); for service in defs["ServiceDefinition"]["oneOf"].as_array_mut().unwrap() { crate::config::schema::validation::property( service, @@ -201,6 +202,15 @@ impl ServiceDefinition { } } + /// Settings of a managed model that runs on the gateway's cluster. + pub(crate) fn kubernetes(&self) -> Option<&super::KubernetesService> { + match self { + Self::Vllm(service) => service.kubernetes.as_ref(), + Self::Ollama(service) => service.kubernetes.as_ref(), + Self::OllamaProxy(_) | Self::Container(_) => None, + } + } + fn stage(&self) -> InstallStage { match self { Self::Ollama(_) | Self::Vllm(_) => InstallStage::Runtime, @@ -237,6 +247,37 @@ impl ServiceDefinition { container.validate_memory(preparation_memory)?; } let gateway = &document.spec.gateway; + if let Some(settings) = self.kubernetes() { + crate::config::validation::require( + gateway.as_kubernetes().is_some(), + "service kubernetes settings require a managed Kubernetes or OpenShift gateway and are not supported with Docker or Podman", + )?; + let (placement, container, runtime) = match self { + Self::Vllm(service) => ( + service.published_placement()?, + service.container.as_ref(), + nemoclaw_runtime::RuntimeSpec::Vllm(Box::new(service.runtime_settings())), + ), + Self::Ollama(service) => ( + service.published_placement()?, + service.container.as_ref(), + nemoclaw_runtime::RuntimeSpec::Ollama(Box::new(service.runtime_settings())), + ), + Self::OllamaProxy(_) | Self::Container(_) => unreachable!(), + }; + settings.validate_runtime(container, &runtime)?; + return crate::config::validation::require( + placement.is_none() + && container.is_none_or(|container| { + container.ipc != installers::vllm::ServiceIpc::Host + }), + "cluster model services exclude Docker placement, publication, and host IPC", + ); + } + crate::config::validation::require( + !gateway.runtime().provider.is_kubernetes(), + "managed vLLM and Ollama services on Kubernetes or OpenShift require kubernetes settings", + )?; let local_docker = gateway.as_managed().is_some_and(|gateway| { gateway.engine.starts_with("unix:///") && crate::config::validate_engine_endpoint(&gateway.engine).is_ok() @@ -264,6 +305,10 @@ impl ServiceDefinition { } fn allocation(&self, gateway: &Gateway) -> Result, ConfigError> { + // Kubernetes chooses where a cluster service runs and its address. + if self.kubernetes().is_some() { + return Ok(None); + } if let Self::Container(service) = self { let gateway = gateway.managed()?; return Ok(Some(NetworkAllocation { @@ -302,6 +347,9 @@ impl Installer for ServiceDefinition { name: &str, generations: &Generations, ) -> Result { + if self.kubernetes().is_some() { + return super::cluster::install(document, name, generations); + } match self { Self::Ollama(service) => service.install(document, name, generations), Self::OllamaProxy(service) => service.install(document, name, generations), @@ -316,6 +364,9 @@ impl Installer for ServiceDefinition { name: &str, generations: &Generations, ) -> Result { + if self.kubernetes().is_some() { + return Ok(super::cluster::remove(name)); + } match self { Self::Ollama(service) => service.remove(document, name, generations), Self::OllamaProxy(service) => service.remove(document, name, generations), @@ -328,6 +379,20 @@ impl Installer for ServiceDefinition { impl ServiceDefinition { fn resolve(&self, document: &Document, name: &str) -> Result { Ok(match self { + ServiceDefinition::Ollama(service) if service.kubernetes.is_some() => { + ResolvedInference { + endpoint: super::cluster::endpoint(document, name, service.serving.port)?, + served_model: service.model.name.clone(), + requires_authentication: false, + resource_dependencies: Vec::new(), + } + } + ServiceDefinition::Vllm(service) if service.kubernetes.is_some() => ResolvedInference { + endpoint: super::cluster::endpoint(document, name, service.serving.port)?, + served_model: service.served_model().into(), + requires_authentication: service.authentication.is_some(), + resource_dependencies: Vec::new(), + }, ServiceDefinition::Container(service) => { let publication = service.publication.as_ref().ok_or_else(|| { ConfigError::new("a container inference service requires a private publication") @@ -398,7 +463,11 @@ impl ServiceDefinition { ), ServiceDefinition::OllamaProxy(service) => service.validate(provider, model), ServiceDefinition::Vllm(service) => crate::config::validation::require( - sandbox_runtime == ComputeDriver::Docker || service.placement.is_some(), + if service.kubernetes.is_some() { + sandbox_runtime.is_kubernetes() + } else { + sandbox_runtime == ComputeDriver::Docker || service.placement.is_some() + }, "vLLM service requires compatible sandbox placement", ), } @@ -416,6 +485,8 @@ impl ServiceDefinition { ServiceDefinition::OllamaProxy(service) => service .credential_source(document, name, generations) .map(Some), + // A cluster service's key comes from the provider's credential. + ServiceDefinition::Vllm(service) if service.kubernetes.is_some() => Ok(None), ServiceDefinition::Vllm(service) => { service.credential_source(document, name, generations) } @@ -436,6 +507,8 @@ pub(crate) fn discovery_engines(document: &Document) -> Result, .spec .services .values() + // Kubernetes, not a container engine, runs cluster services. + .filter(|service| service.kubernetes().is_none()) .map(|service| { if let Some(allocation) = service.allocation(&document.spec.gateway)? { return Ok(allocation.engine); @@ -475,7 +548,7 @@ fn definition<'a>( document: &'a Document, provider: &InferenceProvider, ) -> Result, ConfigError> { - let crate::config::InferenceTarget::Service { name } = provider.target()? else { + let crate::config::InferenceTarget::Service { name, .. } = provider.target()? else { return Ok(None); }; document @@ -598,6 +671,20 @@ pub(crate) fn validate_provider( if let Some((name, definition @ ServiceDefinition::Container(_))) = referenced { definition.resolve(document, name)?; } + if let Some((name, definition)) = referenced { + // OpenShell registers an authenticated cluster service with the key + // the provider names; every other service supplies its own or none. + let authenticated_cluster = definition.kubernetes().is_some() + && definition.resolve(document, name)?.requires_authentication; + crate::config::validation::require( + authenticated_cluster == provider.credential.is_some(), + if authenticated_cluster { + "an inference provider for an authenticated cluster vLLM service requires credential, the same key as the service's kubernetes.keySecret" + } else { + "credential with serviceRef applies only to an authenticated cluster vLLM service" + }, + )?; + } Ok(referenced.is_some()) } diff --git a/crates/nemoclaw-sdk/src/state/mod.rs b/crates/nemoclaw-sdk/src/state/mod.rs index 73340d3a95e..0906bd3627d 100644 --- a/crates/nemoclaw-sdk/src/state/mod.rs +++ b/crates/nemoclaw-sdk/src/state/mod.rs @@ -542,6 +542,7 @@ fn parse_bindings(bytes: &[u8]) -> Result, Error> if let Some((kind, _)) = resource.address.split_once('.') { nemoclaw_openshell::flatten(kind, &mut values); nemoclaw_fabric::agent::flatten(kind, &mut values); + crate::kubernetes::models::flatten(kind, &mut values); } let attributes: StateBinding = serde_json::from_value(values).map_err(|_| { Error::State("OpenTofu binding is unreadable; retain state for recovery") diff --git a/crates/nemoclaw-sdk/src/state/tests.rs b/crates/nemoclaw-sdk/src/state/tests.rs index e3bf5b1c2db..55a7c3ee1e9 100644 --- a/crates/nemoclaw-sdk/src/state/tests.rs +++ b/crates/nemoclaw-sdk/src/state/tests.rs @@ -196,6 +196,36 @@ fn native_helm_state_preserves_its_namespace_and_immutable_chart_binding() { assert!(other["docker_container.runtime"].namespace.is_empty()); assert!(other["docker_container.runtime"].chart.is_empty()); } +#[test] +fn kubernetes_objects_bind_by_their_name_namespace_and_owner_label() { + // Their spec and metadata are nested lists, unlike NemoClaw's own rows. + for kind in [ + "kubernetes_persistent_volume_claim_v1", + "kubernetes_deployment_v1", + "kubernetes_service_v1", + "kubernetes_network_policy_v1", + ] { + let address = format!("{kind}.qwen"); + let resource = serde_json::json!({ + "address": address, "mode": "managed", + "values": { + "id": "models/nc-model", + "metadata": [{"name": "nc-model", "namespace": "models", + "labels": {crate::kubernetes::cluster::OWNER_LABEL: "uid-1"}}], + "spec": [{"replicas": "1"}], + "wait_for_rollout": true + } + }); + let observed = read(&state(serde_json::json!([resource]))).unwrap(); + let binding = &observed[&address]; + assert_eq!(binding.id, "models/nc-model", "{kind}"); + assert_eq!(binding.name, "nc-model", "{kind}"); + assert_eq!(binding.namespace, "models", "{kind}"); + assert_eq!(binding.owner, "uid-1", "{kind}"); + assert!(binding.spec.is_empty(), "{kind}"); + } +} + #[test] fn data_observations_do_not_become_managed_bindings() { let data = serde_json::json!({"address":"data.example.observed", "mode":"data", "values":{"id":"observation"}}); diff --git a/crates/nemoclaw-sdk/tests/cluster_service_config.rs b/crates/nemoclaw-sdk/tests/cluster_service_config.rs new file mode 100644 index 00000000000..4c10fdcd74a --- /dev/null +++ b/crates/nemoclaw-sdk/tests/cluster_service_config.rs @@ -0,0 +1,342 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +use nemoclaw_sdk::config::{Document, schema}; +use nemoclaw_sdk::services::KubernetesService; +use serde_json::{Value, json}; + +/// A managed cluster service beside a managed Kubernetes gateway, whose +/// sandbox still uses the hosted provider. +fn cluster_document(kind: &str) -> Value { + let mut document: Value = serde_saphyr::from_str(include_str!( + "../../../examples/kubernetes/managed-development.yaml" + )) + .unwrap(); + let source = match kind { + "vllm" => include_str!("../../../examples/spark/vllm.yaml"), + "ollama" => include_str!("../../../examples/managed-ollama-gpu.yaml"), + _ => unreachable!(), + }; + let source: Value = serde_saphyr::from_str(source).unwrap(); + document["spec"]["services"] = source["spec"]["services"].clone(); + document["spec"]["services"]["qwen"]["container"] = + json!({"cpuLimitMillis": 4000, "memoryLimitGiB": 64}); + document["spec"]["services"]["qwen"]["kubernetes"] = json!({ + "cpuRequestMillis": 1000, + "memoryRequestGiB": 32, + "storageGiB": 100, + "storageClass": "model-cache", + "runtimeClassName": "nvidia", + "nodeSelector": {"accelerator.example.com/pool": "inference"}, + "tolerations": [{"key": "nvidia.com/gpu", "operator": "Exists", "effect": "NoSchedule"}] + }); + document +} + +fn fixture(kind: &str) -> Value { + serde_saphyr::from_str(match kind { + "vllm" => include_str!("../../test-support/cluster-models/vllm.yaml"), + "ollama" => include_str!("../../test-support/cluster-models/ollama.yaml"), + _ => unreachable!(), + }) + .unwrap() +} + +fn parse_error(input: &Value) -> String { + Document::parse(input.to_string().as_bytes()) + .unwrap_err() + .to_string() +} + +#[test] +fn cluster_model_services_accept_explicit_capacity_storage_and_scheduling() { + let validator = jsonschema::validator_for(&schema::input_schema()).unwrap(); + for kind in ["vllm", "ollama"] { + for driver in ["kubernetes", "openshift"] { + let mut input = cluster_document(kind); + input["spec"]["gateway"]["runtime"]["provider"] = json!(driver); + assert!(validator.is_valid(&input), "{kind} on {driver}"); + let document = Document::parse(input.to_string().as_bytes()).unwrap(); + let exported = serde_json::to_value(&document).unwrap(); + let (authored, exported) = ( + &input["spec"]["services"]["qwen"], + &exported["spec"]["services"]["qwen"], + ); + for field in ["cpuLimitMillis", "memoryLimitGiB"] { + assert_eq!(exported["container"][field], authored["container"][field]); + } + assert_eq!(exported["kubernetes"], authored["kubernetes"]); + assert_eq!( + Document::parse(document.yaml().unwrap().as_bytes()).unwrap(), + document + ); + } + } +} + +#[test] +fn cluster_services_require_limits_capacity_and_compatible_execution_settings() { + let validator = jsonschema::validator_for(&schema::input_schema()).unwrap(); + for kind in ["vllm", "ollama"] { + for (mapping, field) in [ + ("kubernetes", "cpuRequestMillis"), + ("container", "cpuLimitMillis"), + ("kubernetes", "memoryRequestGiB"), + ("container", "memoryLimitGiB"), + ("kubernetes", "storageGiB"), + ] { + let mut input = cluster_document(kind); + input["spec"]["services"]["qwen"][mapping] + .as_object_mut() + .unwrap() + .remove(field); + assert!(!validator.is_valid(&input), "missing {mapping}.{field}"); + assert!(Document::parse(input.to_string().as_bytes()).is_err()); + } + // Docker defaults omitted limits; a cluster service must declare both. + let mut input = cluster_document(kind); + input["spec"]["services"]["qwen"] + .as_object_mut() + .unwrap() + .remove("container"); + let error = parse_error(&input); + assert!( + error.starts_with("configuration violates schema at spec.services.qwen (") + && error.ends_with("cluster model services require container.cpuLimitMillis"), + "{error}" + ); + // The old cluster layout held limits and policy in kubernetes. + for field in [ + "cpuLimitMillis", + "memoryLimitGiB", + "updatePolicy", + "imageMetadata", + ] { + let mut input = cluster_document(kind); + input["spec"]["services"]["qwen"]["kubernetes"][field] = json!("unknown"); + assert!(!validator.is_valid(&input), "kubernetes.{field}"); + assert!(parse_error(&input).ends_with("unknown fields are not allowed")); + } + for variation in [ + "implicit", "docker", "podman", "external", "host-ipc", "ssh", + ] { + let mut input = cluster_document(kind); + match variation { + "implicit" => { + input["spec"]["services"]["qwen"] + .as_object_mut() + .unwrap() + .remove("kubernetes"); + } + "docker" | "podman" => { + input["spec"]["gateway"] = + json!({"management":"managed", "runtime":{"provider":variation}}); + if variation == "podman" { + input["spec"]["gateway"]["engine"] = + json!("unix:///run/user/1000/podman/podman.sock"); + } + for sandbox in input["spec"]["sandboxes"].as_array_mut().unwrap() { + sandbox["image"].as_object_mut().unwrap().remove("metadata"); + } + } + "external" => { + input["spec"]["gateway"] = json!({"management":"external", "runtime":{"provider":"kubernetes"}, "endpoint":"https://gateway.example"}); + } + "host-ipc" => { + input["spec"]["services"]["qwen"]["container"]["ipc"] = json!("host"); + } + "ssh" => { + input["spec"]["services"]["qwen"]["placement"] = + json!({"engine":"ssh://gpu@10.0.0.5", "networkCidr":"10.30.0.0/24"}); + input["spec"]["services"]["qwen"]["publication"] = + json!({"endpoint":"http://10.0.0.5:8000/v1", "bindAddress":"10.0.0.5"}); + } + _ => unreachable!(), + } + assert!( + Document::parse(input.to_string().as_bytes()).is_err(), + "{kind}: {variation}" + ); + if variation != "host-ipc" && variation != "ssh" { + assert!(!validator.is_valid(&input), "{kind}: {variation}"); + } + } + } +} + +#[test] +fn cluster_requests_and_volumes_must_fit_limits_and_runtime_budgets() { + for kind in ["vllm", "ollama"] { + for (request, limit) in [ + ("cpuRequestMillis", "cpuLimitMillis"), + ("memoryRequestGiB", "memoryLimitGiB"), + ] { + let mut input = cluster_document(kind); + input["spec"]["services"]["qwen"]["kubernetes"][request] = json!(65); + input["spec"]["services"]["qwen"]["container"][limit] = json!(64); + assert!( + parse_error(&input).contains("requests must not exceed their limits"), + "{kind}: {request} exceeds {limit}" + ); + } + let mut input = cluster_document(kind); + input["spec"]["services"]["qwen"]["container"]["memoryLimitGiB"] = json!(32); + input["spec"]["services"]["qwen"]["container"]["sharedMemoryGiB"] = json!(33); + input["spec"]["services"]["qwen"]["kubernetes"]["memoryRequestGiB"] = json!(16); + assert!(Document::parse(input.to_string().as_bytes()).is_err()); + input["spec"]["services"]["qwen"]["container"]["sharedMemoryGiB"] = json!(32); + Document::parse(input.to_string().as_bytes()).unwrap(); + input["spec"]["services"]["qwen"]["kubernetes"]["storageGiB"] = json!(15); + assert!(Document::parse(input.to_string().as_bytes()).is_err()); + input["spec"]["services"]["qwen"]["kubernetes"]["storageGiB"] = json!(16); + Document::parse(input.to_string().as_bytes()).unwrap(); + } +} + +#[test] +fn cluster_scheduling_rejects_invalid_names_labels_tolerations_and_secrets() { + let validator = jsonschema::validator_for(&schema::input_schema()).unwrap(); + for (field, value) in [ + ("runtimeClassName", json!("Invalid Class")), + ("storageClass", json!("")), + ("nodeSelector", json!({"not a label": "gpu"})), + ("nodeSelector", json!({"pool": "not a value"})), + ( + "tolerations", + json!([{"key": "gpu", "operator": "Exists", "value": "true"}]), + ), + ( + "tolerations", + json!([{"operator": "Equal", "value": "gpu"}]), + ), + ( + "tolerations", + json!([{"key": "gpu", "operator": "Exists", "effect": "NoSchedule", "tolerationSeconds": 30}]), + ), + ("keySecret", json!({"name": "Not A Name", "key": "key"})), + ("keySecret", json!({"name": "qwen", "key": "a/b"})), + ("memoryRequestGiB", json!((i64::MAX as u64 >> 30) + 1)), + ("storageGiB", json!((i64::MAX as u64 >> 30) + 1)), + ] { + let mut settings = + cluster_document("vllm")["spec"]["services"]["qwen"]["kubernetes"].clone(); + settings[field] = value; + let mut input = cluster_document("vllm"); + input["spec"]["services"]["qwen"]["kubernetes"] = settings.clone(); + assert!(!validator.is_valid(&input), "accepted invalid {field}"); + if let Ok(settings) = serde_json::from_value::(settings) { + assert!(settings.validate().is_err(), "accepted invalid {field}"); + } + } +} + +#[test] +fn cluster_ports_exclude_destinations_openshell_refuses() { + for port in [2379, 2380, 6443, 10250, 10255] { + let mut input = cluster_document("ollama"); + input["spec"]["services"]["qwen"]["serving"]["port"] = json!(port); + assert!( + parse_error(&input).contains("which OpenShell refuses as destinations"), + "{port}" + ); + } +} + +#[test] +fn sandboxes_route_to_a_cluster_service_by_its_service_address() { + for kind in ["vllm", "ollama"] { + let document = Document::parse(fixture(kind).to_string().as_bytes()).unwrap(); + let provider = &document.spec.inference_providers[0]; + let connection = document.provider_connection(provider).unwrap(); + let name = nemoclaw_sdk::services::cluster::name(&document, "qwen"); + let port = match &document.spec.services["qwen"] { + nemoclaw_sdk::services::ServiceDefinition::Vllm(service) => service.serving.port, + nemoclaw_sdk::services::ServiceDefinition::Ollama(service) => service.serving.port, + _ => unreachable!(), + }; + assert_eq!( + connection.endpoint, + format!("http://{name}.nemoclaw-local-{kind}.svc.cluster.local:{port}/v1") + ); + // Only the authenticated vLLM server takes the key, from the provider. + assert_eq!( + connection.credential.map(|credential| credential.env), + (kind == "vllm").then(|| "QWEN_INFERENCE_KEY".to_owned()) + ); + } +} + +#[test] +fn an_authenticated_cluster_service_needs_its_secret_and_its_key_where_nemoclaw_runs() { + let mut input = fixture("vllm"); + input["spec"]["services"]["qwen"]["kubernetes"] + .as_object_mut() + .unwrap() + .remove("keySecret"); + assert!(parse_error(&input).contains("requires kubernetes.keySecret")); + + let mut input = fixture("vllm"); + input["spec"]["inferenceProviders"][0] + .as_object_mut() + .unwrap() + .remove("credential"); + assert!(parse_error(&input).contains("requires credential")); + + // Without authentication there is no key to name. + let mut input = fixture("vllm"); + input["spec"]["services"]["qwen"] + .as_object_mut() + .unwrap() + .remove("authentication"); + assert!(parse_error(&input).contains("applies only to an authenticated vLLM service")); + input["spec"]["services"]["qwen"]["kubernetes"] + .as_object_mut() + .unwrap() + .remove("keySecret"); + let error = parse_error(&input); + assert!( + error.contains( + "credential with serviceRef applies only to an authenticated cluster vLLM service" + ) && !error.contains("QWEN_INFERENCE_KEY"), + "{error}" + ); + + let mut input = fixture("ollama"); + input["spec"]["services"]["qwen"]["kubernetes"]["keySecret"] = + json!({"name": "qwen", "key": "key"}); + assert!(parse_error(&input).contains("applies only to an authenticated vLLM service")); +} + +#[test] +fn a_service_key_with_service_ref_requires_a_cluster_gateway() { + let validator = jsonschema::validator_for(&schema::input_schema()).unwrap(); + let mut input: Value = + serde_saphyr::from_str(include_str!("../../../examples/managed-ollama-gpu.yaml")).unwrap(); + input["spec"]["inferenceProviders"][0]["credential"] = json!({"env": "QWEN_INFERENCE_KEY"}); + assert!(!validator.is_valid(&input)); + let error = parse_error(&input); + assert!( + error.contains("requires a managed Kubernetes or OpenShift gateway") + && !error.contains("QWEN_INFERENCE_KEY"), + "{error}" + ); +} + +#[test] +fn docker_service_defaults_do_not_add_cluster_settings() { + for source in [ + include_str!("../../../examples/spark/vllm.yaml"), + include_str!("../../../examples/managed-ollama-gpu.yaml"), + ] { + let document = Document::parse(source.as_bytes()).unwrap(); + let value = serde_json::to_value(&document).unwrap(); + assert!( + value["spec"]["services"]["qwen"] + .get("kubernetes") + .is_none() + ); + assert_eq!( + Document::parse(document.yaml().unwrap().as_bytes()).unwrap(), + document + ); + } +} diff --git a/crates/nemoclaw-sdk/tests/cluster_services_compile.rs b/crates/nemoclaw-sdk/tests/cluster_services_compile.rs new file mode 100644 index 00000000000..eb3e3f677b9 --- /dev/null +++ b/crates/nemoclaw-sdk/tests/cluster_services_compile.rs @@ -0,0 +1,353 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +//! Cluster model services compile to the Kubernetes provider's objects, fed by +//! the runtime contract, in the deployment's single OpenTofu root. + +use nemoclaw_sdk::{compile, config::Document}; +use serde_json::json; + +fn document(kind: &str) -> Document { + Document::parse(match kind { + "vllm" => include_bytes!("../../test-support/cluster-models/vllm.yaml").as_slice(), + "ollama" => include_bytes!("../../test-support/cluster-models/ollama.yaml").as_slice(), + _ => unreachable!(), + }) + .unwrap() +} + +fn generations() -> compile::Generations { + [ + "workspace", + "provider", + "sandbox", + "kubernetes_storage", + "kubernetes_gateway", + "inference_service", + "ollama_service", + ] + .map(|kind| (kind.into(), "a".repeat(32))) + .into() +} + +fn source(kind: &str) -> &'static str { + match kind { + "vllm" => "vllm_runtime", + _ => "ollama_runtime", + } +} + +#[test] +fn a_cluster_service_runs_the_runtime_contract_as_kubernetes_objects() { + for kind in ["vllm", "ollama"] { + let document = document(kind); + let graph = compile::compile_runtime(&document, &generations(), "0.1.0").unwrap(); + assert_eq!( + graph["terraform"]["required_providers"]["kubernetes"], + json!({"source": "registry.opentofu.org/hashicorp/kubernetes", "version": "= 3.3.0"}) + ); + // The authored kubeconfig and context only; no ambient settings. + assert_eq!( + graph["provider"]["kubernetes"], + json!({"config_path": "${var.nemoclaw_kubeconfig}", "config_context": "replace-with-explicit-context"}) + ); + assert!( + graph["terraform"]["required_providers"] + .get("docker") + .is_none() + ); + let source = source(kind); + assert!(graph["data"][source]["qwen"].is_object(), "{kind}"); + let launch = |field: &str| json!(format!("${{data.{source}.qwen.launch.{field}}}")); + let name = nemoclaw_sdk::services::cluster::name(&document, "qwen"); + let namespace = format!("nemoclaw-local-{kind}"); + + let claim = &graph["resource"]["kubernetes_persistent_volume_claim_v1"]["qwen"]; + assert_eq!(claim["metadata"][0]["name"], format!("{name}-data")); + assert_eq!(claim["metadata"][0]["namespace"], namespace); + assert_eq!(claim["wait_until_bound"], false); + assert_eq!(claim["lifecycle"]["prevent_destroy"], true); + assert_eq!( + claim["depends_on"], + json!(["openshell_kubernetes_storage.runtime"]) + ); + + let deployment = &graph["resource"]["kubernetes_deployment_v1"]["qwen"]; + let spec = &deployment["spec"][0]; + assert_eq!(spec["replicas"], "1"); + assert_eq!(spec["strategy"][0]["type"], "Recreate"); + assert_eq!(deployment["wait_for_rollout"], true); + assert_eq!( + deployment["metadata"][0]["labels"]["nemoclaw.nvidia.com/generation"], + "a".repeat(32) + ); + let pod = &spec["template"][0]["spec"][0]; + assert_eq!(pod["automount_service_account_token"], false); + assert_eq!(pod["node_selector"]["kubernetes.io/arch"], "amd64"); + assert_eq!(pod["node_selector"]["kubernetes.io/os"], "linux"); + assert_eq!( + pod["toleration"], + json!([{"key": "nvidia.com/gpu", "operator": "Exists", "value": "", "effect": "NoSchedule"}]) + ); + let container = &pod["container"][0]; + assert_eq!(container["command"], launch("entrypoint")); + assert_eq!(container["args"], launch("command")); + assert_eq!(container["port"][0]["container_port"], launch("port")); + assert_eq!( + container["readiness_probe"][0]["exec"][0]["command"], + launch("ready_command") + ); + assert!(container.get("liveness_probe").is_none()); + assert_eq!( + container["resources"][0], + json!({ + "requests": {"cpu": "1", "memory": "32Gi"}, + "limits": {"cpu": "4", "memory": "64Gi", "nvidia.com/gpu": "1"}, + }) + ); + assert_eq!( + container["dynamic"]["env"]["for_each"], + launch("environment") + ); + let environment = container["env"].as_array().unwrap(); + assert!( + environment.contains(&json!({"name": "NEMOCLAW_RUNTIME_ON_STOP", "value": "hold"})) + ); + let key = environment + .iter() + .find(|variable| variable.get("value_from").is_some()); + if kind == "vllm" { + assert_eq!( + key.unwrap(), + &json!({"name": launch("key_env"), "value_from": [{"secret_key_ref": [{"name": "qwen-inference-key", "key": "key"}]}]}) + ); + } else { + assert!(key.is_none()); + } + assert_eq!( + container["security_context"][0], + json!({"allow_privilege_escalation": false, "capabilities": [{"drop": ["ALL"]}]}) + ); + assert_eq!( + pod["volume"][0]["persistent_volume_claim"][0]["claim_name"], + format!("{name}-data") + ); + // The policy exists before the server can accept connections. + assert_eq!( + deployment["depends_on"], + json!([ + "openshell_kubernetes_storage.runtime", + "kubernetes_persistent_volume_claim_v1.qwen", + "kubernetes_network_policy_v1.qwen" + ]) + ); + + let service = &graph["resource"]["kubernetes_service_v1"]["qwen"]; + assert_eq!(service["metadata"][0]["name"], name); + assert_eq!(service["spec"][0]["type"], "ClusterIP"); + assert_eq!( + service["spec"][0]["selector"], + spec["selector"][0]["match_labels"] + ); + + let policy = &graph["resource"]["kubernetes_network_policy_v1"]["qwen"]["spec"][0]; + assert_eq!(policy["policy_types"], json!(["Ingress"])); + assert_eq!( + policy["ingress"][0]["from"][0]["pod_selector"][0]["match_labels"], + json!({"openshell.ai/managed-by": "openshell", "openshell.ai/boundary-role": "supervisor"}) + ); + assert_eq!( + policy["pod_selector"][0]["match_labels"], + spec["selector"][0]["match_labels"] + ); + } +} + +#[test] +fn agents_wait_for_the_model_rollout_and_reach_it_by_its_service_address() { + for kind in ["vllm", "ollama"] { + let document = document(kind); + let graph = compile::compile(&document, &generations(), "0.1.0").unwrap(); + // Every object waits on the apply-time gateway read, which waits on + // every runtime resource, the model Deployment's rollout included. + let gates = graph["data"]["openshell_gateway"]["apply"]["depends_on"] + .as_array() + .unwrap(); + for address in [ + "kubernetes_deployment_v1.qwen", + "kubernetes_persistent_volume_claim_v1.qwen", + "kubernetes_service_v1.qwen", + "kubernetes_network_policy_v1.qwen", + ] { + assert!(gates.contains(&json!(address)), "{kind}: {address}"); + } + let inference = graph["resource"]["openshell_inference"] + .as_object() + .unwrap() + .values() + .next() + .unwrap(); + let name = nemoclaw_sdk::services::cluster::name(&document, "qwen"); + assert!( + inference["server"]["endpoint"] + .as_str() + .unwrap() + .starts_with(&format!( + "http://{name}.nemoclaw-local-{kind}.svc.cluster.local:" + )), + "{inference}" + ); + assert_eq!( + inference["server"]["credential_env"], + if kind == "vllm" { + "QWEN_INFERENCE_KEY" + } else { + "" + }, + ); + } +} + +#[test] +fn teardown_keeps_only_the_established_model_volume() { + for kind in ["vllm", "ollama"] { + let document = document(kind); + let all = compile::runtime_targets(&document, &generations()) + .unwrap() + .into_iter() + .map(|target| target.address) + .collect(); + let teardown = compile::compile_teardown(&document, &generations(), "0.1.0", &all).unwrap(); + assert_eq!( + teardown.retained, + [ + "kubernetes_persistent_volume_claim_v1.qwen".into(), + "openshell_kubernetes_storage.runtime".into() + ] + .into() + ); + let resources = &teardown.graph["resource"]; + assert_eq!( + resources["kubernetes_persistent_volume_claim_v1"]["qwen"]["lifecycle"]["prevent_destroy"], + true + ); + for kind in [ + "kubernetes_deployment_v1", + "kubernetes_service_v1", + "kubernetes_network_policy_v1", + ] { + assert!(resources.get(kind).is_none(), "{kind}"); + } + assert!(teardown.graph["provider"]["kubernetes"].is_object()); + // A volume the state never recorded is not created during teardown. + let partial = compile::compile_teardown( + &document, + &generations(), + "0.1.0", + &["openshell_kubernetes_storage.runtime".into()].into(), + ) + .unwrap(); + assert!( + partial.graph["resource"] + .get("kubernetes_persistent_volume_claim_v1") + .is_none() + ); + } +} + +#[test] +fn authored_values_never_become_template_expressions() { + let mut input = serde_json::to_value(document("vllm")).unwrap(); + input["spec"]["services"]["qwen"]["kubernetes"]["nodeSelector"] = json!({"pool": "a${b}"}); + let document = Document::parse(input.to_string().as_bytes()); + // Labels cannot contain `$`; a storage class can't either. The context can. + assert!(document.is_err()); + let mut input = serde_json::to_value(self::document("vllm")).unwrap(); + input["spec"]["gateway"]["kubernetes"]["context"] = json!("ctx-${x}"); + let document = Document::parse(input.to_string().as_bytes()).unwrap(); + let graph = compile::compile_runtime(&document, &generations(), "0.1.0").unwrap(); + assert_eq!( + graph["provider"]["kubernetes"]["config_context"], + "ctx-$${x}" + ); +} + +/// A kubeconfig named `name` for the API at `endpoint`, under the fixture's context. +fn kubeconfig(directory: &std::path::Path, name: &str, endpoint: &str) -> String { + let path = directory.join(name); + std::fs::write( + &path, + json!({"apiVersion":"v1", "kind":"Config", + "clusters":[{"name":"fixture", "cluster":{"server":endpoint}}], + "contexts":[{"name":"replace-with-explicit-context", "context":{"cluster":"fixture", "user":"fixture"}}], + "users":[{"name":"fixture", "user":{}}]}) + .to_string(), + ) + .unwrap(); + path.to_string_lossy().into_owned() +} + +struct Kubeconfig(String); +impl nemoclaw_sdk::Secrets for Kubeconfig { + fn resolve(&self, _: &str) -> Result { + Ok(self.0.clone()) + } +} + +#[tokio::test] +async fn reapply_imports_only_this_deployments_retained_model_volume() { + use nemoclaw_sdk::kubernetes::models::retained_claim_imports; + let _ = rustls::crypto::ring::default_provider().install_default(); + let document = document("vllm"); + let objects = crate::kube_api::Objects::default(); + let fixture = objects.serve().await; + let directory = tempfile::tempdir().unwrap(); + let secrets = Kubeconfig(kubeconfig(directory.path(), "fixture", &fixture.endpoint)); + let unbound = Default::default(); + // A first apply creates the volume. + assert!( + retained_claim_imports(&document, &secrets, &unbound) + .await + .unwrap() + .is_empty() + ); + let claim = format!( + "{}-data", + nemoclaw_sdk::services::cluster::name(&document, "qwen") + ); + let volume = |owner: &str| { + json!({"apiVersion":"v1", "kind":"PersistentVolumeClaim", + "metadata":{"name": claim, "namespace":"nemoclaw-local-vllm", + "labels":{"nemoclaw.nvidia.com/uid": owner}}}) + }; + // After destroy the volume remains and the state no longer records it. + objects.insert(volume(&document.metadata.uid)); + assert_eq!( + retained_claim_imports(&document, &secrets, &unbound) + .await + .unwrap(), + [json!({ + "to": "kubernetes_persistent_volume_claim_v1.qwen", + "id": format!("nemoclaw-local-vllm/{claim}"), + })] + ); + // A recorded volume needs no import, and no cluster read. + let bound = ["kubernetes_persistent_volume_claim_v1.qwen".to_owned()].into(); + let unreachable = Kubeconfig(kubeconfig( + directory.path(), + "unreachable", + "https://127.0.0.1:9", + )); + assert!( + retained_claim_imports(&document, &unreachable, &bound) + .await + .unwrap() + .is_empty() + ); + // Someone else's volume at that name is never adopted. + objects.insert(volume("another-deployment")); + let error = retained_claim_imports(&document, &secrets, &unbound) + .await + .unwrap_err() + .to_string(); + assert!(error.contains("belongs to another owner"), "{error}"); +} diff --git a/crates/nemoclaw-sdk/tests/config_choices.rs b/crates/nemoclaw-sdk/tests/config_choices.rs index dedab329ace..7fb6c1630f3 100644 --- a/crates/nemoclaw-sdk/tests/config_choices.rs +++ b/crates/nemoclaw-sdk/tests/config_choices.rs @@ -75,21 +75,32 @@ fn service_inference_target_preserves_the_service_name() { }; assert!(matches!( provider.target().unwrap(), - InferenceTarget::Service { name: "model" } + InferenceTarget::Service { + name: "model", + credential: None + } )); } +/// The key of an authenticated cluster service; document validation checks +/// it against the service the provider references. #[test] -fn service_inference_target_rejects_credentials_without_exposing_the_reference() { +fn service_inference_target_carries_the_key_of_a_cluster_service() { + let credential = SecretRef { + env: "SECRET_REF".into(), + }; let provider = InferenceProvider { service_ref: Some("model".into()), - credential: Some(SecretRef { - env: "SECRET_REF".into(), - }), + credential: Some(credential.clone()), ..provider() }; - let error = provider.target().unwrap_err().to_string(); - assert!(!error.contains("SECRET_REF")); + assert!(matches!( + provider.target().unwrap(), + InferenceTarget::Service { + name: "model", + credential: Some(found) + } if *found == credential + )); } #[test] diff --git a/crates/nemoclaw-sdk/tests/config_kubernetes.rs b/crates/nemoclaw-sdk/tests/config_kubernetes.rs index 2f1437d0ef1..5383e55ed79 100644 --- a/crates/nemoclaw-sdk/tests/config_kubernetes.rs +++ b/crates/nemoclaw-sdk/tests/config_kubernetes.rs @@ -697,19 +697,24 @@ fn a_reserved_kubernetes_environment_name_states_the_naming_rule() { } #[test] -fn managed_services_with_a_kubernetes_runtime_state_the_cluster_rule() { +fn services_on_a_kubernetes_gateway_require_a_managed_gateway_and_cluster_settings() { let managed = Document::parse(include_bytes!("fixtures/config/managed-ollama.yaml").as_slice()).unwrap(); - let mut input = external_document(); - input["spec"]["services"] = serde_json::to_value(managed.spec.services).unwrap(); - let error = schema_error(&input); - assert!( - error.contains("schema at spec.services (line") - && error.contains( - "Kubernetes requires an external gateway or an explicit managed Kubernetes target, and external inference endpoints; managed services are not supported" - ), - "{error}" - ); + let services = serde_json::to_value(managed.spec.services).unwrap(); + // An external gateway has no cluster for NemoClaw to place services on, + // and a managed one runs only services with kubernetes settings. + for mut input in [external_document(), managed_document()] { + input["spec"]["services"] = services.clone(); + let error = schema_error(&input); + // The rule names the map, or the entry that breaks it. + assert!( + error.contains("schema at spec.services") + && error.contains( + "Kubernetes and OpenShift services require a managed gateway, kind vllm or ollama, and kubernetes settings" + ), + "{error}" + ); + } } #[test] diff --git a/crates/nemoclaw-sdk/tests/main.rs b/crates/nemoclaw-sdk/tests/main.rs index 69684d2de47..6cec66f5123 100644 --- a/crates/nemoclaw-sdk/tests/main.rs +++ b/crates/nemoclaw-sdk/tests/main.rs @@ -29,6 +29,10 @@ mod travel_team; #[path = "agent_tools.rs"] mod agent_tools; +#[path = "cluster_service_config.rs"] +mod cluster_service_config; +#[path = "cluster_services_compile.rs"] +mod cluster_services_compile; #[path = "compile.rs"] mod compile; #[path = "config.rs"] diff --git a/crates/test-support/cluster-models/ollama.yaml b/crates/test-support/cluster-models/ollama.yaml new file mode 100644 index 00000000000..d44ade09f6d --- /dev/null +++ b/crates/test-support/cluster-models/ollama.yaml @@ -0,0 +1,73 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# yaml-language-server: $schema=../../../schemas/nemoclaw-v1alpha1.schema.json +# Test fixture: a managed cluster Ollama service on an AMD64 RTX 4090 node. +apiVersion: nemoclaw.nvidia.com/v1alpha1 +kind: NemoClawConfig +metadata: + name: kubernetes-local-ollama + uid: c79bb6fa-90d3-4ff1-af9a-39cdde3fe321 +spec: + gateway: + management: managed + runtime: + provider: kubernetes + endpoint: https://127.0.0.1:17671 + kubernetes: + kubeconfig: {env: NEMOCLAW_CLUSTER_KUBECONFIG} + context: replace-with-explicit-context + namespace: nemoclaw-local-ollama + authentication: + profile: development + services: + qwen: + kind: ollama + image: registry.example.com/nemoclaw/ollama-amd64@sha256:0000000000000000000000000000000000000000000000000000000000000000 + hardware: + profile: rtx-4090 + architecture: amd64 + model: + name: qwen3:0.6b + digest: 7df6b6e09427a769808717c0a93cadc4ae99ed4eb8bf5ca557c90846becea435 + serving: + contextTokens: 32768 + maxSequences: 1 + startupTimeoutSeconds: 1800 + memory: + gpuMemoryGiB: 16 + container: + cpuLimitMillis: 4000 + memoryLimitGiB: 64 + kubernetes: + cpuRequestMillis: 1000 + memoryRequestGiB: 32 + storageGiB: 20 + # Uses the default StorageClass; set storageClass to select another. + # Set runtimeClassName if the GPU runtime requires it. + tolerations: + - key: nvidia.com/gpu + operator: Exists + effect: NoSchedule + inferenceProviders: + - name: qwen + provider: openai + api: openai-completions + serviceRef: qwen + sandboxes: + - name: assistant + harness: + kind: nvidia.fabric.openclaw + image: + metadata: {env: NEMOCLAW_AGENT_IMAGE_METADATA} + ref: registry.example.com/nemoclaw/openclaw@sha256:0000000000000000000000000000000000000000000000000000000000000000 + network: + tier: isolated + agent: + name: assistant + inference: + routes: + - name: primary + providerRef: qwen + overrides: + model: qwen3:0.6b + maxTokens: 2048 diff --git a/crates/test-support/cluster-models/vllm.yaml b/crates/test-support/cluster-models/vllm.yaml new file mode 100644 index 00000000000..dd2833dcdab --- /dev/null +++ b/crates/test-support/cluster-models/vllm.yaml @@ -0,0 +1,82 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# yaml-language-server: $schema=../../../schemas/nemoclaw-v1alpha1.schema.json +# Test fixture: a managed cluster vLLM service on an AMD64 RTX 4090 node, +# authenticated with a key the platform keeps in the Secret qwen-inference-key. +# QWEN_INFERENCE_KEY holds the same key where nemoclaw runs. +apiVersion: nemoclaw.nvidia.com/v1alpha1 +kind: NemoClawConfig +metadata: + name: kubernetes-local-vllm + uid: 1c756a78-3dcd-458b-a83a-9c546786e704 +spec: + gateway: + management: managed + runtime: + provider: kubernetes + endpoint: https://127.0.0.1:17671 + kubernetes: + kubeconfig: {env: NEMOCLAW_CLUSTER_KUBECONFIG} + context: replace-with-explicit-context + namespace: nemoclaw-local-vllm + authentication: + profile: development + services: + qwen: + kind: vllm + image: registry.example.com/nemoclaw/vllm-amd64@sha256:0000000000000000000000000000000000000000000000000000000000000000 + authentication: bearer + hardware: + profile: rtx-4090 + architecture: amd64 + model: + repository: Qwen/Qwen3-4B + revision: 1cfa9a7208912126459214e8b04321603b3df60c + serving: + toolParser: hermes + reasoningParser: qwen3 + contextTokens: 32768 + maxSequences: 1 + batchTokens: 1024 + startupTimeoutSeconds: 1800 + memory: + gpuMemoryGiB: 20 + kvCacheGiB: 6 + container: + cpuLimitMillis: 4000 + memoryLimitGiB: 64 + kubernetes: + cpuRequestMillis: 1000 + memoryRequestGiB: 32 + storageGiB: 100 + # Uses the default StorageClass; set storageClass to select another. + # Set runtimeClassName if the GPU runtime requires it. + tolerations: + - key: nvidia.com/gpu + operator: Exists + effect: NoSchedule + keySecret: {name: qwen-inference-key, key: key} + inferenceProviders: + - name: qwen + provider: openai + api: openai-completions + serviceRef: qwen + credential: {env: QWEN_INFERENCE_KEY} + sandboxes: + - name: assistant + harness: + kind: nvidia.fabric.openclaw + image: + metadata: {env: NEMOCLAW_AGENT_IMAGE_METADATA} + ref: registry.example.com/nemoclaw/openclaw@sha256:0000000000000000000000000000000000000000000000000000000000000000 + network: + tier: isolated + agent: + name: assistant + inference: + routes: + - name: primary + providerRef: qwen + overrides: + model: Qwen/Qwen3-4B + maxTokens: 2048 diff --git a/docs/build.md b/docs/build.md index 9f007cf115a..8c4593d20c8 100644 --- a/docs/build.md +++ b/docs/build.md @@ -24,7 +24,7 @@ Run the bundle builder: cargo run -p nemoclaw-build -- bundle ``` -The builder downloads and verifies the pinned OpenTofu, Docker provider, and Helm provider archives, builds the CLI and the NemoClaw, OpenShell, and Fabric providers with the lockfile, and writes `dist/`. +The builder downloads and verifies the pinned OpenTofu, Docker provider, Helm provider, and Kubernetes provider archives, builds the CLI and the NemoClaw, OpenShell, and Fabric providers with the lockfile, and writes `dist/`. The manifest records each shipped file's hash, including the unchanged upstream licenses. The SDK verifies the bundle before use. A `Deployment` hashes the bundle on its first operation and again only when the manifest or a file it lists is written, replaced, or removed. @@ -38,7 +38,7 @@ The builder records its source fingerprint at compilation and rejects changed in If it reports `build tool source inputs changed`, rebuild and run it with the `cargo run` command above. The builder also rejects source changes during assembly. Bundles created before schema packaging must be rebuilt; the SDK rejects a manifest that omits the schema or a schema file that fails its recorded hash. -It also rejects bundles missing the pinned Helm provider or its license, or whose recorded hashes fail verification. +It also rejects bundles missing the pinned Helm or Kubernetes provider or its license, or whose recorded hashes fail verification. A source-derived provider version prevents reuse of a stale OpenTofu provider installation. diff --git a/docs/design/architecture.md b/docs/design/architecture.md index ae666e0fbbe..1bbb97ef2ec 100644 --- a/docs/design/architecture.md +++ b/docs/design/architecture.md @@ -16,6 +16,7 @@ The [accepted scope](scope.md) defines the invariants; this page explains the re | OpenTofu | Dependency ordering, concurrent resource reconciliation, and resource state | | Docker provider | Docker containers, images, model-cache volumes, and service networks | | Helm provider | The pinned OpenShell chart release on the authored Kubernetes cluster | +| Kubernetes provider | Managed cluster model services' objects in the gateway's namespace | | OpenShell provider | OpenShell workspaces, provider registrations and profiles, sandboxes, and gateway capability reads; Podman gateway processes, gateway storage, and Kubernetes gateway installation | | Fabric provider | Fabric runtime configuration and readiness in agent sandboxes | | vLLM and Ollama providers | Inference service storage contracts and readiness observations | diff --git a/docs/design/scope.md b/docs/design/scope.md index d78b69625f8..ca58c09c6bb 100644 --- a/docs/design/scope.md +++ b/docs/design/scope.md @@ -16,6 +16,7 @@ NemoClaw provides a public desired-state SDK, CLI, and OpenTofu provider. | OpenTofu | Graph execution and resource state | | Docker provider | Docker gateway, inference, and proxy containers; images, model-cache volumes, and service-owned networks | | Helm provider | Installation, upgrade, and removal of the pinned OpenShell chart release | +| Kubernetes provider | Managed cluster model services' volume claims, Deployments, Services, and NetworkPolicies; Kubernetes runs and restarts the servers | | OpenShell provider | OpenShell workspaces, provider registrations and profiles, sandboxes, and gateway capability reads; Podman gateway processes, gateway initialization and retained bridges, and Kubernetes gateway storage and development authentication | | Fabric provider | Fabric runtime configuration and readiness in agent sandboxes | | vLLM and Ollama providers | Inference service storage, readiness observations, and application-specific persistence | diff --git a/docs/inference.md b/docs/inference.md index 065e85447ac..577080a9ad8 100644 --- a/docs/inference.md +++ b/docs/inference.md @@ -86,6 +86,7 @@ The current tests establish configuration, compilation, API attachment, and drif | NemoClaw should run Ollama on a declared NVIDIA GPU | Declare a service with `kind: ollama`, hardware requirements, a pinned runtime image, a model name and digest, memory, and serving settings | [Managed Ollama](#run-managed-ollama) | | Ollama and its model already run locally and must remain external | Declare a service with `kind: ollamaProxy` to manage an authenticated proxy for one installed model digest | [Proxy configuration](#use-external-ollama-through-a-managed-proxy) | | You run a model server in a Kubernetes or OpenShift gateway's cluster | External `endpoint` naming its Service, `http://..svc.cluster.local:/v1`, and an optional credential reference; follow [in-cluster model servers](kubernetes.md#use-a-model-server-in-the-cluster) | [In-cluster vLLM](../examples/kubernetes/in-cluster-vllm.yaml), [in-cluster Ollama](../examples/kubernetes/in-cluster-ollama.yaml) | +| NemoClaw should run vLLM or Ollama beside a managed Kubernetes or OpenShift gateway | Declare the service as on Docker, plus `kubernetes` requests, storage and scheduling and both container limits; select it with `serviceRef`; follow [managed model services](kubernetes.md#run-a-managed-model-service) | [Managed cluster vLLM](../examples/kubernetes/managed-vllm.yaml), [managed cluster Ollama](../examples/kubernetes/managed-ollama.yaml) | | NemoClaw should download and serve a pinned public model with vLLM | Declare a service with `kind: vllm`, the runtime image, repository revision, capacity, and serving settings; see [managed models](models.md) | [Generic vLLM](../examples/spark/vllm.yaml) | | The Docker daemon running a managed service is reached through SSH | Set `placement.engine` to the SSH endpoint, then declare the private network and `publication` endpoint on the named service; follow [remote service](remote-service.md) | [Remote vLLM](../examples/spark/remote-vllm.yaml) | | The model requires preparation tools or runtime patches | Use an immutable image that packages the recipe's reviewed tools, and declare an [inline recipe](recipes.md) | [Recipe declaration](recipes.md#declaration) | diff --git a/docs/kubernetes.md b/docs/kubernetes.md index bbad4c893ec..60b9c087659 100644 --- a/docs/kubernetes.md +++ b/docs/kubernetes.md @@ -22,8 +22,7 @@ OpenShift's security policy admitting these pods is untested; [current limits](l - [Agent Sandbox](https://github.com/kubernetes-sigs/agent-sandbox), with its controller running in `agent-sandbox-system`; CI tests version 0.5.0. - Exactly one default StorageClass. - **Agent images:** pushed to a registry the cluster can pull from, and referenced by digest. -- **Inference:** an endpoint reachable from inside the sandboxes, such as a [model server you run in the cluster](#use-a-model-server-in-the-cluster). - Managed model services under `spec.services` are not supported on Kubernetes ([#12641](https://github.com/NVIDIA/NemoClaw/issues/12641)). +- **Inference:** an endpoint reachable from inside the sandboxes, such as a [model server you run in the cluster](#use-a-model-server-in-the-cluster), or a [managed model service](#run-a-managed-model-service) that NemoClaw declares beside a managed gateway. NemoClaw installs nothing cluster-wide and never selects a context for you. @@ -208,6 +207,80 @@ spec: Start from [the in-cluster vLLM example](../examples/kubernetes/in-cluster-vllm.yaml), or from [the in-cluster Ollama example](../examples/kubernetes/in-cluster-ollama.yaml) for a server without a key. Both examples use OpenClaw, which can't start in an OpenShell sandbox with the pinned Fabric, so apply stops at the agent until [#13372](https://github.com/NVIDIA/NemoClaw/issues/13372) is fixed. +## Run a Managed Model Service + +Beside a managed gateway, `spec.services` can declare managed vLLM and Ollama services. +NemoClaw declares Kubernetes objects for each one with the bundled Kubernetes provider, and Kubernetes schedules, starts and restarts the server; NemoClaw runs no controller of its own. +This has not run on a real cluster or GPU yet; [current limits](limits.md#platforms-models-and-placement) lists what is untested. + +The service needs `kubernetes` settings and both container limits: + +```yaml +spec: + services: + qwen: + kind: vllm + authentication: bearer + # image, hardware, model, serving and memory as on Docker + container: + cpuLimitMillis: 4000 + memoryLimitGiB: 64 + kubernetes: + cpuRequestMillis: 1000 + memoryRequestGiB: 32 + storageGiB: 100 + tolerations: + - {key: nvidia.com/gpu, operator: Exists, effect: NoSchedule} + keySecret: {name: qwen-inference-key, key: key} + inferenceProviders: + - name: qwen + provider: openai + api: openai-completions + serviceRef: qwen + credential: {env: QWEN_INFERENCE_KEY} +``` + +Start from [the managed vLLM example](../examples/kubernetes/managed-vllm.yaml) or [the managed Ollama example](../examples/kubernetes/managed-ollama.yaml). + +**What NemoClaw declares**, in the gateway's namespace and named after the deployment and the service: + +| Object | Purpose | +|---|---| +| PersistentVolumeClaim `-data` | The model and its prepared data, sized by `storageGiB`, with `storageClass` or the default class; kept on destroy | +| NetworkPolicy | Admits only OpenShell supervisors, which carry sandbox traffic, on the serving port | +| Deployment, one replica, `Recreate` | The server Pod: the runtime image with `vllm_runtime`'s or `ollama_runtime`'s launch, the requests and limits, one `nvidia.com/gpu`, the volume, and `container.sharedMemoryGiB` of memory-backed `/dev/shm` | +| Service, `ClusterIP` | The address sandboxes reach: `http://..svc.cluster.local:/v1` | + +The Pod runs as its image's user with every capability dropped and the runtime default seccomp profile; OpenShift assigns its user. +It is scheduled only on Linux nodes of the model's architecture, plus any `nodeSelector`, `tolerations` and `runtimeClassName` you set. +The gateway's `imagePullSecrets` apply to it too. + +**Cluster prerequisites**, besides those of the gateway: + +- A GPU device plugin that advertises `nvidia.com/gpu`, and the GPU runtime its nodes need. +- A network plugin that enforces NetworkPolicy. Plan and apply warn that the Kubernetes API can't verify this. +- Unlimited locked memory for containers on GPU nodes: Kubernetes can't set process limits, so the node's defaults apply. +- For the kubeconfig identity: create, read, update and delete PersistentVolumeClaims, Deployments, Services and NetworkPolicies in the namespace. + +**Keys:** an authenticated vLLM service reads its key from `keySecret`, a Secret you create in the namespace; NemoClaw never reads or writes it. +Set the provider's `credential` to a variable that holds the same key where you run `nemoclaw`, so OpenShell can add it to sandbox requests. +Ollama takes no key, so the NetworkPolicy is its only access control. + +**Readiness:** apply waits for the Deployment's rollout, up to 9 hours, so the model download and preparation can finish. +The Pod's readiness probe runs the runtime image's `nemoclaw-runtime-ready`, which succeeds only once the model is served; the runtime image must come from a revision that has it. +A server that keeps failing restarts until the rollout deadline expires; read its reason with `kubectl -n logs deploy/` or `kubectl describe pod`. + +**Changes:** with the default `updatePolicy: Preserve`, plan and apply refuse a change that would replace a serving Pod, such as a new image, limits or serving settings. +Set `updatePolicy: Recreate` to accept the replacement and its downtime. +A Deployment whose rollout never completed is replaced without it. + +**Memory protection:** when the runtime's watchdog stops the server, the Pod stays up but unready instead of restarting under the same memory pressure. +Correct the cause, then restart it with `kubectl -n rollout restart deploy/`. + +**Retention:** destroy removes everything but the volume claim. +Applying the same configuration again finds the claim by its name and owner label and reuses it; a claim with the same name and another owner stops apply. +Delete a claim you no longer need with `kubectl -n delete pvc -data`. + ## Destroy a Deployment **Destroy deletes every sandbox's files and conversation history.** @@ -219,6 +292,6 @@ nemoclaw destroy --state-dir .local/kubernetes ``` Destroy removes the sandboxes, the gateway release and the development issuer. -It keeps the namespace, the credential key Secret and the gateway's persistent volumes, as described in [deletion and retention](state.md#deletion-and-retention). +It keeps the namespace, the credential key Secret, the gateway's persistent volumes and managed model services' volume claims, as described in [deletion and retention](state.md#deletion-and-retention). Removing them is not covered yet ([#12640](https://github.com/NVIDIA/NemoClaw/issues/12640)). If destroy fails or is interrupted while removing the gateway release, follow [Recover an Interrupted Helm Removal](usage.md#recover-an-interrupted-helm-removal). diff --git a/docs/limits.md b/docs/limits.md index 4e7ddf98a06..0b33941c705 100644 --- a/docs/limits.md +++ b/docs/limits.md @@ -28,7 +28,7 @@ Other pages state a limit where it affects a procedure and link the same issue. | Distributed inference across several Sparks or Stations | [#12641](https://github.com/NVIDIA/NemoClaw/issues/12641) | | Podman beyond a local rootless Linux gateway: managed inference, rootful operation and remote engines | [#12641](https://github.com/NVIDIA/NemoClaw/issues/12641) | | OpenShift admitting the gateway and sandbox pods; kind runs the OpenShift profile but does not enforce its security constraints | [#12641](https://github.com/NVIDIA/NemoClaw/issues/12641) | -| Model services that NemoClaw places with a Kubernetes or OpenShift gateway; sandboxes can use [a server you run in the cluster](kubernetes.md#use-a-model-server-in-the-cluster) | [#12641](https://github.com/NVIDIA/NemoClaw/issues/12641) | +| [Managed model services](kubernetes.md#run-a-managed-model-service) on a Kubernetes or OpenShift gateway: no real cluster, GPU node, OpenShift security constraint or NetworkPolicy plugin has run them; tests drive the bundled Kubernetes provider against an in-memory API | [#12641](https://github.com/NVIDIA/NemoClaw/issues/12641) | | [A model server you run in the cluster](kubernetes.md#use-a-model-server-in-the-cluster) has been tried only with NemoClaw's vLLM and Ollama runtimes on one kind cluster; OpenShift and other network plugins are untested | [#12641](https://github.com/NVIDIA/NemoClaw/issues/12641) | | Live GPU inference, tools and replies through managed Ollama | [#12641](https://github.com/NVIDIA/NemoClaw/issues/12641) | | Gated repositories, custom remote-code models, GGUF in vLLM, and nested Hugging Face checkpoints | [#12641](https://github.com/NVIDIA/NemoClaw/issues/12641) | diff --git a/docs/provider.md b/docs/provider.md index 4bb8c3b54b0..cd1435693a8 100644 --- a/docs/provider.md +++ b/docs/provider.md @@ -46,6 +46,7 @@ The generated graphs manage these objects and observations: | Docker provider | Docker gateway, inference, proxy, and application containers; model-cache and application volumes, service-owned networks and acquired images | | Docker provider data source | Local images selected with `imagePullPolicy: Never` | | Helm provider | The managed Kubernetes gateway's OpenShell chart release (`helm_release.gateway`) | +| Kubernetes provider | Managed cluster model services: the model volume claim, Deployment, Service and NetworkPolicy (`kubernetes_*_v1`) | Every provider type has a [lifecycle test](contributing/integration-tests.md) that plans hand-written HCL through pinned OpenTofu without SDK orchestration. These tests do not qualify a complete standalone deployment workflow. @@ -71,8 +72,9 @@ The bundle pins these providers: | Host | `registry.opentofu.org/nvidia/host` | Source-derived, matching the bundle | | Docker | `registry.opentofu.org/kreuzwerker/docker` | 4.6.0 | | Helm | `registry.opentofu.org/hashicorp/helm` | 3.3.0 | +| Kubernetes | `registry.opentofu.org/hashicorp/kubernetes` | 3.3.0 | -None of them exposes ephemeral resources or provider functions. +Only the Kubernetes provider exposes ephemeral resources or provider functions, and generated graphs use none of them. ### OpenShell Resources and Data Sources @@ -435,7 +437,7 @@ The `host` provider observes container engines and changes nothing; it has no se | `host_image` | [An image's platform and labels](#runtime-image-compatibility) | | `host_container_health` | [Owned container readiness](#application-container-health): Docker HEALTHCHECK, HTTP, or managed-runtime status | -### Docker and Helm Types +### Docker, Helm, and Kubernetes Types The bundled upstream binaries expose every type below. Generated graphs declare only the types marked as used; NemoClaw does not qualify the others. @@ -448,9 +450,12 @@ Generated graphs declare only the types marked as used; NemoClaw does not qualif | Docker | Resource | `docker_volume` | Model caches | | Docker | Data source | `docker_image` | Local images selected with `imagePullPolicy: Never` | | Helm | Resource | `helm_release` | The managed Kubernetes gateway chart | +| Kubernetes | Resource | `kubernetes_persistent_volume_claim_v1` | [Managed cluster model services'](kubernetes.md#run-a-managed-model-service) retained model volumes | +| Kubernetes | Resource | `kubernetes_deployment_v1`, `kubernetes_service_v1`, `kubernetes_network_policy_v1` | Managed cluster model services' servers, addresses and ingress rules | | Docker | Resource | `docker_buildx_builder`, `docker_compose`, `docker_config`, `docker_plugin`, `docker_registry_image`, `docker_secret`, `docker_service`, `docker_tag` | Unused | | Docker | Data source | `docker_containers`, `docker_logs`, `docker_network`, `docker_plugin`, `docker_registry_image`, `docker_registry_image_manifests`, `docker_registry_image_tags` | Unused | | Helm | Data source | `helm_template` | Unused | +| Kubernetes | Resource, data source, ephemeral resource, function | Every other type the provider serves | Unused | ## OpenShell Resource Lifecycles @@ -899,7 +904,7 @@ Changing any of these settings after creation fails planning and leaves the reso Each NemoClaw resource has a postcondition requiring `running`, so an incomplete step stops apply until a later apply with the same state completes it. The SDK requires each earlier binding before it accepts a later one. -The Helm provider receives only the authored kubeconfig path and context; ambient Helm and Kubernetes settings are excluded. +The Helm and Kubernetes providers receive only the authored kubeconfig path and context; ambient Helm and Kubernetes settings are excluded. Teardown removes the release before the issuer. The authentication resource must confirm through `release_present` that the Helm release records are absent before it deletes the issuer. @@ -910,7 +915,7 @@ The namespace, encryption key, and persistent volumes remain. Follow [bundle building](build.md) for matched CLI, SDK contract, provider, schema, and OpenTofu versions. The NemoClaw, OpenShell, and Fabric providers use the same source-derived version to prevent stale reuse. -The Docker and Helm providers have fixed release versions and checksum-pinned native archives, with their upstream licenses retained in the bundle. +The Docker, Helm, and Kubernetes providers have fixed release versions and checksum-pinned native archives, with their upstream licenses retained in the bundle. [Schema snapshots](contributing/testing.md#provider-schema-snapshots) of the NemoClaw, OpenShell, and Fabric providers, [planning tests](../crates/nemoclaw-provider/tests/planning.rs), and [refresh tests](../crates/nemoclaw-provider/tests/refresh.rs) cover provider contracts. [Fixture qualification](contributing/integration-tests.md) covers real OpenTofu protocol/lifecycle execution with explicit bundle inputs. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index c7ce622a5f4..f75d8e0df27 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -19,7 +19,7 @@ Empty or zero selects a default only where stated. - Document::parse rejects YAML aliases, anchors, merge keys, all explicit tags (including core tags such as !!binary), duplicate keys, multiple documents, and input larger than 1 MiB. It applies the compiled input schema before defaulting; Document::validate applies the normalized schema and semantic checks, including for directly constructed Rust values. - The parser checks the shape of every endpoint URL and the gateway endpoint's transport and address policy; OpenShell checks inference destinations when sandboxes connect. It also checks managed gateway port bounds, canonical private IPv4 /24 networks, local engine socket syntax, and publication address/port/network agreement. -- Managed Kubernetes requires explicit kubeconfig environment, context, namespace, and authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. Local engine fields and managed inference services are excluded; gateway.runtime.provider is kubernetes or openshift. OpenShift uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations. +- Managed Kubernetes requires explicit kubeconfig environment, context, namespace, and authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. Local engine fields are excluded; gateway.runtime.provider is kubernetes or openshift. Managed vLLM and Ollama services require kubernetes settings and explicit container limits, and exclude Docker placement, publication, and host IPC; Kubernetes runs them from the bundled Kubernetes provider's objects. OpenShift uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations. - Explicit sandbox policies are also checked by the pinned OpenShell policy parser and validator, including protocol-specific rule semantics, process identities, filesystem paths, and destination address restrictions. - Explicit filesystem grants must permit reads of the paths the selected image's runtime requires, such as Fabric's /opt/fabric; parent and read-write grants count. Planning checks them against the image's metadata; it does not resolve symlinks or establish runtime permissions. - The schema requires an explicit default for multiple model choices. Rust checks unique route names, that the default names a route, and that native model and tool fields have valid structural shapes. Fabric validates adapter-specific combinations. @@ -377,7 +377,7 @@ Managed Podman targets local rootless Linux; rootful, remote, and other platform | `endpoint` | string | No | `"http://127.0.0.1:17681"` | Local engine gateways use an HTTP origin with an unprivileged loopback port. Kubernetes requires `https://127.0.0.1:PORT` with an explicit nonzero port and no trailing slash; providers forward free local ports of their own to the owned gateway, so this port is not bound. Without kubernetes, omitted or empty selects the local HTTP endpoint. Kubernetes requires an explicit HTTPS loopback endpoint and port. | | `engine` | string | No | `"unix:///var/run/docker.sock"` | Managed local gateway Unix engine socket; Podman requires its API service socket. Excluded by kubernetes. With runtime.provider docker, omitted or empty selects Docker's default socket. Podman requires its API service socket. Excluded by kubernetes. | | `imagePullPolicy` | [ImagePullPolicy](#imagepullpolicy) | No | — | Image acquisition before local container creation. Docker accepts IfNotPresent (the default) or Never; Podman also accepts Always before creation or restart. Excluded by kubernetes. | -| `kubernetes` | [ManagedKubernetes](#managedkubernetes) | No | — | Explicit Kubernetes provisioning target. Excludes local engine, imagePullPolicy, and networkCIDR settings and requires Kubernetes sandboxes without managed inference services. | +| `kubernetes` | [ManagedKubernetes](#managedkubernetes) | No | — | Explicit Kubernetes provisioning target. Excludes local engine, imagePullPolicy, and networkCIDR settings and requires Kubernetes sandboxes. Managed vLLM and Ollama services run in this namespace. | | `management` | string | Yes | — | Whether this deployment manages the gateway. Constraints: `"managed"`. | | `networkCIDR` | string | No | — | Canonical private IPv4 /24 for a managed local gateway. Excluded by kubernetes. Without kubernetes, omitted or empty selects 172.30.N.0/24, where N is the first byte of SHA-256(metadata.uid). Excluded by kubernetes. | | `runtime` | [Runtime](#runtime) | No | — | Compute driver the gateway runs every sandbox with; omission selects Docker. | @@ -526,11 +526,11 @@ Paths: | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| | `api` | [InferenceApi](#inferenceapi) | No | — | Request API. Omission selects anthropic-messages for Anthropic providers and openai-completions for OpenAI providers. NemoClaw uses it to read the endpoint's model catalog; agents use the protocol their adapter selects for the provider. | -| `credential` | [SecretRef](#secretref) | No | — | Optional API credential reference for an external HTTPS endpoint. Excluded by serviceRef. | +| `credential` | [SecretRef](#secretref) | No | — | Optional API credential reference for an external endpoint, or, with serviceRef, the key of an authenticated cluster vLLM service, the same key as its kubernetes.keySecret. | | `endpoint` | string | Without serviceRef | — | Inference HTTP(S) URL owned outside the deployment. Required without serviceRef and excluded with serviceRef. | | `name` | string | Yes | — | Provider name referenced by model choices. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | | `provider` | string | Yes | — | OpenShell provider implementation. Must match the selected API family. Constraints: `"openai"` or `"anthropic"`. | -| `serviceRef` | string | No | — | Name of a managed service in spec.services. Excludes endpoint and credential. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | +| `serviceRef` | string | No | — | Name of a managed service in spec.services. Excludes endpoint, and credential except for an authenticated cluster vLLM service. Constraints: pattern `^[a-z][a-z0-9-]{0,39}$`. | ## InlineRecipe @@ -594,6 +594,21 @@ A key-authenticated HTTP API, such as an MCP service, with a gateway-held key. | `headerName` | string | No | — | The header that carries the key. Defaults to Authorization for bearer; required for header. | | `kind` | string | Yes | — | Integration implementation selected by this definition. Constraints: `"api"`. | +## KeySecret + +A key of an existing Secret in the gateway namespace. + +Guide: [Configuration and credentials](../usage.md#configuration-and-credentials). + +Paths: + +- `spec.services.{key}.kubernetes.keySecret` + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `key` | string | Yes | — | Key within the Secret's data. Constraints: pattern `^[-._a-zA-Z0-9]+$(?![\s\S])`; maximum characters 253. | +| `name` | string | Yes | — | Secret name. Constraints: pattern `^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$(?![\s\S])`; maximum characters 253. | + ## KubernetesAuthentication Authentication provisioned for a managed Kubernetes gateway. @@ -610,6 +625,27 @@ Paths: | `profile` | string | Yes | — | `development` generates a scoped local issuer for isolated qualification; `oidc` uses an existing OIDC issuer, configured in spec.gateway.config's openshell.gateway.oidc table. Constraints: `"development"` or `"oidc"`. | | `token` | [SecretRef](#secretref) | No | — | Environment reference holding the bearer token NemoClaw sends to the gateway. Required for `oidc`; your identity provider's tooling obtains and refreshes it. | +## KubernetesService + +One GPU model service in the managed gateway's namespace. Its model volume survives destroy. + +Guide: [Configuration and credentials](../usage.md#configuration-and-credentials). + +Paths: + +- `spec.services.{key}.kubernetes` + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `cpuRequestMillis` | integer | Yes | — | Requested CPU capacity in millicores. Must not exceed container.cpuLimitMillis. Constraints: minimum 1. | +| `keySecret` | [KeySecret](#keysecret) | No | — | The Secret in the gateway namespace whose key holds the API key of an authenticated vLLM service. The platform owns the Secret; NemoClaw never reads or writes it. Required with authentication and rejected without. | +| `memoryRequestGiB` | integer | Yes | — | Requested container memory in GiB. Must not exceed container.memoryLimitGiB. Constraints: minimum 1; maximum 8589934591. | +| `nodeSelector` | map of string | No | — | Required node labels in addition to Linux and the model's declared CPU architecture. Constraints: keys: pattern `^(?:(?=[^/]{1,253}/)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*/)?[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?$(?![\s\S])`; values: pattern `^(?:[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?$(?![\s\S])`. | +| `runtimeClassName` | string | No | — | Existing RuntimeClass to use for the model Pod. Constraints: pattern `^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$(?![\s\S])`; maximum characters 253. | +| `storageClass` | string | No | — | StorageClass for the retained model volume. Omission selects the cluster default. Constraints: pattern `^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$(?![\s\S])`; maximum characters 253. | +| `storageGiB` | integer | Yes | — | Retained model-volume capacity in GiB. Must cover prepared data plus a 16 GiB working reserve; allow additional space for model downloads and retained snapshots. Constraints: minimum 16; maximum 8589934591. | +| `tolerations` | array of [ServiceToleration](#servicetoleration) | No | — | Node taints the model Pod may tolerate. | + ## ManagedKubernetes Explicit existing-cluster target for a managed development gateway. The SDK does not create a cluster or select an ambient context, and installs nothing cluster-wide: Agent Sandbox and a default StorageClass must already exist. `runtime.provider: openshift` selects the OpenShift profile. @@ -1195,17 +1231,18 @@ Managed Ollama daemon and selected model. | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| -| `container` | [ServiceContainer](#servicecontainer) | No | — | Container CPU and memory limits, IPC, and shared memory for Docker. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory. | +| `container` | [ServiceContainer](#servicecontainer) | No | — | Container CPU and memory limits, IPC, and shared memory for Docker, Kubernetes, and OpenShift. Kubernetes and OpenShift require both limits. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory. | | `hardware` | [ServiceHardware](#servicehardware) | Yes | — | Explicit supported GPU or system profile. | | `image` | string | Yes | — | Immutable runtime image containing Ollama and the NemoClaw supervisor. Constraints: pattern `^[a-zA-Z0-9][a-zA-Z0-9._:/-]*@sha256:[a-f0-9]{64}$`. | | `imagePullPolicy` | [ImagePullPolicy](#imagepullpolicy) | No | — | Image acquisition before container creation. Omission means IfNotPresent. Constraints: `"IfNotPresent"` or `"Never"`. | | `kind` | string | Yes | — | Supported installer selected by this service definition. Constraints: `"ollama"`. | +| `kubernetes` | [KubernetesService](#kubernetesservice) | With a managed Kubernetes or OpenShift gateway | — | Scheduling requests, retained-volume settings and the key Secret for a managed Kubernetes or OpenShift gateway only. Rejected for Docker and Podman. | | `memory` | [OllamaMemory](#ollamamemory) | No | — | GPU budget and resident memory-protection thresholds. | | `model` | [OllamaModel](#ollamamodel) | Yes | — | Selected immutable Ollama registry model. | | `placement` | [ServicePlacement](#serviceplacement) | No | — | Optional remote Docker placement. Requires publication. | | `publication` | [ServicePublication](#servicepublication) | No | — | Private inference address for an explicitly placed service. | | `serving` | [OllamaServing](#ollamaserving) | No | — | Ollama serving limits. | -| `updatePolicy` | [ServiceUpdatePolicy](#serviceupdatepolicy) | No | `"Preserve"` | Preserve refuses replacement of a running Docker model container. Recreate permits sequential replacement and possible downtime until removed or changed. | +| `updatePolicy` | [ServiceUpdatePolicy](#serviceupdatepolicy) | No | `"Preserve"` | Preserve refuses replacement of a running Docker model container or a cluster model Pod. Recreate permits sequential replacement and possible downtime until removed or changed. | ### Alternative 2 @@ -1229,18 +1266,19 @@ Managed vLLM runtime and immutable model snapshot. | Field | Input type | Required | Default | Description and constraints | |---|---|---|---|---| | `authentication` | [ServiceAuthentication](#serviceauthentication) | No | — | Optional native bearer authentication. The runtime uses a key supplied in NEMOCLAW_INFERENCE_KEY, or generates and retains one in its credential storage; omission preserves unauthenticated serving. | -| `container` | [ServiceContainer](#servicecontainer) | No | — | Container CPU and memory limits, IPC, and shared memory for Docker. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory. | +| `container` | [ServiceContainer](#servicecontainer) | No | — | Container CPU and memory limits, IPC, and shared memory for Docker, Kubernetes, and OpenShift. Kubernetes and OpenShift require both limits. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory. | | `hardware` | [ServiceHardware](#servicehardware) | Without recipe | — | Explicit hardware contract: a named GPU or system profile, or dedicated GPU requirements for Linux AMD64. Required without an inline recipe; excludes recipe. | | `image` | string | Yes | — | Immutable runtime image containing vLLM, the NemoClaw supervisor, and any declared recipe tools. Constraints: pattern `^[a-zA-Z0-9][a-zA-Z0-9._:/-]*@sha256:[a-f0-9]{64}$`. | | `imagePullPolicy` | [ImagePullPolicy](#imagepullpolicy) | No | — | Image acquisition before container creation. Omission means IfNotPresent. Constraints: `"IfNotPresent"` or `"Never"`. | | `kind` | string | Yes | — | Supported installer selected by this service definition. Constraints: `"vllm"`. | +| `kubernetes` | [KubernetesService](#kubernetesservice) | With a managed Kubernetes or OpenShift gateway | — | Scheduling requests, retained-volume settings and the key Secret for a managed Kubernetes or OpenShift gateway only. Rejected for Docker and Podman. | | `memory` | [Memory](#memory) | No | — | GPU budget and resident watchdog thresholds. Omission selects the SDK defaults. | | `model` | [Model](#model) | Yes | — | Public Hugging Face repository and immutable commit. | | `placement` | [ServicePlacement](#serviceplacement) | With external gateway or Podman; paired with publication | — | SSH Docker placement. Required with an external gateway or Podman sandbox; requires publication. | | `publication` | [ServicePublication](#servicepublication) | With placement | — | Private inference address reachable by OpenShell. Required with placement. | | `recipe` | [InlineRecipe](#inlinerecipe) | Without hardware | — | Inline preparation and serving contract supplied by the pinned runtime image. Required without hardware; excludes hardware. | | `serving` | [Serving](#serving) | No | — | Service limits. Omission selects the SDK defaults; recipe serving settings select recipe-specific parsers and execution options. | -| `updatePolicy` | [ServiceUpdatePolicy](#serviceupdatepolicy) | No | `"Preserve"` | Preserve refuses replacement of a running Docker model container. Recreate permits sequential replacement and possible downtime until removed or changed. | +| `updatePolicy` | [ServiceUpdatePolicy](#serviceupdatepolicy) | No | `"Preserve"` | Preserve refuses replacement of a running Docker model container or a cluster model Pod. Recreate permits sequential replacement and possible downtime until removed or changed. | ### Alternative 4 @@ -1328,6 +1366,24 @@ Paths: | `bindAddress` | string | Yes | — | Private host IPv4 address outside the service Docker subnet. Loopback is rejected. | | `endpoint` | string | Yes | — | Private HTTP inference URL reachable by OpenShell. Constraints: pattern `^http://.+:[0-9]+/v1$`. | +## ServiceToleration + +One explicit Kubernetes node-taint toleration. + +Guide: [Configuration and credentials](../usage.md#configuration-and-credentials). + +Paths: + +- `spec.services.{key}.kubernetes.tolerations[]` + +| Field | Input type | Required | Default | Description and constraints | +|---|---|---|---|---| +| `effect` | [TolerationEffect](#tolerationeffect) | No | — | Omission matches all taint effects. | +| `key` | string | No | — | Taint key. An empty key requires Exists and matches every key. Constraints: `""` or pattern `^(?:(?=[^/]{1,253}/)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*/)?[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?$(?![\s\S])`. | +| `operator` | [TolerationOperator](#tolerationoperator) | Yes | — | Match the taint's value with Equal, or its presence with Exists. | +| `tolerationSeconds` | integer | No | — | Optional eviction delay, valid only for NoExecute tolerations. Constraints: minimum 0; maximum 9223372036854775807. | +| `value` | string | No | — | Value matched by Equal; Exists requires an empty value. Constraints: pattern `^(?:[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?$(?![\s\S])`. | + ## ServiceUpdatePolicy Whether updates may stop an existing model service before its replacement is ready. @@ -1426,6 +1482,34 @@ Paths: | `certificate` | [FileRef](#fileref) | Yes | — | Environment variable whose value names the local client certificate file. | | `key` | [FileRef](#fileref) | Yes | — | Environment variable whose value names the local client private-key file. | +## TolerationEffect + +Node-taint effect matched by a toleration. + +Guide: [Configuration and credentials](../usage.md#configuration-and-credentials). + +Paths: + +- `spec.services.{key}.kubernetes.tolerations[].effect` + +Accepted input: string. + +Constraints: `"NoSchedule"` or `"PreferNoSchedule"` or `"NoExecute"`. + +## TolerationOperator + +How a toleration matches a node taint. + +Guide: [Configuration and credentials](../usage.md#configuration-and-credentials). + +Paths: + +- `spec.services.{key}.kubernetes.tolerations[].operator` + +Accepted input: string. + +Constraints: `"Equal"` or `"Exists"`. + ## Tool Executable identity inside the runtime image; this is not a shell command. diff --git a/docs/state.md b/docs/state.md index d2f2f90e4b6..01e14c2a154 100644 --- a/docs/state.md +++ b/docs/state.md @@ -206,6 +206,7 @@ To retire a deployment whose retained resources are on Docker engines, follow [R | External gateway, inference service, external Ollama daemon/model, and externally owned engine/network | Remain under their operators' control | | OpenShell workspace | Deleted; re-applying the configuration recreates it | | Managed vLLM/Ollama process containers and service-owned networks | Removed; model storage remains tracked | +| Managed cluster vLLM/Ollama Deployments, Services and NetworkPolicies | Removed; the model volume claim remains tracked | | Managed model downloads and prepared data | Native Docker volumes retained by default; missing caches may be reconstructed separately from credentials | | Managed vLLM credentials | Separate tracked credential volume retained | | Managed Ollama proxy | Container removed; tracked credential volume retained | @@ -240,6 +241,7 @@ On a managed Kubernetes or OpenShift gateway, destroy keeps these objects, all i | The namespace itself | Everything below; NemoClaw creates it and never adopts an existing one | | Secret `GATEWAY-kek`, where `GATEWAY` is the gateway's release name | The gateway's key-encryption key | | The gateway's PersistentVolumeClaims, and the volumes bound to them | The gateway's database | +| PersistentVolumeClaim `NAME-data` of each [managed model service](kubernetes.md#run-a-managed-model-service), and its volume | The model and its prepared data; a later apply of the same configuration reuses it | The state directory keeps the cluster ownership receipt and, for the `development` authentication profile, the development issuer's keys. diff --git a/docs/usage.md b/docs/usage.md index 3d3d5344a1f..bc0f937fec1 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -556,7 +556,7 @@ It has been run against a managed rootless Podman 5.8.8 gateway. #### On Kubernetes or OpenShift -Destroy keeps the deployment's namespace, the gateway's key Secret and its persistent volume claims ([retained Kubernetes objects](state.md#find-retained-kubernetes-objects)). +Destroy keeps the deployment's namespace, the gateway's key Secret, its persistent volume claims and managed model services' volume claims ([retained Kubernetes objects](state.md#find-retained-kubernetes-objects)). Deleting the namespace removes them all. Use the kubeconfig and context the deployment uses, and set `deployment_namespace` to its `gateway.kubernetes.namespace`: diff --git a/examples/kubernetes/managed-ollama.yaml b/examples/kubernetes/managed-ollama.yaml new file mode 100644 index 00000000000..4548089e893 --- /dev/null +++ b/examples/kubernetes/managed-ollama.yaml @@ -0,0 +1,81 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# An agent on a managed Kubernetes gateway uses an Ollama server that NemoClaw +# runs in the gateway's namespace with the bundled Kubernetes provider. +# Kubernetes schedules, starts and restarts it; see "Run a Managed Model +# Service" in docs/kubernetes.md for the cluster prerequisites. +# Ollama takes no key, so a NetworkPolicy is its only access control. +# Replace the deployment UID, the context, and both image digests before +# applying. The runtime image must come from this revision's runtimes/ollama. +# Write the agent image's metadata bundle with `cargo images export-metadata` +# and set NEMOCLAW_AGENT_IMAGE_METADATA to its path; see docs/build.md. +apiVersion: nemoclaw.nvidia.com/v1alpha1 +kind: NemoClawConfig +metadata: + name: kubernetes-managed-ollama + uid: b2d6e9f4-1a7c-4e58-8f3b-6d0c5a1e7b94 +spec: + gateway: + management: managed + runtime: + provider: kubernetes + endpoint: https://127.0.0.1:17671 + kubernetes: + kubeconfig: {env: NEMOCLAW_CLUSTER_KUBECONFIG} + context: replace-with-explicit-context + namespace: nemoclaw-managed-ollama + authentication: + profile: development + services: + qwen: + kind: ollama + image: registry.example.com/nemoclaw/ollama-amd64@sha256:0000000000000000000000000000000000000000000000000000000000000000 + hardware: + profile: rtx-4090 + architecture: amd64 + model: + name: qwen3:0.6b + digest: 7df6b6e09427a769808717c0a93cadc4ae99ed4eb8bf5ca557c90846becea435 + serving: + contextTokens: 32768 + maxSequences: 1 + startupTimeoutSeconds: 1800 + memory: + gpuMemoryGiB: 16 + container: + cpuLimitMillis: 4000 + memoryLimitGiB: 64 + kubernetes: + cpuRequestMillis: 1000 + memoryRequestGiB: 32 + storageGiB: 20 + # Uses the default StorageClass; set storageClass to select another. + # Set runtimeClassName if the GPU runtime requires it. + tolerations: + - key: nvidia.com/gpu + operator: Exists + effect: NoSchedule + inferenceProviders: + - name: qwen + provider: openai + api: openai-completions + serviceRef: qwen + sandboxes: + - name: assistant + harness: + kind: nvidia.fabric.openclaw + image: + metadata: {env: NEMOCLAW_AGENT_IMAGE_METADATA} + ref: registry.example.com/nemoclaw/openclaw@sha256:0000000000000000000000000000000000000000000000000000000000000000 + network: + tier: isolated + agent: + name: assistant + inference: + routes: + - name: primary + providerRef: qwen + overrides: + model: qwen3:0.6b + maxTokens: 2048 diff --git a/examples/kubernetes/managed-vllm.yaml b/examples/kubernetes/managed-vllm.yaml new file mode 100644 index 00000000000..95697de6e56 --- /dev/null +++ b/examples/kubernetes/managed-vllm.yaml @@ -0,0 +1,90 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# yaml-language-server: $schema=../../schemas/nemoclaw-v1alpha1.schema.json +# An agent on a managed Kubernetes gateway uses a vLLM server that NemoClaw +# runs in the gateway's namespace with the bundled Kubernetes provider. +# Kubernetes schedules, starts and restarts it; see "Run a Managed Model +# Service" in docs/kubernetes.md for the cluster prerequisites. +# The server requires a key: create the Secret qwen-inference-key with the key +# under "key" in the namespace, and set QWEN_INFERENCE_KEY to the same key +# where you run nemoclaw. +# Replace the deployment UID, the context, and both image digests before +# applying. The runtime image must come from this revision's runtimes/vllm. +# Write the agent image's metadata bundle with `cargo images export-metadata` +# and set NEMOCLAW_AGENT_IMAGE_METADATA to its path; see docs/build.md. +apiVersion: nemoclaw.nvidia.com/v1alpha1 +kind: NemoClawConfig +metadata: + name: kubernetes-managed-vllm + uid: 5f0a3c2e-8d41-4b7a-9e16-2c7b4a9d8e31 +spec: + gateway: + management: managed + runtime: + provider: kubernetes + endpoint: https://127.0.0.1:17671 + kubernetes: + kubeconfig: {env: NEMOCLAW_CLUSTER_KUBECONFIG} + context: replace-with-explicit-context + namespace: nemoclaw-managed-vllm + authentication: + profile: development + services: + qwen: + kind: vllm + image: registry.example.com/nemoclaw/vllm-amd64@sha256:0000000000000000000000000000000000000000000000000000000000000000 + authentication: bearer + hardware: + profile: rtx-4090 + architecture: amd64 + model: + repository: Qwen/Qwen3-4B + revision: 1cfa9a7208912126459214e8b04321603b3df60c + serving: + toolParser: hermes + reasoningParser: qwen3 + contextTokens: 32768 + maxSequences: 1 + batchTokens: 1024 + startupTimeoutSeconds: 1800 + memory: + gpuMemoryGiB: 20 + kvCacheGiB: 6 + container: + cpuLimitMillis: 4000 + memoryLimitGiB: 64 + kubernetes: + cpuRequestMillis: 1000 + memoryRequestGiB: 32 + storageGiB: 100 + # Uses the default StorageClass; set storageClass to select another. + # Set runtimeClassName if the GPU runtime requires it. + tolerations: + - key: nvidia.com/gpu + operator: Exists + effect: NoSchedule + keySecret: {name: qwen-inference-key, key: key} + inferenceProviders: + - name: qwen + provider: openai + api: openai-completions + serviceRef: qwen + credential: {env: QWEN_INFERENCE_KEY} + sandboxes: + - name: assistant + harness: + kind: nvidia.fabric.openclaw + image: + metadata: {env: NEMOCLAW_AGENT_IMAGE_METADATA} + ref: registry.example.com/nemoclaw/openclaw@sha256:0000000000000000000000000000000000000000000000000000000000000000 + network: + tier: isolated + agent: + name: assistant + inference: + routes: + - name: primary + providerRef: qwen + overrides: + model: Qwen/Qwen3-4B + maxTokens: 2048 diff --git a/schemas/nemoclaw-v1alpha1.schema.json b/schemas/nemoclaw-v1alpha1.schema.json index 7a70e1d7c0a..44bdbac9045 100644 --- a/schemas/nemoclaw-v1alpha1.schema.json +++ b/schemas/nemoclaw-v1alpha1.schema.json @@ -653,7 +653,7 @@ }, "kubernetes": { "$ref": "#/$defs/ManagedKubernetes", - "description": "Explicit Kubernetes provisioning target. Excludes local engine, imagePullPolicy, and networkCIDR settings and requires Kubernetes sandboxes without managed inference services." + "description": "Explicit Kubernetes provisioning target. Excludes local engine, imagePullPolicy, and networkCIDR settings and requires Kubernetes sandboxes. Managed vLLM and Ollama services run in this namespace." }, "management": { "const": "managed", @@ -1010,7 +1010,7 @@ }, "credential": { "$ref": "#/$defs/SecretRef", - "description": "Optional API credential reference for an external HTTPS endpoint. Excluded by serviceRef." + "description": "Optional API credential reference for an external endpoint, or, with serviceRef, the key of an authenticated cluster vLLM service, the same key as its kubernetes.keySecret." }, "endpoint": { "description": "Inference HTTP(S) URL owned outside the deployment. Required without serviceRef and excluded with serviceRef.", @@ -1031,7 +1031,7 @@ "type": "string" }, "serviceRef": { - "description": "Name of a managed service in spec.services. Excludes endpoint and credential.", + "description": "Name of a managed service in spec.services. Excludes endpoint, and credential except for an authenticated cluster vLLM service.", "pattern": "^[a-z][a-z0-9-]{0,39}$", "type": "string" } @@ -1041,19 +1041,6 @@ "provider" ], "then": { - "allOf": [ - { - "not": { - "anyOf": [ - { - "required": [ - "credential" - ] - } - ] - } - } - ], "properties": { "endpoint": { "const": "" @@ -1202,6 +1189,29 @@ } ] }, + "KeySecret": { + "additionalProperties": false, + "description": "A key of an existing Secret in the gateway namespace.", + "properties": { + "key": { + "description": "Key within the Secret's data.", + "maxLength": 253, + "pattern": "^[-._a-zA-Z0-9]+$(?![\\s\\S])", + "type": "string" + }, + "name": { + "description": "Secret name.", + "maxLength": 253, + "pattern": "^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$(?![\\s\\S])", + "type": "string" + } + }, + "required": [ + "name", + "key" + ], + "type": "object" + }, "KubernetesAuthentication": { "additionalProperties": false, "allOf": [ @@ -1317,6 +1327,72 @@ ], "type": "object" }, + "KubernetesService": { + "additionalProperties": false, + "description": "One GPU model service in the managed gateway's namespace. Its model volume survives destroy.", + "properties": { + "cpuRequestMillis": { + "description": "Requested CPU capacity in millicores. Must not exceed container.cpuLimitMillis.", + "format": "uint32", + "minimum": 1, + "type": "integer" + }, + "keySecret": { + "$ref": "#/$defs/KeySecret", + "description": "The Secret in the gateway namespace whose key holds the API key of an authenticated vLLM service. The platform owns the Secret; NemoClaw never reads or writes it. Required with authentication and rejected without." + }, + "memoryRequestGiB": { + "description": "Requested container memory in GiB. Must not exceed container.memoryLimitGiB.", + "format": "uint64", + "maximum": 8589934591, + "minimum": 1, + "type": "integer" + }, + "nodeSelector": { + "additionalProperties": { + "pattern": "^(?:[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?$(?![\\s\\S])", + "type": "string" + }, + "description": "Required node labels in addition to Linux and the model's declared CPU architecture.", + "propertyNames": { + "pattern": "^(?:(?=[^/]{1,253}/)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*/)?[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?$(?![\\s\\S])" + }, + "type": "object" + }, + "runtimeClassName": { + "description": "Existing RuntimeClass to use for the model Pod.", + "maxLength": 253, + "pattern": "^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$(?![\\s\\S])", + "type": "string" + }, + "storageClass": { + "description": "StorageClass for the retained model volume. Omission selects the cluster default.", + "maxLength": 253, + "pattern": "^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$(?![\\s\\S])", + "type": "string" + }, + "storageGiB": { + "description": "Retained model-volume capacity in GiB. Must cover prepared data plus a 16 GiB working reserve; allow additional space for model downloads and retained snapshots.", + "format": "uint64", + "maximum": 8589934591, + "minimum": 16, + "type": "integer" + }, + "tolerations": { + "description": "Node taints the model Pod may tolerate.", + "items": { + "$ref": "#/$defs/ServiceToleration" + }, + "type": "array" + } + }, + "required": [ + "cpuRequestMillis", + "memoryRequestGiB", + "storageGiB" + ], + "type": "object" + }, "ManagedKubernetes": { "additionalProperties": false, "description": "Explicit existing-cluster target for a managed development gateway. The SDK does not create a cluster or select an ambient context, and installs nothing cluster-wide: Agent Sandbox and a default StorageClass must already exist. `runtime.provider: openshift` selects the OpenShift profile.", @@ -2759,6 +2835,69 @@ } ] } + }, + { + "if": { + "required": [ + "kubernetes" + ] + }, + "then": { + "allOf": [ + { + "properties": { + "container": { + "properties": { + "cpuLimitMillis": {} + }, + "required": [ + "cpuLimitMillis" + ] + } + }, + "required": [ + "container" + ], + "x-nemoclaw-error": "cluster model services require container.cpuLimitMillis" + }, + { + "properties": { + "container": { + "properties": { + "memoryLimitGiB": {} + }, + "required": [ + "memoryLimitGiB" + ] + } + }, + "required": [ + "container" + ], + "x-nemoclaw-error": "cluster model services require container.memoryLimitGiB" + }, + { + "properties": { + "serving": { + "properties": { + "port": { + "not": { + "enum": [ + 2379, + 2380, + 6443, + 10250, + 10255 + ] + } + } + } + } + }, + "x-nemoclaw-error": "a cluster model service's serving.port must not be 2379, 2380, 6443, 10250, or 10255, which OpenShell refuses as destinations" + } + ] + } } ], "dependentRequired": { @@ -2773,7 +2912,7 @@ "properties": { "container": { "$ref": "#/$defs/ServiceContainer", - "description": "Container CPU and memory limits, IPC, and shared memory for Docker. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory." + "description": "Container CPU and memory limits, IPC, and shared memory for Docker, Kubernetes, and OpenShift. Kubernetes and OpenShift require both limits. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory." }, "hardware": { "$ref": "#/$defs/ServiceHardware", @@ -2798,6 +2937,11 @@ "description": "Supported installer selected by this service definition.", "type": "string" }, + "kubernetes": { + "$ref": "#/$defs/KubernetesService", + "description": "Scheduling requests, retained-volume settings and the key Secret for a managed Kubernetes or OpenShift gateway only. Rejected for Docker and Podman.", + "x-nemoclaw-required": "With a managed Kubernetes or OpenShift gateway" + }, "memory": { "$ref": "#/$defs/OllamaMemory", "description": "GPU budget and resident memory-protection thresholds." @@ -2821,7 +2965,7 @@ "updatePolicy": { "$ref": "#/$defs/ServiceUpdatePolicy", "default": "Preserve", - "description": "Preserve refuses replacement of a running Docker model container. Recreate permits sequential replacement and possible downtime until removed or changed." + "description": "Preserve refuses replacement of a running Docker model container or a cluster model Pod. Recreate permits sequential replacement and possible downtime until removed or changed." } }, "required": [ @@ -3048,6 +3192,69 @@ } ] } + }, + { + "if": { + "required": [ + "kubernetes" + ] + }, + "then": { + "allOf": [ + { + "properties": { + "container": { + "properties": { + "cpuLimitMillis": {} + }, + "required": [ + "cpuLimitMillis" + ] + } + }, + "required": [ + "container" + ], + "x-nemoclaw-error": "cluster model services require container.cpuLimitMillis" + }, + { + "properties": { + "container": { + "properties": { + "memoryLimitGiB": {} + }, + "required": [ + "memoryLimitGiB" + ] + } + }, + "required": [ + "container" + ], + "x-nemoclaw-error": "cluster model services require container.memoryLimitGiB" + }, + { + "properties": { + "serving": { + "properties": { + "port": { + "not": { + "enum": [ + 2379, + 2380, + 6443, + 10250, + 10255 + ] + } + } + } + } + }, + "x-nemoclaw-error": "a cluster model service's serving.port must not be 2379, 2380, 6443, 10250, or 10255, which OpenShell refuses as destinations" + } + ] + } } ], "dependentRequired": { @@ -3082,7 +3289,7 @@ }, "container": { "$ref": "#/$defs/ServiceContainer", - "description": "Container CPU and memory limits, IPC, and shared memory for Docker. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory." + "description": "Container CPU and memory limits, IPC, and shared memory for Docker, Kubernetes, and OpenShift. Kubernetes and OpenShift require both limits. Native managed Podman inference is unsupported. Omission uses private IPC and 8 GiB of shared memory." }, "hardware": { "$ref": "#/$defs/ServiceHardware", @@ -3108,6 +3315,11 @@ "description": "Supported installer selected by this service definition.", "type": "string" }, + "kubernetes": { + "$ref": "#/$defs/KubernetesService", + "description": "Scheduling requests, retained-volume settings and the key Secret for a managed Kubernetes or OpenShift gateway only. Rejected for Docker and Podman.", + "x-nemoclaw-required": "With a managed Kubernetes or OpenShift gateway" + }, "memory": { "$ref": "#/$defs/Memory", "description": "GPU budget and resident watchdog thresholds. Omission selects the SDK defaults." @@ -3138,7 +3350,7 @@ "updatePolicy": { "$ref": "#/$defs/ServiceUpdatePolicy", "default": "Preserve", - "description": "Preserve refuses replacement of a running Docker model container. Recreate permits sequential replacement and possible downtime until removed or changed." + "description": "Preserve refuses replacement of a running Docker model container or a cluster model Pod. Recreate permits sequential replacement and possible downtime until removed or changed." } }, "required": [ @@ -3385,6 +3597,96 @@ ], "type": "object" }, + "ServiceToleration": { + "additionalProperties": false, + "allOf": [ + { + "else": { + "properties": { + "key": { + "minLength": 1 + } + }, + "required": [ + "key" + ] + }, + "if": { + "properties": { + "operator": { + "const": "Exists" + } + }, + "required": [ + "operator" + ] + }, + "then": { + "properties": { + "value": { + "const": "" + } + } + } + }, + { + "if": { + "required": [ + "tolerationSeconds" + ] + }, + "then": { + "properties": { + "effect": { + "const": "NoExecute" + } + }, + "required": [ + "effect" + ] + } + } + ], + "description": "One explicit Kubernetes node-taint toleration.", + "properties": { + "effect": { + "$ref": "#/$defs/TolerationEffect", + "description": "Omission matches all taint effects." + }, + "key": { + "anyOf": [ + { + "const": "" + }, + { + "pattern": "^(?:(?=[^/]{1,253}/)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*/)?[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?$(?![\\s\\S])" + } + ], + "description": "Taint key. An empty key requires Exists and matches every key.", + "type": "string" + }, + "operator": { + "$ref": "#/$defs/TolerationOperator", + "description": "Match the taint's value with Equal, or its presence with Exists." + }, + "tolerationSeconds": { + "description": "Optional eviction delay, valid only for NoExecute tolerations.", + "format": "uint64", + "maximum": 9223372036854775807, + "minimum": 0, + "type": "integer" + }, + "value": { + "description": "Value matched by Equal; Exists requires an empty value.", + "pattern": "^(?:[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?$(?![\\s\\S])", + "type": "string" + } + }, + "required": [ + "operator" + ], + "type": "object" + }, "ServiceUpdatePolicy": { "description": "Whether updates may stop an existing model service before its replacement is ready.", "oneOf": [ @@ -3770,6 +4072,23 @@ ], "type": "object" }, + "TolerationEffect": { + "description": "Node-taint effect matched by a toleration.", + "enum": [ + "NoSchedule", + "PreferNoSchedule", + "NoExecute" + ], + "type": "string" + }, + "TolerationOperator": { + "description": "How a toleration matches a node taint.", + "enum": [ + "Equal", + "Exists" + ], + "type": "string" + }, "Tool": { "additionalProperties": false, "description": "Executable identity inside the runtime image; this is not a shell command.", @@ -4137,20 +4456,369 @@ ] } ] + } + ], + "x-nemoclaw-error": "Kubernetes requires an external gateway or an explicit managed Kubernetes target" + } + }, + { + "else": { + "allOf": [ + { + "properties": { + "spec": { + "properties": { + "services": { + "additionalProperties": { + "not": { + "anyOf": [ + { + "required": [ + "kubernetes" + ] + } + ] + } + } + } + } + } + } + } + ], + "x-nemoclaw-error": "service kubernetes settings require a managed Kubernetes or OpenShift gateway and are not supported with Docker or Podman" + }, + "if": { + "properties": { + "spec": { + "properties": { + "gateway": { + "properties": { + "runtime": { + "properties": { + "provider": { + "enum": [ + "kubernetes", + "openshift" + ] + } + }, + "required": [ + "provider" + ] + } + }, + "required": [ + "runtime" + ] + } + }, + "required": [ + "gateway" + ] + } + }, + "required": [ + "spec" + ] + }, + "then": { + "allOf": [ + { + "if": { + "properties": { + "spec": { + "properties": { + "gateway": { + "properties": { + "management": { + "const": "external" + } + }, + "required": [ + "management" + ] + } + }, + "required": [ + "gateway" + ] + } + }, + "required": [ + "spec" + ] + }, + "then": { + "properties": { + "spec": { + "properties": { + "services": { + "maxProperties": 0 + } + } + } + } + } }, { "properties": { "spec": { "properties": { "services": { - "maxProperties": 0 + "additionalProperties": { + "properties": { + "kind": { + "enum": [ + "vllm", + "ollama" + ] + } + }, + "required": [ + "kubernetes" + ] + } + } + } + } + } + } + ], + "x-nemoclaw-error": "Kubernetes and OpenShift services require a managed gateway, kind vllm or ollama, and kubernetes settings" + } + }, + { + "if": { + "not": { + "properties": { + "spec": { + "properties": { + "gateway": { + "properties": { + "runtime": { + "properties": { + "provider": { + "enum": [ + "kubernetes", + "openshift" + ] + } + }, + "required": [ + "provider" + ] + } + }, + "required": [ + "runtime" + ] + } + }, + "required": [ + "gateway" + ] + } + }, + "required": [ + "spec" + ] + } + }, + "then": { + "allOf": [ + { + "properties": { + "spec": { + "properties": { + "inferenceProviders": { + "items": { + "if": { + "required": [ + "serviceRef" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "credential" + ] + } + ] + } + } + } + } + } + } + } + }, + { + "properties": { + "spec": { + "properties": { + "sandboxes": { + "items": { + "properties": { + "inferenceProviders": { + "items": { + "if": { + "required": [ + "serviceRef" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "credential" + ] + } + ] + } + } + } + } + } + } + } + } + } + } + }, + { + "properties": { + "spec": { + "properties": { + "inferences": { + "additionalProperties": { + "properties": { + "routes": { + "items": { + "properties": { + "provider": { + "if": { + "required": [ + "serviceRef" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "credential" + ] + } + ] + } + } + } + } + } + } + } + } + } + } + } + } + }, + { + "properties": { + "spec": { + "properties": { + "sandboxes": { + "items": { + "properties": { + "inferences": { + "additionalProperties": { + "properties": { + "routes": { + "items": { + "properties": { + "provider": { + "if": { + "required": [ + "serviceRef" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "credential" + ] + } + ] + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + }, + { + "properties": { + "spec": { + "properties": { + "sandboxes": { + "items": { + "properties": { + "agent": { + "properties": { + "inference": { + "properties": { + "routes": { + "items": { + "properties": { + "provider": { + "if": { + "required": [ + "serviceRef" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "credential" + ] + } + ] + } + } + } + } + } + } + } + } + } + } + } + } } } } } } ], - "x-nemoclaw-error": "Kubernetes requires an external gateway or an explicit managed Kubernetes target, and external inference endpoints; managed services are not supported" + "x-nemoclaw-error": "credential with serviceRef is the key of an authenticated cluster vLLM service and requires a managed Kubernetes or OpenShift gateway" } } ], @@ -4186,7 +4854,7 @@ "x-nemoclaw-parser-checks": [ "Document::parse rejects YAML aliases, anchors, merge keys, all explicit tags (including core tags such as !!binary), duplicate keys, multiple documents, and input larger than 1 MiB. It applies the compiled input schema before defaulting; Document::validate applies the normalized schema and semantic checks, including for directly constructed Rust values.", "The parser checks the shape of every endpoint URL and the gateway endpoint's transport and address policy; OpenShell checks inference destinations when sandboxes connect. It also checks managed gateway port bounds, canonical private IPv4 /24 networks, local engine socket syntax, and publication address/port/network agreement.", - "Managed Kubernetes requires explicit kubeconfig environment, context, namespace, and authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. Local engine fields and managed inference services are excluded; gateway.runtime.provider is kubernetes or openshift. OpenShift uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations.", + "Managed Kubernetes requires explicit kubeconfig environment, context, namespace, and authentication profile; Agent Sandbox and one default StorageClass must already be installed. Its HTTPS endpoint is exactly 127.0.0.1 with an explicit port from 1 through 65535 and no path. Local engine fields are excluded; gateway.runtime.provider is kubernetes or openshift. Managed vLLM and Ollama services require kubernetes settings and explicit container limits, and exclude Docker placement, publication, and host IPC; Kubernetes runs them from the bundled Kubernetes provider's objects. OpenShift uses the upstream Kubernetes driver and requires platform-owned OpenShift security prerequisites. Cluster identity, ownership, prerequisite compatibility, and credential files are checked during operations.", "Explicit sandbox policies are also checked by the pinned OpenShell policy parser and validator, including protocol-specific rule semantics, process identities, filesystem paths, and destination address restrictions.", "Explicit filesystem grants must permit reads of the paths the selected image's runtime requires, such as Fabric's /opt/fabric; parent and read-write grants count. Planning checks them against the image's metadata; it does not resolve symlinks or establish runtime permissions.", "The schema requires an explicit default for multiple model choices. Rust checks unique route names, that the default names a route, and that native model and tool fields have valid structural shapes. Fabric validates adapter-specific combinations.", diff --git a/versions.json b/versions.json index e89eb73bc2e..b83e97afa7d 100644 --- a/versions.json +++ b/versions.json @@ -27,6 +27,10 @@ "helmProvider": { "url": "https://releases.hashicorp.com/terraform-provider-helm/3.3.0/terraform-provider-helm_3.3.0_linux_arm64.zip", "sha256": "77515e5576f4ea3d8d9e404237882de62518950ccd7b312371f5c03580f22fb0" + }, + "kubernetesProvider": { + "url": "https://releases.hashicorp.com/terraform-provider-kubernetes/3.3.0/terraform-provider-kubernetes_3.3.0_linux_arm64.zip", + "sha256": "0e91225427284c67b313fda814439416f83c484c017df5c902992ae936154ae2" } }, "linux_amd64": { @@ -53,6 +57,10 @@ "helmProvider": { "url": "https://releases.hashicorp.com/terraform-provider-helm/3.3.0/terraform-provider-helm_3.3.0_linux_amd64.zip", "sha256": "24a942352667cf49bed467c51a951f17a6c13e0cdf1c505b01b41f75a1a60d0f" + }, + "kubernetesProvider": { + "url": "https://releases.hashicorp.com/terraform-provider-kubernetes/3.3.0/terraform-provider-kubernetes_3.3.0_linux_amd64.zip", + "sha256": "3152d82f36512eada40daa35939b2908f0d43f92e6df5d0ea3fb0be77c3b3af1" } }, "darwin_arm64": { @@ -75,6 +83,10 @@ "helmProvider": { "url": "https://releases.hashicorp.com/terraform-provider-helm/3.3.0/terraform-provider-helm_3.3.0_darwin_arm64.zip", "sha256": "a4e601eddf9781b5f8678ee9c2b6fb0791fbe6ab85a53707efdf80f714a3011c" + }, + "kubernetesProvider": { + "url": "https://releases.hashicorp.com/terraform-provider-kubernetes/3.3.0/terraform-provider-kubernetes_3.3.0_darwin_arm64.zip", + "sha256": "7967a3ab94d312d6857442fad0f9d187162c3d3f4f7e431505b4c6787b651f12" } }, "darwin_amd64": { @@ -97,6 +109,10 @@ "helmProvider": { "url": "https://releases.hashicorp.com/terraform-provider-helm/3.3.0/terraform-provider-helm_3.3.0_darwin_amd64.zip", "sha256": "2c057eafd1e4d8b50acdc676f9a3096e38fb7d30c3fab3d64af82fa04a2f767e" + }, + "kubernetesProvider": { + "url": "https://releases.hashicorp.com/terraform-provider-kubernetes/3.3.0/terraform-provider-kubernetes_3.3.0_darwin_amd64.zip", + "sha256": "caec2baae96383d57ade3c1d4200147e34bb9c2fe8cd17f857200a34c64f2b81" } }, "windows_amd64": { @@ -119,6 +135,10 @@ "helmProvider": { "url": "https://releases.hashicorp.com/terraform-provider-helm/3.3.0/terraform-provider-helm_3.3.0_windows_amd64.zip", "sha256": "eaa58edc8bb43aeb0fe6c0f99975cb24e2e9f5441e938a389fe848795a30b825" + }, + "kubernetesProvider": { + "url": "https://releases.hashicorp.com/terraform-provider-kubernetes/3.3.0/terraform-provider-kubernetes_3.3.0_windows_amd64.zip", + "sha256": "402af4bdcd166e13f60d2d2e50252420d2968658a649756908af6cefededd3bc" } } }, @@ -136,5 +156,6 @@ "kindNode": "kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5" }, "dockerProvider": "4.6.0", - "helmProvider": "3.3.0" + "helmProvider": "3.3.0", + "kubernetesProvider": "3.3.0" }