diff --git a/crates/nemoclaw-e2e/tests/kubernetes_hcl.rs b/crates/nemoclaw-e2e/tests/kubernetes_hcl.rs new file mode 100644 index 00000000000..44c91c731de --- /dev/null +++ b/crates/nemoclaw-e2e/tests/kubernetes_hcl.rs @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +//! Managed Kubernetes resources written in HCL, planned without a cluster. + +use nemoclaw_e2e::tofu::TofuWorkspace; +use serde_json::{Value, json}; +use std::{fs, path::PathBuf}; + +fn workspace(resources: &str) -> TofuWorkspace { + let tofu = PathBuf::from(std::env::var_os("NEMOCLAW_TEST_TOFU").unwrap()); + let provider = PathBuf::from(std::env::var_os("NEMOCLAW_TEST_PROVIDER").unwrap()); + assert!(tofu.is_absolute() && provider.is_absolute()); + let workspace = TofuWorkspace::new(tofu, provider); + fs::write( + workspace.path().join("main.tf"), + format!( + r#"terraform {{ + required_version = "= 1.12.6" + required_providers {{ + nemoclaw = {{ source = "registry.opentofu.org/nvidia/nemoclaw" }} + }} +}} +provider "nemoclaw" {{}} +{resources}"# + ), + ) + .unwrap(); + workspace +} + +fn storage(namespace: &str) -> String { + format!( + r#"resource "nemoclaw_kubernetes_storage" "platform" {{ + name = "nc-0123456789abcdef-gateway" + compute_driver = "openshift" + endpoint = "https://127.0.0.1:17671" + kubeconfig_env = "TEST_CLUSTER_KUBECONFIG" + context = "selected" + namespace = "{namespace}" + authentication_profile = "development" + environment = ["AWS_PROFILE"] +}} +"# + ) +} + +#[test] +#[ignore = "requires explicit NEMOCLAW_TEST_TOFU and NEMOCLAW_TEST_PROVIDER; no cluster"] +fn kubernetes_resources_plan_from_typed_settings_and_reject_invalid_ones() { + let valid = workspace(&storage("agents")); + let run = + |workspace: &TofuWorkspace, args: &[&str]| workspace.command().args(args).output().unwrap(); + let output = run(&valid, &["plan", "-input=false", "-out=platform.plan"]); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let plan: Value = + serde_json::from_slice(&run(&valid, &["show", "-json", "platform.plan"]).stdout).unwrap(); + let change = &plan["resource_changes"][0]["change"]; + assert_eq!(change["actions"], json!(["create"])); + assert_eq!(change["after"]["environment"], json!(["AWS_PROFILE"])); + assert_eq!(change["after"]["namespace"], "agents"); + // The provider generates the identity the author omits. + assert_eq!(change["after_unknown"]["owner"], true); + assert_eq!(change["after_unknown"]["generation"], true); + + let invalid = workspace(&storage("Not A Namespace")); + let output = run(&invalid, &["validate"]); + assert!(!output.status.success()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("namespace must be a Kubernetes namespace name"), + "{stderr}" + ); +} diff --git a/crates/nemoclaw-e2e/tests/main.rs b/crates/nemoclaw-e2e/tests/main.rs index d4fecd57077..8ac4531a4cb 100644 --- a/crates/nemoclaw-e2e/tests/main.rs +++ b/crates/nemoclaw-e2e/tests/main.rs @@ -29,6 +29,8 @@ mod health; mod hosted_parity; #[path = "inference_discovery.rs"] mod inference_discovery; +#[path = "kubernetes_hcl.rs"] +mod kubernetes_hcl; #[path = "managed.rs"] mod managed; #[path = "model_live.rs"] diff --git a/crates/nemoclaw-provider/src/kubernetes.rs b/crates/nemoclaw-provider/src/kubernetes.rs index ebf67645b15..0893f98bd32 100644 --- a/crates/nemoclaw-provider/src/kubernetes.rs +++ b/crates/nemoclaw-provider/src/kubernetes.rs @@ -2,8 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 //! Kubernetes preparation, authentication and gateway observation resources. //! -//! Each row carries the encoded specification. Operations connect with the -//! kubeconfig and context it names and keep their receipt in the directory +//! Each row carries the cluster target and identity as attributes. Operations +//! connect with the kubeconfig and context they name and keep their receipt in the directory //! the SDK passes through `NEMOCLAW_KUBERNETES_STATE`. use crate::{ @@ -39,34 +39,26 @@ fn bound_id(row: &Row) -> Option<&str> { } fn spec(kind: &str, row: &Row) -> Result { - let spec = Spec::decode(row.get("spec").ok_or(ObservationError::Incomplete)?) - .map_err(|_| ObservationError::Query)?; - if spec.kind != kind { - return Err(ObservationError::BindingMismatch); - } - Ok(spec) + Spec::from_row(kind, row).map_err(|error| match error { + Error::Observation(error) => error, + _ => ObservationError::Query, + }) } /// The provider row for an observation, or `None` when nothing exists. -fn row(source: &Row, response: Response) -> Result, ObservationError> { +fn row(spec: &Spec, response: Response) -> Result, ObservationError> { let Some(id) = response.id else { return Ok(None); }; - let spec = source - .get("spec") - .ok_or(ObservationError::Incomplete)? - .clone(); let running = response.running.ok_or(ObservationError::Incomplete)?; - let authentication = Spec::decode(&spec) - .map_err(|_| ObservationError::Query)? - .kind - == AUTH_KIND; - let mut result = Row::from([ - ("spec".into(), spec), - ("id".into(), id), - ("running".into(), running.to_string()), - ]); - if authentication { + let mut result = spec.row().map_err(|_| ObservationError::Query)?; + // Observations report every field; an omitted environment is empty. + result + .entry(nemoclaw_sdk::kubernetes::ENVIRONMENT_FIELD.into()) + .or_default(); + result.insert("id".into(), id); + result.insert("running".into(), running.to_string()); + if spec.kind == AUTH_KIND { let release_present = response .release_present .ok_or(ObservationError::Incomplete)?; @@ -121,14 +113,14 @@ fn failed_mutation( #[async_trait] impl Backend for KubernetesBackend { async fn plan(&self, kind: &str, desired: &Row, prior: Option<&Row>) -> Result<(), Error> { + let want = spec(kind, desired)?; if let Some(prior) = prior - && prior.get("spec") != desired.get("spec") + && spec(kind, prior)? != want { return Err(Error::Conflict( "managed Kubernetes target or identity changed; resources retained", )); } - spec(kind, desired)?; Ok(()) } @@ -145,7 +137,7 @@ impl Backend for KubernetesBackend { } else { operations.read(&spec, bound_id(prior)).await? }; - let row = row(prior, response)?; + let row = row(&spec, response)?; // Storage is retained: once recorded, it never reads as absent. if row.is_none() && kind == STORAGE_KIND && bound_id(prior).is_some() { return Err(ObservationError::Incomplete); @@ -163,7 +155,7 @@ impl Backend for KubernetesBackend { Err(error) => return Mutation::failed(error), }; match operations.ensure(&spec, bound_id(desired)).await { - Ok(response) => match row(desired, response) { + Ok(response) => match row(&spec, response) { Ok(Some(row)) => Mutation::complete(row), Ok(None) => Mutation::failed(ObservationError::Incomplete), Err(error) => Mutation::failed(error), @@ -175,7 +167,7 @@ impl Backend for KubernetesBackend { let observed = operations .read_for_removal(&spec, bound_id(desired)) .await - .and_then(|response| row(desired, response)); + .and_then(|response| row(&spec, response)); failed_mutation(error, observed) } } @@ -202,20 +194,30 @@ impl Backend for KubernetesBackend { /// Kubernetes platform resources and their planning rules. pub(crate) fn definitions() -> [crate::Definition; 3] { use crate::{Protection, carry_prior, rerun_when_stopped}; - let validate = nemoclaw_sdk::services::validate_resource_spec; + use nemoclaw_sdk::kubernetes::{ENVIRONMENT_FIELD, check_attribute}; + use nemoclaw_tofu::shape::Shape; + let typed = |kind| { + crate::services::schema_definition(kind) + .optional(&[ENVIRONMENT_FIELD]) + .structured( + "environment", + ENVIRONMENT_FIELD, + Shape::List(Box::new(Shape::String)), + ) + .validate_attribute(check_attribute) + .generated("owner", nemoclaw_backend::generate_owner) + .generated("generation", nemoclaw_backend::generate_generation) + }; [ - crate::services::schema_definition(STORAGE_KIND) - .validate_spec(validate) + typed(STORAGE_KIND) .computed("running", rerun_when_stopped) .protect(Protection::Always) .refuse_replacement() .keep_running_during_destroy(), - crate::services::schema_definition(GATEWAY_KIND) - .validate_spec(validate) + typed(GATEWAY_KIND) .computed("running", rerun_when_stopped) .refuse_replacement(), - crate::services::schema_definition(AUTH_KIND) - .validate_spec(validate) + typed(AUTH_KIND) .computed("running", rerun_when_stopped) .computed("release_present", carry_prior) .computed("gateway_values", prepared_gateway_values), @@ -249,6 +251,7 @@ mod tests { "layout": 1, "kind": kind, "name": "nc-0123456789abcdef-gateway", "owner": "11111111-1111-4111-8111-111111111111", "generation": "0123456789abcdef0123456789abcdef", "settings": { + "runtime": {"provider": "kubernetes"}, "endpoint": "https://127.0.0.1:17671", "kubernetes": { "kubeconfig": {"env": "TEST_CLUSTER_CONFIG"}, "context": "selected", "namespace": "agents", @@ -257,7 +260,25 @@ mod tests { } })) .unwrap(); - Row::from([("spec".into(), spec.encode().unwrap())]) + spec.row().unwrap() + } + + fn fixture(kind: &str) -> Spec { + Spec::from_row(kind, &spec_row(kind)).unwrap() + } + + /// Recorded state for a bound `kind` resource. + fn bound(kind: &str, observed: &[(&str, &str)]) -> crate::State { + use tf_provider::value::Value; + spec_row(kind) + .into_iter() + .map(|(name, value)| (name, Value::Value(value))) + .chain( + observed + .iter() + .map(|(name, value)| ((*name).into(), Value::Value((*value).into()))), + ) + .collect() } #[test] @@ -272,7 +293,7 @@ mod tests { #[test] fn an_observation_without_running_is_incomplete() { - let source = spec_row(GATEWAY_KIND); + let source = fixture(GATEWAY_KIND); let missing = Response { id: Some("uid-1".into()), running: None, @@ -283,9 +304,30 @@ mod tests { assert_eq!(row(&source, absent), Ok(None)); } + #[test] + fn observations_report_every_attribute_including_an_omitted_environment() { + for kind in [STORAGE_KIND, AUTH_KIND, GATEWAY_KIND] { + let observed = row( + &fixture(kind), + Response { + id: Some("uid-1".into()), + running: Some(true), + release_present: Some(true), + gateway_values: Some("{}".into()), + }, + ) + .unwrap() + .unwrap(); + let definition = crate::resource_definition(kind).unwrap(); + for attribute in definition.attributes() { + assert!(observed.contains_key(attribute), "{kind}.{attribute}"); + } + } + } + #[test] fn authentication_requires_an_independent_release_observation() { - let source = spec_row(AUTH_KIND); + let source = fixture(AUTH_KIND); let missing = Response { id: Some("issuer-uid".into()), running: Some(true), @@ -323,24 +365,14 @@ mod tests { fn authentication_planning_preserves_only_refreshed_release_observation() { let definition = crate::resource_definition(AUTH_KIND).unwrap(); for present in ["false", "true"] { - let prior = crate::State::from([ - ( - "id".into(), - tf_provider::value::Value::Value("issuer-uid".into()), - ), - ( - "spec".into(), - tf_provider::value::Value::Value(spec_row(AUTH_KIND)["spec"].clone()), - ), - ( - "running".into(), - tf_provider::value::Value::Value("true".into()), - ), - ( - "release_present".into(), - tf_provider::value::Value::Value(present.into()), - ), - ]); + let prior = bound( + AUTH_KIND, + &[ + ("id", "issuer-uid"), + ("running", "true"), + ("release_present", present), + ], + ); let mut proposed = prior.clone(); proposed.insert("release_present".into(), tf_provider::value::Value::Unknown); let (planned, replacements) = crate::plan_update(&definition, &prior, proposed); @@ -354,16 +386,15 @@ mod tests { use tf_provider::value::Value; let definition = crate::resource_definition(AUTH_KIND).unwrap(); for running in ["true", "false"] { - let prior = crate::State::from([ - ("id".into(), Value::Value("issuer-uid".into())), - ( - "spec".into(), - Value::Value(spec_row(AUTH_KIND)["spec"].clone()), - ), - ("running".into(), Value::Value(running.into())), - ("release_present".into(), Value::Value("false".into())), - ("gateway_values".into(), Value::Value("{}".into())), - ]); + let prior = bound( + AUTH_KIND, + &[ + ("id", "issuer-uid"), + ("running", running), + ("release_present", "false"), + ("gateway_values", "{}"), + ], + ); let mut proposed = prior.clone(); if running == "true" { proposed.insert("gateway_values".into(), Value::Unknown); @@ -383,7 +414,7 @@ mod tests { #[test] fn an_incomplete_apply_retains_a_verified_partial_binding_and_its_error() { - let source = spec_row(AUTH_KIND); + let source = fixture(AUTH_KIND); let observed = row( &source, Response { @@ -400,7 +431,8 @@ mod tests { .expect("retain the verified identity for teardown"); assert_eq!(state["id"], "recorded-issuer-uid"); assert_eq!(state["running"], "false"); - assert_eq!(state["spec"], source["spec"]); + assert_eq!(state["namespace"], "agents"); + assert_eq!(state["kubeconfig_env"], "TEST_CLUSTER_CONFIG"); } #[test] @@ -422,9 +454,7 @@ mod tests { async fn a_changed_specification_is_never_planned_as_an_update() { let prior = spec_row(GATEWAY_KIND); let mut desired = spec_row(GATEWAY_KIND); - let mut spec = Spec::decode(&desired["spec"]).unwrap(); - spec.settings.kubernetes.as_mut().unwrap().namespace = "elsewhere".into(); - desired.insert("spec".into(), spec.encode().unwrap()); + desired.insert("namespace".into(), "elsewhere".into()); assert!(matches!( KubernetesBackend::new() .plan(GATEWAY_KIND, &desired, Some(&prior)) @@ -438,10 +468,10 @@ mod tests { } #[tokio::test] - async fn a_row_for_the_other_kind_is_refused() { + async fn a_row_for_another_resource_type_is_refused() { let storage = spec_row(STORAGE_KIND); assert_eq!( - spec(GATEWAY_KIND, &storage).err(), + spec("managed_gateway", &storage).err(), Some(ObservationError::BindingMismatch) ); } diff --git a/crates/nemoclaw-provider/src/provider.rs b/crates/nemoclaw-provider/src/provider.rs index b76a5e58d41..a32a7cd7d08 100644 --- a/crates/nemoclaw-provider/src/provider.rs +++ b/crates/nemoclaw-provider/src/provider.rs @@ -210,9 +210,16 @@ impl Provider for NemoClawProvider { .into_iter() .map(|definition| { let name = definition.kind.into(); + let structured = !definition.structured.is_empty(); let mut resource = ResourceAdapter::new(definition, self.backend.clone()); resource.destroying = self.destroying.clone(); - (name, Box::new(resource) as Box) + // Typed list and block inputs need the structured adapter. + let resource: Box = if structured { + Box::new(nemoclaw_tofu::StructuredAdapter(resource)) + } else { + Box::new(resource) + }; + (name, resource) }) .collect(), ) diff --git a/crates/nemoclaw-provider/tests/refresh.rs b/crates/nemoclaw-provider/tests/refresh.rs index 0aae8dae1d2..171d8511d2b 100644 --- a/crates/nemoclaw-provider/tests/refresh.rs +++ b/crates/nemoclaw-provider/tests/refresh.rs @@ -79,22 +79,23 @@ async fn teardown_does_not_resume_incomplete_retained_kubernetes_storage() { let generations = ["kubernetes_storage", "kubernetes_gateway"] .map(|kind| (kind.into(), "a".repeat(32))) .into(); - let spec = compile::runtime_targets(&document, &generations) + let mut row = compile::runtime_targets(&document, &generations) .unwrap() .into_iter() .find(|target| target.kind == "kubernetes_storage") .unwrap() - .values["spec"] - .clone(); + .values; + let fields: Vec<_> = nemoclaw_sdk::kubernetes::ATTRIBUTES + .into_iter() + .chain(["running"]) + .collect(); let resource = ResourceAdapter::new( - support::definition("kubernetes_storage", &["spec", "running"], &["running"]), + support::definition("kubernetes_storage", &fields, &["running"]), Arc::new(Fixture(Ok(None))), ); - let prior = state(Row::from([ - ("id".into(), "retained-storage".into()), - ("spec".into(), spec), - ("running".into(), "false".into()), - ])); + row.insert("id".into(), "retained-storage".into()); + row.insert("running".into(), "false".into()); + let prior = state(row); for destroying in [false, true] { resource .destroying diff --git a/crates/nemoclaw-provider/tests/schema.rs b/crates/nemoclaw-provider/tests/schema.rs index 0fb6eb64f0b..475b0967b83 100644 --- a/crates/nemoclaw-provider/tests/schema.rs +++ b/crates/nemoclaw-provider/tests/schema.rs @@ -281,3 +281,51 @@ fn service_observations_take_typed_inputs_instead_of_compiled_specs() { } assert!(diagnostics.errors.is_empty()); } + +#[test] +fn kubernetes_resources_take_typed_settings() { + use tf_provider::schema::{ + AttributeConstraint::{OptionalComputed, Required}, + AttributeType, + }; + let provider = NemoClawProvider::default(); + let mut diagnostics = Diagnostics::default(); + let resources = provider.get_resources(&mut diagnostics).unwrap(); + for kind in [ + "kubernetes_storage", + "kubernetes_auth", + "kubernetes_gateway", + ] { + let schema = resources[kind].schema(&mut diagnostics).unwrap(); + let attributes = &schema.block.attributes; + assert!(!attributes.contains_key("spec"), "{kind}"); + for attribute in [ + "name", + "compute_driver", + "endpoint", + "kubeconfig_env", + "context", + "namespace", + "authentication_profile", + ] { + assert!( + matches!(attributes[attribute].constraint, Required), + "{kind}.{attribute}" + ); + } + for attribute in ["owner", "generation"] { + assert!( + matches!(attributes[attribute].constraint, OptionalComputed), + "{kind}.{attribute}" + ); + } + assert!( + matches!( + &attributes["environment"].attr_type, + AttributeType::List(item) if matches!(**item, AttributeType::String) + ), + "{kind}.environment" + ); + } + assert!(diagnostics.errors.is_empty()); +} diff --git a/crates/nemoclaw-sdk/src/compile_runtime.rs b/crates/nemoclaw-sdk/src/compile_runtime.rs index 8f50149e195..c1410abac03 100644 --- a/crates/nemoclaw-sdk/src/compile_runtime.rs +++ b/crates/nemoclaw-sdk/src/compile_runtime.rs @@ -61,7 +61,7 @@ fn runtime_targets_with_plans( Ok(Target { kind: kind.into(), address: format!("nemoclaw_{kind}.runtime"), - values: Row::from([("spec".into(), spec.encode()?)]), + values: spec.row()?, }) }) .collect::, Error>>()?; @@ -147,8 +147,16 @@ pub(crate) fn runtime_graph( .iter() .filter(|target| target.kind != "helm_release") { - let mut attributes = - json!({"spec": target.values["spec"].replace("${", "$${").replace("%{", "%%{")}); + // The environment list travels as JSON in the target row. + let mut attributes = json!({}); + for (name, value) in &target.values { + if name == crate::kubernetes::ENVIRONMENT_FIELD { + attributes["environment"] = serde_json::from_str(value) + .map_err(|_| Error::State("invalid Kubernetes environment"))?; + } else { + attributes[name] = json!(value.replace("${", "$${").replace("%{", "%%{")); + } + } attributes["lifecycle"] = json!({"postcondition": [{ "condition": "${self.running == \"true\"}", "error_message": "Managed Kubernetes reconciliation is incomplete; retain the same configuration and state directory, resolve prerequisites, then run apply again." @@ -167,7 +175,7 @@ pub(crate) fn runtime_graph( .iter() .find(|target| target.kind == crate::kubernetes::GATEWAY_KIND) .expect("Kubernetes gateway target"); - let spec = crate::kubernetes::Spec::decode(&gateway.values["spec"])?; + let spec = crate::kubernetes::Spec::from_row(&gateway.kind, &gateway.values)?; crate::kubernetes::gateway::configure(&mut graph, &spec)?; return Ok((graph, targets)); } diff --git a/crates/nemoclaw-sdk/src/deployment/export.rs b/crates/nemoclaw-sdk/src/deployment/export.rs index cef98069d7c..c93b37ec110 100644 --- a/crates/nemoclaw-sdk/src/deployment/export.rs +++ b/crates/nemoclaw-sdk/src/deployment/export.rs @@ -75,6 +75,8 @@ impl Deployment { ))?; if !plan::disposable(&target.address) && (target.values.contains_key("spec") + // Gateways, their storage, and Kubernetes resources are typed. + || target.values.contains_key("compute_driver") || crate::services::resource_behavior(&target.kind).retained_storage) && binding.differs(&target.values) { diff --git a/crates/nemoclaw-sdk/src/deployment/plan.rs b/crates/nemoclaw-sdk/src/deployment/plan.rs index 78337086f21..ccb3bd9c626 100644 --- a/crates/nemoclaw-sdk/src/deployment/plan.rs +++ b/crates/nemoclaw-sdk/src/deployment/plan.rs @@ -71,6 +71,9 @@ fn identity(change: &ResourceChange, expected: &Row, binding: &StateBinding) -> "endpoint", "image", "network_cidr", + "kubeconfig_env", + "context", + "authentication_profile", ] { if let Some(value) = expected.get(key) && change.change.before[key] != *value diff --git a/crates/nemoclaw-sdk/src/deployment/runtime.rs b/crates/nemoclaw-sdk/src/deployment/runtime.rs index 1feeee17ab2..913d90ead3e 100644 --- a/crates/nemoclaw-sdk/src/deployment/runtime.rs +++ b/crates/nemoclaw-sdk/src/deployment/runtime.rs @@ -52,7 +52,7 @@ fn bound_spec(kind: &str, want: &Spec, binding: Option<&StateBinding>) -> Result let Some(binding) = binding else { return Ok(want.clone()); }; - let mut bound = binding.gateway_values(); + let mut bound = binding.typed_values(); bound.insert("spec".into(), binding.spec.clone()); let old = Spec::from_values(kind, &bound) .map_err(|_| Error::Conflict("bound runtime specification is incomplete"))?; diff --git a/crates/nemoclaw-sdk/src/deployment/runtime/teardown.rs b/crates/nemoclaw-sdk/src/deployment/runtime/teardown.rs index 9c3d8d03f31..16f4e0d96e7 100644 --- a/crates/nemoclaw-sdk/src/deployment/runtime/teardown.rs +++ b/crates/nemoclaw-sdk/src/deployment/runtime/teardown.rs @@ -285,7 +285,7 @@ fn bind_teardown_processes( crate::kubernetes::GATEWAY_KIND | crate::kubernetes::AUTH_KIND ) { if let Some(binding) = bindings.get(&target.address) - && binding.spec != target.values["spec"] + && binding.differs(&target.values) { return Err(Error::Conflict( "Kubernetes gateway binding differs from retained intent", diff --git a/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs b/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs index 6e2b7a98fcb..d108a38c32b 100644 --- a/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs +++ b/crates/nemoclaw-sdk/src/deployment/runtime/tests.rs @@ -39,7 +39,7 @@ fn kubernetes_gateway_requires_storage_and_fresh_readiness_without_replacement() missing.remove(KUBERNETES_STORAGE); assert!(runtime_bindings(&targets, &missing).is_err()); let mut drift = bindings.clone(); - drift.get_mut(KUBERNETES_STORAGE).unwrap().spec = "changed".into(); + drift.get_mut(KUBERNETES_STORAGE).unwrap().namespace = "elsewhere".into(); assert!(runtime_bindings(&targets, &drift).is_err()); for change in &mut plan.resource_changes { if change.address == "nemoclaw_kubernetes_gateway.runtime" { @@ -119,7 +119,7 @@ fn bound(id: impl Into, target: &Target) -> StateBinding { /// Planned prior attributes of a bound resource. fn before(binding: &StateBinding) -> Value { - let mut before = json!(binding.gateway_values()); + let mut before = json!(binding.typed_values()); before["id"] = json!(binding.id); if !binding.spec.is_empty() { before["spec"] = json!(binding.spec); diff --git a/crates/nemoclaw-sdk/src/kubernetes/mod.rs b/crates/nemoclaw-sdk/src/kubernetes/mod.rs index d5384d7596c..ce13b089dd5 100644 --- a/crates/nemoclaw-sdk/src/kubernetes/mod.rs +++ b/crates/nemoclaw-sdk/src/kubernetes/mod.rs @@ -86,6 +86,158 @@ impl Spec { serde_json::to_string(self) .map_err(|_| Error::State("cannot encode Kubernetes specification")) } + /// Resource attributes naming this specification's resource; the + /// `environment` list is carried as JSON in `environment_json`. + /// + /// # Errors + /// Returns an error if the specification is invalid. + pub fn row(&self) -> Result { + self.validate()?; + let target = self + .settings + .kubernetes + .as_ref() + .ok_or(Error::State("missing Kubernetes settings"))?; + let driver = serde_json::to_value(self.settings.runtime.provider) + .ok() + .and_then(|value| value.as_str().map(str::to_owned)) + .ok_or(Error::State("cannot encode Kubernetes compute driver"))?; + let profile = serde_json::to_value(target.authentication.profile) + .ok() + .and_then(|value| value.as_str().map(str::to_owned)) + .ok_or(Error::State("cannot encode Kubernetes authentication"))?; + let mut row: crate::backend::Row = ATTRIBUTES + .into_iter() + .zip([ + self.name.clone(), + self.owner.clone(), + self.generation.clone(), + driver, + self.settings.endpoint.clone(), + target.kubeconfig.env.clone(), + target.context.clone(), + target.namespace.clone(), + profile, + ]) + .map(|(attribute, value)| (attribute.to_owned(), value)) + .collect(); + if !target.environment.is_empty() { + row.insert( + ENVIRONMENT_FIELD.into(), + serde_json::to_string(&target.environment) + .map_err(|_| Error::State("cannot encode Kubernetes environment"))?, + ); + } + Ok(row) + } + /// The `kind` resource's specification named by its attributes. + /// + /// # Errors + /// Returns an incomplete observation for missing attributes and a conflict + /// for invalid ones. + pub fn from_row(kind: &str, row: &crate::backend::Row) -> Result { + if !matches!(kind, STORAGE_KIND | AUTH_KIND | GATEWAY_KIND) { + return Err(ObservationError::BindingMismatch.into()); + } + let get = |attribute: &str| { + row.get(attribute) + .filter(|value| !value.is_empty()) + .cloned() + .ok_or(ObservationError::Incomplete) + }; + let invalid = || Error::Conflict("invalid managed Kubernetes attribute"); + let parse = |attribute: &str| -> Result { + Ok(serde_json::Value::String(get(attribute)?)) + }; + let provider: crate::config::ComputeDriver = + serde_json::from_value(parse("compute_driver")?).map_err(|_| invalid())?; + if !provider.is_kubernetes() { + return Err(invalid()); + } + let environment = match row.get(ENVIRONMENT_FIELD).filter(|value| !value.is_empty()) { + Some(encoded) => serde_json::from_str(encoded).map_err(|_| invalid())?, + None => Vec::new(), + }; + let spec = Self { + layout: 1, + kind: kind.into(), + name: get("name")?, + owner: get("owner")?, + generation: get("generation")?, + settings: ManagedGateway { + runtime: crate::config::Runtime { provider }, + endpoint: get("endpoint")?, + kubernetes: Some(crate::config::ManagedKubernetes { + kubeconfig: crate::config::Credential { + env: get("kubeconfig_env")?, + }, + context: get("context")?, + namespace: get("namespace")?, + authentication: crate::config::KubernetesAuthentication { + profile: serde_json::from_value(parse("authentication_profile")?) + .map_err(|_| invalid())?, + }, + environment, + }), + ..Default::default() + }, + }; + spec.validate()?; + Ok(spec) + } +} + +/// String attributes of the managed Kubernetes resources. +pub const ATTRIBUTES: [&str; 9] = [ + "name", + "owner", + "generation", + "compute_driver", + "endpoint", + "kubeconfig_env", + "context", + "namespace", + "authentication_profile", +]; +/// Row field carrying the `environment` list as JSON. +pub const ENVIRONMENT_FIELD: &str = "environment_json"; + +/// Check one attribute without the others, explaining a rejected value +/// without echoing it. +pub fn check_attribute(attribute: &str, value: &str) -> Result<(), &'static str> { + let (pattern, requirement) = match attribute { + "name" => ( + r"^nc-[a-f0-9]{16}-gateway$", + "must be nc-, 16 lowercase hexadecimal characters, and -gateway", + ), + "owner" => (r"^[a-f0-9-]{36}$", "must be a lowercase UUID"), + "generation" => ( + r"^[a-f0-9]{32}$", + "must be 32 lowercase hexadecimal characters", + ), + "compute_driver" => ( + r"^(kubernetes|openshift)$", + "must be kubernetes or openshift", + ), + "authentication_profile" => (r"^development$", "must be development"), + "namespace" => ( + r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$", + "must be a Kubernetes namespace name", + ), + "kubeconfig_env" => ( + r"^[A-Z_][A-Z0-9_]*$", + "must be an uppercase environment variable name", + ), + _ => return Ok(()), + }; + if regex::Regex::new(pattern) + .expect("constant pattern") + .is_match(value) + { + Ok(()) + } else { + Err(requirement) + } } /// The kubeconfig file and context a deployment names. diff --git a/crates/nemoclaw-sdk/src/services/registry.rs b/crates/nemoclaw-sdk/src/services/registry.rs index 8e8dafd70f4..4a103008d1b 100644 --- a/crates/nemoclaw-sdk/src/services/registry.rs +++ b/crates/nemoclaw-sdk/src/services/registry.rs @@ -55,21 +55,51 @@ pub struct ResourceSchema { pub mutable: &'static [&'static str], } +/// Managed Kubernetes resource fields: the cluster target and identity, the +/// environment list as JSON, and the observed reconciliation. +const KUBERNETES_FIELDS: [&str; 11] = [ + "name", + "owner", + "generation", + "compute_driver", + "endpoint", + "kubeconfig_env", + "context", + "namespace", + "authentication_profile", + crate::kubernetes::ENVIRONMENT_FIELD, + "running", +]; +const KUBERNETES_AUTH_FIELDS: [&str; 13] = [ + "name", + "owner", + "generation", + "compute_driver", + "endpoint", + "kubeconfig_env", + "context", + "namespace", + "authentication_profile", + crate::kubernetes::ENVIRONMENT_FIELD, + "running", + "release_present", + "gateway_values", +]; pub fn resource_schemas() -> Vec { vec![ ResourceSchema { kind: crate::kubernetes::STORAGE_KIND, - fields: &["spec", "running"], + fields: &KUBERNETES_FIELDS, mutable: &["running"], }, ResourceSchema { kind: crate::kubernetes::GATEWAY_KIND, - fields: &["spec", "running"], + fields: &KUBERNETES_FIELDS, mutable: &["running"], }, ResourceSchema { kind: crate::kubernetes::AUTH_KIND, - fields: &["spec", "running", "release_present", "gateway_values"], + fields: &KUBERNETES_AUTH_FIELDS, mutable: &["running", "release_present", "gateway_values"], }, ResourceSchema { diff --git a/crates/nemoclaw-sdk/src/services/validation.rs b/crates/nemoclaw-sdk/src/services/validation.rs index d41fa41d0a5..e849eb8e893 100644 --- a/crates/nemoclaw-sdk/src/services/validation.rs +++ b/crates/nemoclaw-sdk/src/services/validation.rs @@ -7,20 +7,6 @@ use crate::{Error, managed::Spec}; /// Validate a compiled resource without opening connections or reading secrets. /// Parse errors deliberately omit serialized source values. pub fn validate_resource_spec(kind: &str, encoded: &str) -> Result<(), Error> { - if matches!( - kind, - crate::kubernetes::STORAGE_KIND - | crate::kubernetes::GATEWAY_KIND - | crate::kubernetes::AUTH_KIND - ) { - let spec = crate::kubernetes::Spec::decode(encoded)?; - if spec.kind != kind { - return Err(Error::Conflict( - "Kubernetes specification does not match the resource kind", - )); - } - return spec.validate(); - } if !matches!(kind, vllm::SERVICE_KIND | ollama::SERVICE_KIND) { return Ok(()); } diff --git a/crates/nemoclaw-sdk/src/state/mod.rs b/crates/nemoclaw-sdk/src/state/mod.rs index a1aee691e36..06fde633995 100644 --- a/crates/nemoclaw-sdk/src/state/mod.rs +++ b/crates/nemoclaw-sdk/src/state/mod.rs @@ -319,6 +319,26 @@ impl Record { fn nullable<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { Ok(Option::::deserialize(deserializer)?.unwrap_or_default()) } +fn nullable_list<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + Ok(Option::>::deserialize(deserializer)?.unwrap_or_default()) +} +/// String attributes typed resources record in state. +const TYPED_ATTRIBUTES: [&str; 12] = [ + "name", + "owner", + "generation", + "compute_driver", + "engine", + "endpoint", + "image", + "network_cidr", + "kubeconfig_env", + "context", + "namespace", + "authentication_profile", +]; #[derive(Clone, Debug, Default, Deserialize)] pub(crate) struct StateBinding { pub id: String, @@ -346,14 +366,24 @@ pub(crate) struct StateBinding { pub image: String, #[serde(default, deserialize_with = "nullable")] pub network_cidr: String, + #[serde(default, deserialize_with = "nullable")] + pub kubeconfig_env: String, + #[serde(default, deserialize_with = "nullable")] + pub context: String, + #[serde(default, deserialize_with = "nullable")] + pub authentication_profile: String, + #[serde(default, deserialize_with = "nullable_list")] + pub environment: Vec, #[serde(skip)] pub deposed: BTreeMap, } impl StateBinding { - /// Bound gateway or storage attributes; empty values were not set. - pub(crate) fn gateway_values(&self) -> crate::backend::Row { - crate::managed::GATEWAY_ATTRIBUTES + /// Bound typed attributes of gateways, their storage, and managed + /// Kubernetes resources, as their compiled rows carry them; empty values + /// were not set. + pub(crate) fn typed_values(&self) -> crate::backend::Row { + let mut values: crate::backend::Row = TYPED_ATTRIBUTES .into_iter() .zip([ &self.name, @@ -364,10 +394,21 @@ impl StateBinding { &self.endpoint, &self.image, &self.network_cidr, + &self.kubeconfig_env, + &self.context, + &self.namespace, + &self.authentication_profile, ]) .filter(|(_, value)| !value.is_empty()) .map(|(attribute, value)| (attribute.to_owned(), value.clone())) - .collect() + .collect(); + if !self.environment.is_empty() { + values.insert( + crate::kubernetes::ENVIRONMENT_FIELD.into(), + serde_json::to_string(&self.environment).unwrap_or_default(), + ); + } + values } /// Whether bound configuration differs from compiled values. An encoded /// specification compares whole; typed resources compare their attributes. @@ -375,14 +416,15 @@ impl StateBinding { match values.get("spec") { Some(spec) => *spec != self.spec, None => { - let bound = self.gateway_values(); - crate::managed::GATEWAY_ATTRIBUTES - .into_iter() - .any(|attribute| { - values - .get(attribute) - .is_some_and(|want| bound.get(attribute) != Some(want)) - }) + let bound = self.typed_values(); + // An omitted environment list is still part of a Kubernetes target. + let environment = crate::kubernetes::ENVIRONMENT_FIELD; + TYPED_ATTRIBUTES.into_iter().any(|attribute| { + values + .get(attribute) + .is_some_and(|want| bound.get(attribute) != Some(want)) + }) || (values.contains_key("kubeconfig_env") + && values.get(environment) != bound.get(environment)) } } } @@ -612,6 +654,10 @@ fn parse_bindings(bytes: &[u8]) -> Result, Error> binding.endpoint = attributes.endpoint; binding.image = attributes.image; binding.network_cidr = attributes.network_cidr; + binding.kubeconfig_env = attributes.kubeconfig_env; + binding.context = attributes.context; + binding.authentication_profile = attributes.authentication_profile; + binding.environment = attributes.environment; } } } diff --git a/crates/nemoclaw-sdk/src/state/tests.rs b/crates/nemoclaw-sdk/src/state/tests.rs index 9ca1ba897c0..06dbf83b765 100644 --- a/crates/nemoclaw-sdk/src/state/tests.rs +++ b/crates/nemoclaw-sdk/src/state/tests.rs @@ -792,7 +792,7 @@ fn gateway_storage_bindings_record_their_typed_settings() { .filter(|(name, _)| crate::managed::GATEWAY_ATTRIBUTES.contains(&name.as_str())) .filter_map(|(name, value)| Some((name.clone(), value.as_str()?.to_owned()))) .collect(); - assert_eq!(bindings[address].gateway_values(), compiled); + assert_eq!(bindings[address].typed_values(), compiled); assert!(!bindings[address].differs(&compiled)); let mut changed = compiled.clone(); changed.insert("image".into(), "changed".into()); diff --git a/crates/nemoclaw-sdk/tests/config_openshift.rs b/crates/nemoclaw-sdk/tests/config_openshift.rs index 610a75418fe..7ae8857feec 100644 --- a/crates/nemoclaw-sdk/tests/config_openshift.rs +++ b/crates/nemoclaw-sdk/tests/config_openshift.rs @@ -124,8 +124,7 @@ fn openshift_compiles_platform_identity_and_wire_driver_without_docker() { .iter() .filter(|target| target.kind != "helm_release") { - let spec: Value = serde_json::from_str(&target.values["spec"]).unwrap(); - assert_eq!(spec["settings"]["runtime"]["provider"], "openshift"); + assert_eq!(target.values["compute_driver"], "openshift"); } let platform = compile_runtime(&document, &generations, "0.1.0").unwrap(); // The platform stage has no gateway, so it omits the gateway providers. diff --git a/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs b/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs index f28c36ed18d..1a6cd9fe79b 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_managed_compile.rs @@ -191,17 +191,23 @@ fn managed_kubernetes_stages_owned_platform_before_authenticated_agents() { "${self.running == \"true\"}" ); } - let spec: serde_json::Value = serde_json::from_str( - platform["resource"]["nemoclaw_kubernetes_gateway"]["runtime"]["spec"] - .as_str() - .unwrap(), - ) - .unwrap(); - assert_eq!( - spec["settings"]["kubernetes"]["kubeconfig"]["env"], - "TEST_KUBECONFIG" - ); - assert_eq!(spec["generation"], "a".repeat(32)); + // Every platform resource takes the cluster target as typed attributes. + for kind in [ + "nemoclaw_kubernetes_storage", + "nemoclaw_kubernetes_auth", + "nemoclaw_kubernetes_gateway", + ] { + let resource = &platform["resource"][kind]["runtime"]; + assert!(resource.get("spec").is_none(), "{kind}"); + assert_eq!(resource["kubeconfig_env"], "TEST_KUBECONFIG", "{kind}"); + assert_eq!(resource["context"], "test-cluster", "{kind}"); + assert_eq!(resource["namespace"], "test-agents", "{kind}"); + assert_eq!(resource["compute_driver"], "kubernetes", "{kind}"); + assert_eq!(resource["endpoint"], "https://127.0.0.1:17671", "{kind}"); + assert_eq!(resource["authentication_profile"], "development", "{kind}"); + assert_eq!(resource["generation"], "a".repeat(32), "{kind}"); + assert!(resource.get("environment").is_none(), "{kind}"); + } let agents = compile(&document, &generations, "0.1.0").unwrap(); // The managed gateway's credentials reach both gateway providers. for provider in ["openshell", "fabric"] { @@ -258,3 +264,63 @@ fn managed_kubernetes_discovery_never_uses_a_local_container_engine() { let platform = compile_runtime(&document, &generations, "0.1.0").unwrap(); assert!(platform.get("output").is_none()); } + +#[test] +fn kubernetes_attributes_reproduce_each_resource_specification() { + use nemoclaw_sdk::kubernetes::{AUTH_KIND, GATEWAY_KIND, STORAGE_KIND, Spec}; + let mut value = serde_json::to_value(document()).unwrap(); + value["spec"]["gateway"]["kubernetes"]["environment"] = json!(["AWS_PROFILE"]); + value["spec"]["gateway"]["runtime"]["provider"] = json!("openshift"); + let generations = [ + "workspace", + "provider", + "sandbox", + "kubernetes_gateway", + "kubernetes_storage", + ] + .map(|kind| (kind.into(), "a".repeat(32))) + .into(); + for document in [ + document(), + Document::parse(serde_json::to_vec(&value).unwrap().as_slice()).unwrap(), + ] { + for target in runtime_targets(&document, &generations) + .unwrap() + .into_iter() + .filter(|target| target.kind.starts_with("kubernetes_")) + { + let spec = Spec::from_row(&target.kind, &target.values).unwrap(); + assert_eq!(spec.row().unwrap(), target.values); + assert_eq!(spec.kind, target.kind); + let kubernetes = spec.settings.kubernetes.as_ref().unwrap(); + assert_eq!(kubernetes.context, "test-cluster"); + assert_eq!( + document + .spec + .gateway + .as_managed() + .unwrap() + .kubernetes + .as_ref(), + Some(kubernetes) + ); + assert!(matches!( + target.kind.as_str(), + STORAGE_KIND | AUTH_KIND | GATEWAY_KIND + )); + for (attribute, invalid) in [ + ("compute_driver", "docker"), + ("namespace", "Not A Namespace"), + ("kubeconfig_env", "lowercase"), + ("endpoint", "http://127.0.0.1:17671"), + ("authentication_profile", "production"), + ("environment_json", "[\"KUBECONFIG\"]"), + ] { + let mut row = target.values.clone(); + row.insert(attribute.into(), invalid.into()); + assert!(Spec::from_row(&target.kind, &row).is_err(), "{attribute}"); + } + assert!(Spec::from_row("managed_gateway", &target.values).is_err()); + } + } +} diff --git a/docs/limits.md b/docs/limits.md index 8bc83247f13..b40d05d3869 100644 --- a/docs/limits.md +++ b/docs/limits.md @@ -91,7 +91,6 @@ Other pages state a limit where it affects a procedure and link the same issue. | A compatibility policy for the SDK, provider, schema and state across releases | [#12645](https://github.com/NVIDIA/NemoClaw/issues/12645) | | A hosted Rust API reference | [#12645](https://github.com/NVIDIA/NemoClaw/issues/12645) | | Supported HCL examples, import, adoption and remote-state backends | [#12645](https://github.com/NVIDIA/NemoClaw/issues/12645) | -| Typed HCL schemas for Kubernetes resources, which take one SDK-compiled `spec` string | [#12782](https://github.com/NVIDIA/NemoClaw/issues/12782) | ## Documentation Site diff --git a/docs/provider.md b/docs/provider.md index 642dd87982d..7c420dbba2e 100644 --- a/docs/provider.md +++ b/docs/provider.md @@ -581,6 +581,21 @@ The runtime graph for a managed Kubernetes or OpenShift gateway declares four re 3. `helm_release.gateway` installs the pinned OpenShell chart into the prepared namespace without creating the namespace or taking ownership of existing objects. 4. `nemoclaw_kubernetes_gateway.runtime` records the chart's StatefulSet identity and reports readiness in `running`. +The three NemoClaw resources take the same cluster target and identity: + +- `name`: `nc-`, 16 lowercase hexadecimal characters, and `-gateway`. +- `compute_driver`: `kubernetes` or `openshift`. +- `endpoint`: the gateway's `https://127.0.0.1:PORT` loopback endpoint. +- `kubeconfig_env`: the environment variable whose value is the kubeconfig file path. +- `context` and `namespace`: the exact kubeconfig context and the namespace for the gateway. +- `authentication_profile`: `development`. +- Optional `environment`: the names of the environment variables the kubeconfig's exec credential plugin needs. +- Optional `owner` and `generation`, generated on create when omitted. + +The three resources share one private receipt, keyed by `owner` and `name`, so give `nemoclaw_kubernetes_auth` and `nemoclaw_kubernetes_gateway` the storage's `owner`, for example `owner = nemoclaw_kubernetes_storage.platform.owner`. +Generated graphs also give the authentication resource the gateway's `generation`. +Changing any of these settings after creation fails planning and leaves the resources unchanged. + 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. @@ -603,6 +618,5 @@ The Docker and Helm providers have fixed release versions and checksum-pinned na The providers are not published yet ([#12638](https://github.com/NVIDIA/NemoClaw/issues/12638)). Supported HCL examples, import, adoption, remote-state backends and compatibility across releases are tracked in [#12645](https://github.com/NVIDIA/NemoClaw/issues/12645). -Kubernetes resources take one SDK-compiled `spec` string instead of typed attributes ([#12782](https://github.com/NVIDIA/NemoClaw/issues/12782)). These sections need verified implementations and test results before they can recommend a direct-use workflow.