workload_spec/validate.rs
1//! Shape validators for [`WorkloadSpec`].
2//!
3//! Called by clients (desktop, agent, CLI) before sending a spec over RPC.
4//! Sync, no I/O. Returns `Ok(warnings)` on pass or `Err(ShapeError)` on the
5//! first hard constraint violation.
6//!
7//! Layers: shape (this file, no I/O) → semantic (yubaba-side, R090-F3) →
8//! environment (deploy-time, R090-F4).
9
10use std::fmt;
11use std::sync::OnceLock;
12
13use regex::Regex;
14use thiserror::Error;
15
16use crate::{
17 DurabilityDeclError, EnvValue, EnvVar, ImageRef, LifecycleArchetype, MachineId, MeshIdent, MeshLookup,
18 RestartPolicy, SecretRef, SecretTarget, StaticAssetWorkload, Supply, VolumeSource,
19 WorkloadSpec,
20};
21
22// ── Field paths ───────────────────────────────────────────────────────────────
23
24/// Identifies the field that caused a shape error or warning.
25///
26/// Structured as an enum so promoting to all-errors mode (collecting into
27/// `Vec<FieldError>` instead of returning on the first hit) is mechanical.
28#[derive(Debug, Clone, PartialEq)]
29pub enum FieldPath {
30 Name,
31 MeshIdentity,
32 TailscaleTag,
33 Replicas,
34 ImageTag,
35 Tier,
36 /// `volumes[index].<sub>` — e.g. `Volume(0, "source")`.
37 Volume(usize, &'static str),
38 /// Public port not found in `expose.mesh.ports`.
39 ExposeMeshPort(u16),
40 /// `expose.mesh.ports[index]` — a malformed port declaration (R844-F17):
41 /// an empty entry, a bad name, or a name/number repeated within the list.
42 MeshPort(usize),
43 /// `secrets[index].<sub>` — e.g. `Secret(0, "target.path")`.
44 Secret(usize, &'static str),
45 /// `healthcheck.<sub>`.
46 Healthcheck(&'static str),
47 RestartPolicy,
48 /// `image` — registry says the image/tag is unknown.
49 Image,
50 /// `depends_on[index]` — mesh ident is not a known deployed workload.
51 DependsOn(usize),
52 /// `requires[index]` — a malformed requirement (R860-T1): a `supply` /
53 /// `provides` mismatch, a provider whose spec names a different identity,
54 /// a nested `self` supply, or a repeated / self-naming ident.
55 Requires(usize),
56 /// `expose.public.hostname` — hostname is not in an owned CF zone.
57 Hostname,
58 /// `resources` — machine lacks sufficient capacity.
59 Resources,
60 /// `aliases[key]` — alias target filename is not in the `[[asset]]` catalog.
61 AssetAlias(String),
62 /// `asset[index].<sub>` — e.g. `Asset(0, "source")` for the XOR rule.
63 Asset(usize, &'static str),
64 /// `annotations["<key>"]` — today only a key from a family R896-F3 retired
65 /// into typed fields.
66 Annotation(String),
67 /// `durability.<sub>` — e.g. `Durability("subjects")`.
68 Durability(&'static str),
69}
70
71impl fmt::Display for FieldPath {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 match self {
74 FieldPath::Name => write!(f, "name"),
75 FieldPath::MeshIdentity => write!(f, "expose.mesh.identity"),
76 FieldPath::TailscaleTag => write!(f, "expose.operator.tailscale_tag"),
77 FieldPath::Replicas => write!(f, "replicas"),
78 FieldPath::ImageTag => write!(f, "image.tag"),
79 FieldPath::Tier => write!(f, "tier"),
80 FieldPath::Volume(i, sub) => write!(f, "volumes[{i}].{sub}"),
81 FieldPath::ExposeMeshPort(port) => write!(f, "expose.public.port ({port})"),
82 FieldPath::MeshPort(i) => write!(f, "expose.mesh.ports[{i}]"),
83 FieldPath::Secret(i, sub) => write!(f, "secrets[{i}].{sub}"),
84 FieldPath::Healthcheck(sub) => write!(f, "healthcheck.{sub}"),
85 FieldPath::RestartPolicy => write!(f, "restart_policy"),
86 FieldPath::Image => write!(f, "image"),
87 FieldPath::DependsOn(i) => write!(f, "depends_on[{i}]"),
88 FieldPath::Requires(i) => write!(f, "requires[{i}]"),
89 FieldPath::Hostname => write!(f, "expose.public.hostname"),
90 FieldPath::Resources => write!(f, "resources"),
91 FieldPath::AssetAlias(key) => write!(f, "aliases[{key}]"),
92 FieldPath::Asset(i, sub) => write!(f, "asset[{i}].{sub}"),
93 FieldPath::Annotation(key) => write!(f, "annotations[\"{key}\"]"),
94 FieldPath::Durability(sub) => write!(f, "durability.{sub}"),
95 }
96 }
97}
98
99/// The `durability.<sub>` a [`DurabilityDeclError`] is about, so the path in a
100/// refusal points at the key to fix rather than at the whole table.
101fn durability_error_field(e: &DurabilityDeclError) -> &'static str {
102 use DurabilityDeclError as E;
103 match e {
104 E::RetiredAnnotation { .. } => "tier",
105 E::MissingStore { .. } | E::StoreWithoutTier => "store",
106 E::RpoOnNonStreamTier { .. } => "rpo_seconds",
107 E::MissingEngine { .. } | E::EngineWithoutTier => "engine",
108 E::MissingSubjects { .. }
109 | E::SubjectsWithoutTier
110 | E::EmptySubject
111 | E::AbsoluteSubject { .. }
112 | E::TraversingSubject { .. }
113 | E::DuplicateSubject { .. } => "subjects",
114 }
115}
116
117// ── Hard errors ───────────────────────────────────────────────────────────────
118
119/// A hard constraint violation that makes a spec impossible to deploy.
120///
121/// V1 surfaces the first error found. When the UI needs per-field
122/// highlighting, wrap in `Vec<ShapeError>` and collect instead of returning
123/// early — the `FieldPath` enum is already the common currency.
124#[derive(Debug, Error, PartialEq)]
125pub enum ShapeError {
126 #[error("field {path}: {reason}")]
127 Field { path: FieldPath, reason: String },
128}
129
130// ── Soft warnings ─────────────────────────────────────────────────────────────
131
132/// A soft check that passed but may indicate misconfiguration.
133#[derive(Debug, Clone, PartialEq)]
134pub struct ShapeWarning {
135 pub path: FieldPath,
136 pub message: String,
137}
138
139impl fmt::Display for ShapeWarning {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 write!(f, "warning at {}: {}", self.path, self.message)
142 }
143}
144
145// ── Internal helpers ──────────────────────────────────────────────────────────
146
147/// V1 known tier values. Unknown tiers produce a warning, not an error
148/// (cluster config may add custom tiers).
149const KNOWN_TIERS: &[&str] = &["public", "tenant", "private", "infra"];
150
151fn dns_label_re() -> &'static Regex {
152 static RE: OnceLock<Regex> = OnceLock::new();
153 RE.get_or_init(|| Regex::new(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$").unwrap())
154}
155
156fn env_name_re() -> &'static Regex {
157 static RE: OnceLock<Regex> = OnceLock::new();
158 RE.get_or_init(|| Regex::new(r"^[A-Z_][A-Z0-9_]*$").unwrap())
159}
160
161/// Validates a single DNS label: `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`, ≤ 63 chars.
162fn check_dns_label(value: &str, path: FieldPath) -> Result<(), ShapeError> {
163 if value.len() > 63 {
164 return Err(ShapeError::Field {
165 path,
166 reason: format!("length {} exceeds maximum 63", value.len()),
167 });
168 }
169 if !dns_label_re().is_match(value) {
170 return Err(ShapeError::Field {
171 path,
172 reason: format!(
173 "{:?} must match ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",
174 value
175 ),
176 });
177 }
178 Ok(())
179}
180
181/// Validates a dot-separated mesh identity where each segment is a DNS label.
182/// Total length ≤ 63. Example valid value: `"noisetable-api.pdx"`.
183fn check_mesh_ident(value: &str, path: FieldPath) -> Result<(), ShapeError> {
184 if value.len() > 63 {
185 return Err(ShapeError::Field {
186 path,
187 reason: format!("length {} exceeds maximum 63", value.len()),
188 });
189 }
190 for segment in value.split('.') {
191 if !dns_label_re().is_match(segment) {
192 return Err(ShapeError::Field {
193 path,
194 reason: format!(
195 "segment {:?} in {:?} must match ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",
196 segment, value
197 ),
198 });
199 }
200 }
201 Ok(())
202}
203
204/// The longest a port name may be. Matches IANA's service-name limit, which is
205/// what Kubernetes uses for the same field and what any tool that has to render
206/// a port name in a fixed column already assumes.
207const MESH_PORT_NAME_MAX: usize = 15;
208
209/// Validates `expose.mesh.ports` (R844-F17): every entry states something, every
210/// name is a DNS label short enough to be a service name, and nothing is
211/// declared twice.
212///
213/// The uniqueness rules are the load-bearing half. A repeated *name* would make
214/// `name -> port` ambiguous at exactly the moment a consumer asks for it —
215/// `ServiceRecord::port("http")` and the `PORT_HTTP` variable both resolve
216/// through that map — and a repeated *number* is a workload asking to bind one
217/// socket twice. Both are caught here rather than at bring-up because the
218/// author can still see the manifest.
219fn check_mesh_ports(
220 mesh: &crate::MeshExpose,
221 warnings: &mut Vec<ShapeWarning>,
222) -> Result<(), ShapeError> {
223 let mut seen_names: Vec<&str> = Vec::new();
224 let mut seen_numbers: Vec<u16> = Vec::new();
225
226 for (i, port) in mesh.ports.iter().enumerate() {
227 let path = FieldPath::MeshPort(i);
228
229 if port.name.is_none() && port.number.is_none() {
230 return Err(ShapeError::Field {
231 path,
232 reason: "declares neither a name nor a number — write a number \
233 (8080), a name (\"http\"), or both \
234 ({ name = \"http\", port = 8080 })"
235 .to_string(),
236 });
237 }
238
239 if let Some(name) = port.name.as_deref() {
240 if name.len() > MESH_PORT_NAME_MAX {
241 return Err(ShapeError::Field {
242 path,
243 reason: format!(
244 "port name {name:?} is {} characters; the maximum is \
245 {MESH_PORT_NAME_MAX}",
246 name.len()
247 ),
248 });
249 }
250 if !dns_label_re().is_match(name) {
251 return Err(ShapeError::Field {
252 path,
253 reason: format!(
254 "port name {name:?} must match \
255 ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$"
256 ),
257 });
258 }
259 if seen_names.contains(&name) {
260 return Err(ShapeError::Field {
261 path,
262 reason: format!(
263 "port name {name:?} is declared twice; a name is how a \
264 consumer selects one port, so it has to pick out \
265 exactly one"
266 ),
267 });
268 }
269 seen_names.push(name);
270 }
271
272 match port.number {
273 Some(number) => {
274 if seen_numbers.contains(&number) {
275 return Err(ShapeError::Field {
276 path,
277 reason: format!(
278 "port {number} is declared twice; a workload cannot \
279 bind the same port on two listeners"
280 ),
281 });
282 }
283 seen_numbers.push(number);
284 }
285 // Still a warning rather than an error, but R844-F21 changed what
286 // it has to say. A name-only port IS allocated now — on the native
287 // backend, which owns the workload's network namespace: kamaji
288 // picks the number, remembers it per `(ident, name)` across a
289 // restart, and hands it to the process as `PORT_<NAME>`.
290 //
291 // It is still unbindable on a container backend, where the ports
292 // are the image's and both backends refuse the spelling outright
293 // (`kamaji::reject_unresolved_ports`). Shape validation cannot tell
294 // which backend a spec will land on — placement decides that later
295 // — so naming the split is the most this layer can honestly say,
296 // and it is why an error here would be wrong.
297 None => warnings.push(ShapeWarning {
298 path,
299 message: format!(
300 "port {:?} declares no number: the native backend allocates \
301 one and tells the process via PORT_{}, but a container \
302 backend refuses it — a container's ports are its image's. \
303 State the number ({{ name = {:?}, port = <n> }}) if this \
304 workload runs as a container.",
305 port.name.as_deref().unwrap_or_default(),
306 port.name
307 .as_deref()
308 .unwrap_or_default()
309 .to_uppercase()
310 .replace(|c: char| !c.is_ascii_alphanumeric(), "_"),
311 port.name.as_deref().unwrap_or_default(),
312 ),
313 }),
314 }
315 }
316
317 Ok(())
318}
319
320/// Validates `requires` (R860-T1 / W338): the `supply` / `provides` pairing,
321/// the identity a self-provisioned provider claims, the depth bound on the
322/// recursion, and ident uniqueness.
323///
324/// The depth bound is the load-bearing rule. `Requirement::provides` makes
325/// `WorkloadSpec` recursive, and a provider that may itself self-provision
326/// turns "a workload plus its sidecars" into an unbounded tree that placement
327/// would have to flatten before it could schedule anything. One level is what
328/// the design asks for, so one level is what is representable.
329fn check_requires(spec: &WorkloadSpec) -> Result<(), ShapeError> {
330 let mut seen: Vec<&str> = Vec::new();
331
332 for (i, req) in spec.requires.iter().enumerate() {
333 let path = || FieldPath::Requires(i);
334 let ident = req.ident.0.as_str();
335
336 if ident == spec.expose.mesh.identity.0 {
337 return Err(ShapeError::Field {
338 path: path(),
339 reason: format!(
340 "requires its own identity {ident:?}; a workload cannot be \
341 its own provider"
342 ),
343 });
344 }
345 if seen.contains(&ident) {
346 return Err(ShapeError::Field {
347 path: path(),
348 reason: format!(
349 "ident {ident:?} is declared twice; one requirement per \
350 provider, since a second entry could only contradict the \
351 first's locality or supply"
352 ),
353 });
354 }
355 seen.push(ident);
356
357 match (req.supply, &req.provides) {
358 (Supply::SelfProvision, None) => {
359 return Err(ShapeError::Field {
360 path: path(),
361 reason: format!(
362 "supply = \"self\" on {ident:?} but no `provides` spec; \
363 a self-provisioned requirement is the one that carries \
364 its provider, so there is nothing to stand up"
365 ),
366 });
367 }
368 (Supply::Wait, Some(_)) => {
369 return Err(ShapeError::Field {
370 path: path(),
371 reason: format!(
372 "supply = \"wait\" on {ident:?} but a `provides` spec is \
373 present; a waiting requirement names a provider someone \
374 else declares, so this spec would have no owner — set \
375 supply = \"self\" to deploy it here"
376 ),
377 });
378 }
379 (Supply::Wait, None) => {}
380 (Supply::SelfProvision, Some(provided)) => {
381 if provided.expose.mesh.identity.0 != ident {
382 return Err(ShapeError::Field {
383 path: path(),
384 reason: format!(
385 "`provides` declares expose.mesh.identity {:?} but the \
386 requirement names {ident:?}; the provider keeps its \
387 own mesh identity and it has to be the one this \
388 requirement asks for (its `name` is {:?})",
389 provided.expose.mesh.identity.0, provided.name
390 ),
391 });
392 }
393 if let Some(nested) = provided
394 .requires
395 .iter()
396 .find(|r| matches!(r.supply, Supply::SelfProvision))
397 {
398 return Err(ShapeError::Field {
399 path: path(),
400 reason: format!(
401 "`provides` spec {ident:?} itself requires {:?} with \
402 supply = \"self\"; composition is bounded at one \
403 level, so a provider may only wait on things it \
404 does not deploy — hoist that requirement up to this \
405 spec's own `requires`",
406 nested.ident.0
407 ),
408 });
409 }
410 }
411 }
412 }
413
414 Ok(())
415}
416
417// ── Public API ────────────────────────────────────────────────────────────────
418
419/// Run shape validation — sync, no I/O.
420///
421/// Returns `Ok(warnings)` when all hard constraints pass; the `Vec` is empty
422/// for a clean spec. Returns `Err` on the first hard constraint violation.
423/// Callers that only need hard errors can discard the Ok value with
424/// `.map(|_| ())`.
425///
426/// Hard constraints checked:
427/// - `name`, `expose.mesh.identity`: DNS-label format, ≤ 63 chars.
428/// - `expose.operator.tailscale_tag`: `"tag:<dns-label>"`, ≤ 63 chars.
429/// - `replicas`: 0–100.
430/// - `image.tag`: non-empty when `digest` is `None`.
431/// - `volumes[*].source = Bind`: only allowed when `tier = "infra"`.
432/// - `expose.mesh.ports[*]`: each entry states a name and/or a number; names are
433/// DNS labels ≤ 15 chars; no name and no number is declared twice (R844-F17).
434/// - `expose.public.port`: must appear in `expose.mesh.ports`.
435/// - `secrets[*].target`: file paths must be absolute; env-var names must
436/// match `^[A-Z_][A-Z0-9_]*$`.
437/// - `requires[*]`: `supply = "self"` carries a `provides` spec and
438/// `supply = "wait"` does not; a `provides` spec declares the identity its
439/// requirement names; a `provides` spec carries no `self` supply of its own
440/// (depth 1); idents are unique and none is the spec's own (R860-T1).
441///
442/// Soft checks (produce warnings, not errors):
443/// - `expose.mesh.ports[*]`: a name with no number — nothing allocates from the
444/// manifest yet, so nothing binds it (R844-F17).
445/// - Unknown tier value.
446/// - `RestartPolicy::Never` without `annotations["yah.forge"] = "true"`.
447/// - `healthcheck.initial_delay < stop_policy.grace_period * 2`.
448pub fn shape(spec: &WorkloadSpec) -> Result<Vec<ShapeWarning>, ShapeError> {
449 let mut warnings: Vec<ShapeWarning> = Vec::new();
450
451 // name: single DNS label, ≤ 63 chars
452 check_dns_label(&spec.name, FieldPath::Name)?;
453
454 // expose.mesh.identity: dot-separated DNS name, ≤ 63 total
455 check_mesh_ident(&spec.expose.mesh.identity.0, FieldPath::MeshIdentity)?;
456
457 // expose.operator.tailscale_tag: "tag:<dns-label>", ≤ 63 chars (optional)
458 if let Some(op) = &spec.expose.operator {
459 let tag = &op.tailscale_tag;
460 if tag.len() > 63 {
461 return Err(ShapeError::Field {
462 path: FieldPath::TailscaleTag,
463 reason: format!("length {} exceeds maximum 63", tag.len()),
464 });
465 }
466 let rest = tag.strip_prefix("tag:").ok_or_else(|| ShapeError::Field {
467 path: FieldPath::TailscaleTag,
468 reason: format!("{:?} must start with \"tag:\"", tag),
469 })?;
470 if !dns_label_re().is_match(rest) {
471 return Err(ShapeError::Field {
472 path: FieldPath::TailscaleTag,
473 reason: format!(
474 "the part after \"tag:\" in {:?} must match \
475 ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",
476 tag
477 ),
478 });
479 }
480 }
481
482 // replicas: 0..=100
483 if spec.replicas > 100 {
484 return Err(ShapeError::Field {
485 path: FieldPath::Replicas,
486 reason: format!("{} exceeds maximum 100", spec.replicas),
487 });
488 }
489
490 // image.tag: non-empty (informational identifier; digest is normally the
491 // source of truth — but see the digest check just below, which is where
492 // "normally" earns its qualifier).
493 if spec.image.tag.is_empty() {
494 return Err(ShapeError::Field {
495 path: FieldPath::ImageTag,
496 reason: "tag is empty; provide a human-readable tag alongside the digest".into(),
497 });
498 }
499
500 // image.digest: empty is legal ONLY for a spec whose exec substrate never
501 // pulls the image — `wants_native_exec` and `wants_microvm` both document
502 // their `image` as "identity metadata only, nothing is pulled". A
503 // Container-substrate spec has no such backend: it reaches containerd or
504 // docker, both of which resolve the ref by digest before doing anything
505 // else. An empty digest there is not a missing image, it is a
506 // construction bug — a spec built for native/microVM that never got the
507 // `yah.exec` marker (R931-B4: `InnerDoorPlan::workload` did exactly this,
508 // and the failure surfaced as containerd 500ing on a cr-less pull of
509 // `local/passway:inner-door@`, an empty-digest ref containerd was never
510 // meant to see). Caught here, at the one shape gate every deploy and
511 // `/workloads/validate` call runs before admission or the backend, so a
512 // future construction site that forgets the annotation is refused by name
513 // instead of reaching a backend that mis-reads "nothing to pull" as
514 // "pull it and 500".
515 if spec.image.digest.is_empty() && spec.exec_substrate() == crate::ExecSubstrate::Container {
516 return Err(ShapeError::Field {
517 path: FieldPath::Image,
518 reason: format!(
519 "digest is empty, which is only valid for a spec marked for native or \
520 microVM execution (annotations[{:?}] = {:?} or {:?}) — this spec requests \
521 the container substrate, which pulls {}/{}:{} by digest and has nothing to \
522 pull",
523 crate::NATIVE_EXEC_ANNOTATION,
524 crate::NATIVE_EXEC_VALUE,
525 crate::MICROVM_EXEC_VALUE,
526 spec.image.registry,
527 spec.image.repository,
528 spec.image.tag,
529 ),
530 });
531 }
532
533 // tier: warn on unknown (cluster config may add custom tiers)
534 if !KNOWN_TIERS.contains(&spec.tier.0.as_str()) {
535 warnings.push(ShapeWarning {
536 path: FieldPath::Tier,
537 message: format!(
538 "\"{}\" is not in the known tier set (public/tenant/private/infra); \
539 yubaba may reject it if the cluster config does not include this tier",
540 spec.tier.0
541 ),
542 });
543 }
544
545 // volumes[*]: Bind rejected unless tier = "infra"
546 for (i, vol) in spec.volumes.iter().enumerate() {
547 if matches!(&vol.source, VolumeSource::Bind { .. }) && spec.tier.0 != "infra" {
548 return Err(ShapeError::Field {
549 path: FieldPath::Volume(i, "source"),
550 reason: format!(
551 "Bind mounts are only allowed when tier = \"infra\" \
552 (current tier: {:?})",
553 spec.tier.0
554 ),
555 });
556 }
557 }
558
559 // expose.mesh.ports[*]: names well-formed, nothing declared twice (R844-F17)
560 check_mesh_ports(&spec.expose.mesh, &mut warnings)?;
561
562 // requires[*]: supply/provides pairing, provider identity, depth bound,
563 // ident uniqueness (R860-T1)
564 check_requires(spec)?;
565
566 // expose.public.port must appear in expose.mesh.ports
567 if let Some(public) = &spec.expose.public {
568 if !spec.expose.mesh.declares_number(public.port) {
569 return Err(ShapeError::Field {
570 path: FieldPath::ExposeMeshPort(public.port),
571 reason: format!(
572 "port {} must appear in expose.mesh.ports {:?} \
573 before it can be exposed publicly",
574 public.port,
575 spec.expose.mesh.numbers()
576 ),
577 });
578 }
579 }
580
581 // secrets[*]: target paths absolute; env-var names valid identifiers
582 for (i, secret) in spec.secrets.iter().enumerate() {
583 match &secret.target {
584 SecretTarget::File { path, .. } => {
585 if !path.is_absolute() {
586 return Err(ShapeError::Field {
587 path: FieldPath::Secret(i, "target.path"),
588 reason: format!("{:?} is not an absolute path", path),
589 });
590 }
591 }
592 SecretTarget::EnvVar { name } => {
593 if !env_name_re().is_match(name) {
594 return Err(ShapeError::Field {
595 path: FieldPath::Secret(i, "target.name"),
596 reason: format!(
597 "{:?} is not a valid env-var identifier (^[A-Z_][A-Z0-9_]*$)",
598 name
599 ),
600 });
601 }
602 }
603 }
604 }
605
606 // soft: RestartPolicy::Never without yah.forge=true annotation
607 if matches!(spec.restart_policy, RestartPolicy::Never) {
608 let is_forge = spec
609 .annotations
610 .get("yah.forge")
611 .map(|v| v == "true")
612 .unwrap_or(false);
613 if !is_forge {
614 warnings.push(ShapeWarning {
615 path: FieldPath::RestartPolicy,
616 message: "restart_policy=Never is intended for forge runs; \
617 add annotation yah.forge=true to suppress this warning"
618 .into(),
619 });
620 }
621 }
622
623 // R896-F3: the `yah.limits.*` / `yah.placement.memory-request-mb` /
624 // `yah.durability.*` annotations became typed fields. Nothing reads those
625 // keys any more, and a key nothing reads fails silently — a pids ceiling
626 // falls back to the default, a durability tier means "no backup" — so a
627 // surviving one refuses the spec and names where the value goes now.
628 if let Some((key, field)) = spec.retired_annotation() {
629 return Err(ShapeError::Field {
630 path: FieldPath::Annotation(key.to_string()),
631 reason: format!(
632 "annotation {key:?} is no longer read; since R896-F3 it is the typed field \
633 `{field}` — move the value there, because an ignored annotation silently \
634 falls back to the default"
635 ),
636 });
637 }
638
639 // durability: a malformed declaration is hard, and a stateful workload with
640 // no declaration at all is soft (R850-P4).
641 //
642 // The asymmetry is deliberate. Refusing every undeclared appliance would
643 // fail every spec in the tree on the day the declaration shipped; reading a
644 // *malformed* one as "undeclared" would let a half-written declaration mean
645 // "no backups" silently, which is the failure this whole surface exists to
646 // stop. See `WorkloadSpec::durability`.
647 let durability = spec.durability().map_err(|e| ShapeError::Field {
648 path: FieldPath::Durability(durability_error_field(&e)),
649 reason: e.to_string(),
650 })?;
651 // R850-F1: a bytes-shipping tier's subjects are volume-relative, so there
652 // has to be exactly one volume for them to be relative *to*. Zero means the
653 // declaration names files that will never exist; two or more means the
654 // hydrate helper would have to guess which host directory to restore into,
655 // and a wrong guess writes somebody's database over somebody else's.
656 //
657 // A **bind** counts, not only a yubaba-managed named volume. The rule was
658 // named-only until R858-F17 named the case it excluded: headscale keeps its
659 // state at `/var/lib/yah-cloud/headscale/`, is a native-exec appliance, and
660 // has no named volume and never will — so the narrow rule made the one
661 // workload whose loss took this camp's mesh down for 37 hours the one
662 // workload that could not declare durability. A bind is already restricted
663 // to `tier = "infra"` below, which is exactly the class this applies to.
664 if let Some(d) = durability.as_ref().filter(|d| d.tier.ships_bytes()) {
665 let roots: Vec<String> = spec
666 .volumes
667 .iter()
668 // A secret-materializer bind (R858-B26) is excluded for the same
669 // reason Tmpfs is: it is not where durable subjects live, it is
670 // just where yubaba parked a decrypted file.
671 .filter(|v| !v.from_secret_mount)
672 .filter_map(|v| match &v.source {
673 VolumeSource::Named { name } => Some(name.clone()),
674 VolumeSource::Bind { host_path } => Some(host_path.display().to_string()),
675 // Tmpfs is deliberately not a candidate: it is the declaration
676 // that this data does not survive the process, so counting it
677 // would let a spec claim durable state on a ramdisk.
678 VolumeSource::Tmpfs { .. } => None,
679 })
680 .collect();
681 if roots.len() != 1 {
682 return Err(ShapeError::Field {
683 path: FieldPath::Durability("subjects"),
684 reason: format!(
685 "durability.tier = \"{}\" declares subjects {:?}, which are \
686 relative to one volume, but this spec declares {} named-or-bind volumes{}; \
687 a tier that ships bytes needs exactly one (tmpfs does not count — it is a \
688 declaration that the data does not survive)",
689 d.tier,
690 d.subjects,
691 roots.len(),
692 if roots.is_empty() {
693 String::new()
694 } else {
695 format!(" ({})", roots.join(", "))
696 }
697 ),
698 });
699 }
700 }
701
702 if durability.is_none()
703 && spec.effective_archetype() == LifecycleArchetype::Appliance
704 && spec
705 .volumes
706 .iter()
707 .any(|v| matches!(v.source, VolumeSource::Named { .. }))
708 {
709 warnings.push(ShapeWarning {
710 path: FieldPath::Durability("tier"),
711 message: "appliance with a yubaba-managed named volume declares no durability \
712 tier, so that volume is the only copy of its state and losing the node \
713 loses it; declare durability.tier = \"none\" if that is intended, or a \
714 real tier if it is not"
715 .into(),
716 });
717 }
718
719 // soft: healthcheck.initial_delay >= stop_policy.grace_period * 2
720 if let Some(hc) = &spec.healthcheck {
721 let min_recommended = spec.stop_policy.grace_period.as_ms().saturating_mul(2);
722 if hc.initial_delay.as_ms() < min_recommended {
723 warnings.push(ShapeWarning {
724 path: FieldPath::Healthcheck("initial_delay"),
725 message: format!(
726 "initial_delay ({}ms) is less than stop_policy.grace_period * 2 ({}ms); \
727 a SIGTERM during startup may catch a still-initialising container",
728 hc.initial_delay.as_ms(),
729 min_recommended
730 ),
731 });
732 }
733 }
734
735 Ok(warnings)
736}
737
738// ── StaticAsset validator ─────────────────────────────────────────────────────
739
740/// Shape-validate a `kind = "static-asset"` workload.
741///
742/// Enforces the closed-catalog invariant: every value in `[aliases]` must be a
743/// `filename` present in `[[asset]]`. A mirror's `[asset_aliases]` overrides
744/// are bound by the same rule and are validated separately at sync time when
745/// both the workload and mirror are loaded together.
746pub fn shape_static_asset(workload: &StaticAssetWorkload) -> Result<(), ShapeError> {
747 // XOR rule (W164 / R438-T2): every [[asset]] row must set exactly one of
748 // `source` (legacy local bytes) or `derive` (fetch + optional transform).
749 // Both-set is ambiguous (which one wins?); neither-set leaves the
750 // reconciler with no bytes to upload.
751 for (i, entry) in workload.assets.iter().enumerate() {
752 match (entry.source.is_some(), entry.derive.is_some()) {
753 (true, true) => {
754 return Err(ShapeError::Field {
755 path: FieldPath::Asset(i, "source"),
756 reason: format!(
757 "asset {:?}: both `source` and `derive` are set; pick exactly one",
758 entry.filename
759 ),
760 });
761 }
762 (false, false) => {
763 return Err(ShapeError::Field {
764 path: FieldPath::Asset(i, "source"),
765 reason: format!(
766 "asset {:?}: neither `source` nor `derive` is set; pick exactly one",
767 entry.filename
768 ),
769 });
770 }
771 _ => {}
772 }
773 }
774
775 let filenames: std::collections::HashSet<&str> =
776 workload.assets.iter().map(|a| a.filename.as_str()).collect();
777
778 for (alias_key, alias_target) in &workload.aliases {
779 if !filenames.contains(alias_target.as_str()) {
780 return Err(ShapeError::Field {
781 path: FieldPath::AssetAlias(alias_key.clone()),
782 reason: format!(
783 "alias target {:?} is not present in the [[asset]] catalog; \
784 add a matching [[asset]] row or correct the filename",
785 alias_target
786 ),
787 });
788 }
789 }
790
791 Ok(())
792}
793
794// ── Semantic layer ────────────────────────────────────────────────────────────
795
796/// Transient error from a [`ValidationContext`] lookup.
797///
798/// Distinct from a semantic "resource not found" failure. `ContextError` means
799/// the lookup itself could not complete (network timeout, auth failure, etc.),
800/// not that the resource is definitively absent.
801#[derive(Debug, Error, Clone, PartialEq)]
802#[error("context lookup failed: {0}")]
803pub struct ContextError(pub String);
804
805/// A semantic constraint violation: the spec references a resource that is not
806/// known to the cluster at validation time.
807#[derive(Debug, Error, PartialEq)]
808pub enum SemanticError {
809 #[error("field {path}: {reason}")]
810 Unknown { path: FieldPath, reason: String },
811}
812
813/// Top-level validation error spanning both shape and semantic layers.
814///
815/// `Shape` always wins: if the spec is structurally invalid, semantic checks
816/// never run.
817#[derive(Debug, Error, PartialEq)]
818pub enum WorkloadValidationError {
819 /// Hard shape constraint failed — spec is structurally invalid.
820 #[error("shape: {0}")]
821 Shape(ShapeError),
822
823 /// Semantic check failed — spec references an unknown cluster resource.
824 #[error("semantic: {0}")]
825 Semantic(SemanticError),
826
827 /// Transient ValidationContext lookup failure — the check itself failed.
828 #[error("context: {0}")]
829 Context(ContextError),
830}
831
832impl From<ShapeError> for WorkloadValidationError {
833 fn from(e: ShapeError) -> Self { WorkloadValidationError::Shape(e) }
834}
835
836impl From<ContextError> for WorkloadValidationError {
837 fn from(e: ContextError) -> Self { WorkloadValidationError::Context(e) }
838}
839
840/// Read-only view of yubaba state used for semantic validation.
841///
842/// Defined here so clients (desktop, CLI, agents) can run semantic checks
843/// without depending on the yubaba crate. Yubaba implements this trait.
844///
845/// Each method returns `Result<bool, ContextError>` so transient failures are
846/// distinguishable from definitive "not found" answers.
847pub trait ValidationContext {
848 /// True when the registry confirms the image exists.
849 fn image_exists(&self, image: &ImageRef) -> Result<bool, ContextError>;
850
851 /// True when the named secret exists in the yubaba secret store.
852 fn secret_exists(&self, secret: &SecretRef) -> Result<bool, ContextError>;
853
854 /// True when `ident` is a known deployed workload OR appears in `batch`
855 /// (the set of specs co-deployed in the same request — allows forward
856 /// references within a single deployment batch).
857 fn mesh_ident_known(&self, ident: &MeshIdent, batch: &[MeshIdent]) -> Result<bool, ContextError>;
858
859 /// True when `hostname` falls under a Cloudflare zone owned by this cluster.
860 fn cf_zone_owned(&self, hostname: &str) -> Result<bool, ContextError>;
861
862 /// True when `tag` (e.g. `"tag:noisetable-ops"`) is in the cluster's
863 /// Tailscale ACL tag list.
864 fn tailscale_tag_known(&self, tag: &str) -> Result<bool, ContextError>;
865
866 /// True when `machine_id` has sufficient remaining capacity to host the
867 /// given spec's resource requirements.
868 ///
869 /// Implementors: read memory via [`WorkloadSpec::memory_request_mb`], not
870 /// `spec.resources.memory_mb`. The latter is a cgroup ceiling, and using
871 /// it as a capacity floor is what made every build-worker smaller than
872 /// `for_forge`'s 32 GiB ceiling unschedulable in `admit_workload`. Only a
873 /// test implementation of this trait exists today, so the bug is not live
874 /// here — this note is to keep it from arriving with the first real one.
875 fn capacity_for(&self, spec: &WorkloadSpec, machine_id: &MachineId) -> Result<bool, ContextError>;
876}
877
878/// Run semantic validation — requires yubaba state via [`ValidationContext`].
879///
880/// Shape validation is NOT run here. Callers MUST run [`shape`] first; use
881/// [`all`] to enforce this automatically.
882///
883/// `machine_id` is the target machine for admission-control capacity checks.
884/// `batch` is the set of mesh idents being co-deployed (pass `&[]` for
885/// single-spec deployment); these count as "known" for `depends_on` resolution.
886pub fn semantic(
887 spec: &WorkloadSpec,
888 ctx: &dyn ValidationContext,
889 machine_id: &MachineId,
890 batch: &[MeshIdent],
891) -> Result<(), WorkloadValidationError> {
892 if !ctx.image_exists(&spec.image)? {
893 return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
894 path: FieldPath::Image,
895 reason: format!(
896 "image {}/{}:{} not found in registry",
897 spec.image.registry, spec.image.repository, spec.image.tag
898 ),
899 }));
900 }
901
902 for (i, secret) in spec.secrets.iter().enumerate() {
903 if !ctx.secret_exists(&secret.source)? {
904 return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
905 path: FieldPath::Secret(i, "source"),
906 reason: format!("secret source at index {i} not found in yubaba secret store"),
907 }));
908 }
909 }
910
911 for (i, dep) in spec.depends_on.iter().enumerate() {
912 if !ctx.mesh_ident_known(dep, batch)? {
913 return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
914 path: FieldPath::DependsOn(i),
915 reason: format!("mesh ident {:?} is not a known deployed workload", dep.0),
916 }));
917 }
918 }
919
920 if let Some(public) = &spec.expose.public {
921 if !ctx.cf_zone_owned(&public.hostname)? {
922 return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
923 path: FieldPath::Hostname,
924 reason: format!(
925 "hostname {:?} is not under a Cloudflare zone owned by this cluster",
926 public.hostname
927 ),
928 }));
929 }
930 }
931
932 if let Some(op) = &spec.expose.operator {
933 if !ctx.tailscale_tag_known(&op.tailscale_tag)? {
934 return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
935 path: FieldPath::TailscaleTag,
936 reason: format!(
937 "tailscale tag {:?} is not in the cluster's ACL tag list",
938 op.tailscale_tag
939 ),
940 }));
941 }
942 }
943
944 if !ctx.capacity_for(spec, machine_id)? {
945 return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
946 path: FieldPath::Resources,
947 reason: format!(
948 "machine {:?} lacks capacity (memory={}MB cpu_millis={})",
949 machine_id.0, spec.resources.memory_mb, spec.resources.cpu_millis
950 ),
951 }));
952 }
953
954 Ok(())
955}
956
957// ── Mesh resolution layer ─────────────────────────────────────────────────────
958
959/// Failure surface for [`MeshResolver`] lookups.
960///
961/// `NotDeployed` means the dependency hasn't been observed in mesh state yet
962/// (yubaba's deploy step waits on this — see [`crate::EnvValue::FromMesh`]).
963/// `NoPorts` means the dependency is deployed but its `MeshExpose.ports`
964/// list is empty, so a port-based lookup can't render a value. `Lookup`
965/// covers transient failures from the underlying state read.
966#[derive(Debug, Error, Clone, PartialEq)]
967pub enum MeshError {
968 #[error("mesh ident {ident:?} is not yet deployed")]
969 NotDeployed { ident: String },
970
971 #[error(
972 "mesh ident {ident:?} exposes no ports; {lookup:?} requires at least one"
973 )]
974 NoPorts { ident: String, lookup: MeshLookup },
975
976 /// The peer exposes several ports and the lookup did not say which
977 /// (R844-B22). Deliberately an error rather than a pick — see
978 /// [`MeshLookup`]'s docs.
979 #[error(
980 "mesh ident {ident:?} exposes {} ports ({}) and none is named \"http\", \
981 so {lookup:?} cannot say which one to use. Name the port in the \
982 lookup (kind = \"port_named\", name = \"…\"), or name one of the \
983 peer's ports \"http\" in its expose.mesh.ports.",
984 .names.len(),
985 .names.join(", ")
986 )]
987 AmbiguousPort {
988 ident: String,
989 lookup: MeshLookup,
990 names: Vec<String>,
991 },
992
993 /// The lookup named a port the peer does not expose (R844-B22).
994 #[error(
995 "mesh ident {ident:?} exposes no port named {name:?}; it has {}",
996 if .available.is_empty() { "none".to_string() } else { .available.join(", ") }
997 )]
998 NoSuchPort {
999 ident: String,
1000 name: String,
1001 available: Vec<String>,
1002 },
1003
1004 #[error("mesh state lookup failed: {0}")]
1005 Lookup(String),
1006}
1007
1008/// The port name a peer's sole/default listener carries. Agrees with
1009/// `kamaji::DEFAULT_PORT_NAME` by convention rather than by import: kamaji sits
1010/// *above* workload-spec in the publish DAG (`yah-base <- {qed,kamaji} <-
1011/// yubaba`), so depending on it here would invert the graph. The two are pinned
1012/// together by `default_port_name_agrees_with_the_supervisor` in this file's
1013/// tests.
1014pub const DEFAULT_PORT_NAME: &str = "http";
1015
1016/// Pick the port a [`MeshLookup`] refers to out of a peer's `name -> port` map
1017/// (R844-B22) — the one place the rule lives, so every resolver answers the
1018/// same way.
1019///
1020/// - A **named** lookup takes that port, or errors naming what the peer does
1021/// have. No fallback: a lookup that asked for `wss` and silently got `http`
1022/// would be the positional guess wearing a name.
1023/// - An **unnamed** lookup takes the sole port when there is one, else the port
1024/// named [`DEFAULT_PORT_NAME`], else errors. It never takes "the first",
1025/// which is what this function exists to stop.
1026pub fn select_mesh_port(
1027 ident: &str,
1028 ports: &std::collections::BTreeMap<String, u16>,
1029 lookup: &MeshLookup,
1030) -> Result<u16, MeshError> {
1031 if let Some(name) = lookup.port_name() {
1032 return ports.get(name).copied().ok_or_else(|| MeshError::NoSuchPort {
1033 ident: ident.to_string(),
1034 name: name.to_string(),
1035 available: ports.keys().cloned().collect(),
1036 });
1037 }
1038
1039 let mut entries = ports.iter();
1040 match (entries.next(), entries.next()) {
1041 (None, _) => Err(MeshError::NoPorts {
1042 ident: ident.to_string(),
1043 lookup: lookup.clone(),
1044 }),
1045 (Some((_, &only)), None) => Ok(only),
1046 _ => ports
1047 .get(DEFAULT_PORT_NAME)
1048 .copied()
1049 .ok_or_else(|| MeshError::AmbiguousPort {
1050 ident: ident.to_string(),
1051 lookup: lookup.clone(),
1052 names: ports.keys().cloned().collect(),
1053 }),
1054 }
1055}
1056
1057/// Resolve [`crate::EnvValue::FromMesh`] references to literal env values.
1058///
1059/// Defined in workload-spec so clients (agents, desktop, CLI) can render
1060/// specs against fake mesh state without depending on the yubaba crate.
1061/// Yubaba's production implementation (in `yubaba::deploy::mesh_resolve`)
1062/// reads from raft state.
1063///
1064/// **Resolution rules** (R844-B22 replaced the positional ones):
1065/// - [`MeshLookup::Host`] — the bare DNS-ish identifier as authored (e.g.
1066/// `"noisetable-db.pdx"`). Needs no port and resolves for a portless peer.
1067/// - [`MeshLookup::Url`] — `"http://<ident>:<port>"`.
1068/// - [`MeshLookup::Port`] — that port stringified, e.g. `"5432"`.
1069/// - [`MeshLookup::UrlNamed`] / [`MeshLookup::PortNamed`] — the same, at the
1070/// peer's port of that name.
1071///
1072/// **Which port** is [`select_mesh_port`]'s decision, and implementations must
1073/// route through it rather than re-deriving: a sole port, else the one named
1074/// [`DEFAULT_PORT_NAME`], else an error. It is emphatically *not* "the first
1075/// entry", which is what this trait's doc used to promise — declaration order
1076/// is not a statement about which listener a dependent should dial, and acting
1077/// as if it were is how a workload gets handed a metrics port as its API URL.
1078///
1079/// Because the rule is name-based rather than positional, a `Url` and a `Port`
1080/// resolved in the same deploy agree by construction; the old doc had to ask
1081/// implementations to make the lookup atomic to get that.
1082pub trait MeshResolver {
1083 fn resolve(&self, ident: &MeshIdent, kind: MeshLookup) -> Result<String, MeshError>;
1084}
1085
1086/// Render every [`EnvValue::FromMesh`] entry in `env` to a [`EnvValue::Literal`]
1087/// using `resolver`; pass through `Literal` and `FromSecret` values unchanged.
1088///
1089/// Returns the first resolution error encountered. Callers should run this
1090/// after yubaba's stage-3 mesh peering completes (see
1091/// `yubaba::deploy::env_validate::run` doc), at containerd-spec assembly.
1092///
1093/// `FromSecret` values are deliberately untouched here — secret resolution
1094/// is the secrets layer's job (R090-F5), not the mesh resolver's.
1095///
1096/// @yah:ticket(R844-B22, "MeshLookup::Url and ::Port resolve "the first entry in expose.mesh.ports" — the positional guess this relay abolishes, in the env-injection path")
1097/// @yah:status(review)
1098/// @yah:at(2026-09-04T14:10:34Z)
1099/// @yah:assignee(agent:bundle-anthropic-ashguard)
1100/// @yah:parent(R844)
1101/// @yah:severity(medium)
1102/// @yah:gotcha("THE CLAIM IS IN THE TRAIT'S OWN DOC, so this is confirmed rather than inferred. `MeshResolver` (oss/yah-base/crates/workload-spec/src/validate.rs, \\\"Resolution rules\\\") states: `MeshLookup::Url` resolves to `\\\"http://<ident>:<port>\\\"` where port is \\\"the first entry in the referenced workload's `MeshExpose.ports`\\\", and `MeshLookup::Port` is \\\"the first port stringified\\\". That is precisely the index-guess `kamaji::name_anonymous_ports` refuses to make and that R844-F15's `ServiceRecordFanout::port_for` was rewritten to stop making — an ingress rule resolved off declaration order can publish a hostname at a metrics listener, and this path can hand a DEPENDENT WORKLOAD the same wrong number in its environment. Nothing has hit it because no fronted or depended-on workload declares two ports yet; that is the same reason F15 gave for the passway gap it left, and it stops being true the moment someone uses R844-F17's new spelling.")
1103/// @yah:next("THIS IS NOW FIXABLE, WHICH IS WHY IT IS FILED — before R844-F17 a manifest could not name a port, so \\\"first\\\" was the only selector available and the doc was describing a limitation rather than a bug. `MeshExpose::named_numbers()` and `kamaji::declared_port_names()` now give a name-keyed answer.")
1104/// @yah:next("SHAPE: add a named variant to `MeshLookup` (e.g. `Port { name: String }` / `Url { name: String }`) and make the unnamed forms resolve through the `http` rule instead of index 0 — i.e. one port resolves as today, several resolve to `http` if one is named that, and NONE otherwise. Returning an error when several ports are unnamed is the whole point: it sends the author to the manifest rather than handing a dependent a plausible wrong number. MIND THE WIRE: `MeshLookup` rides `EnvValue::FromMesh` inside `WorkloadSpec`, which crosses the postcard kamaji UDS — see the V6/V7 stanza in oss/kamaji/crates/kamaji-proto/src/version.rs. Adding a field to an existing variant is a bump; appending a whole new variant is not.")
1105/// @yah:handoff("FIXED — the positional guess is gone from the env-injection path. `MeshLookup` gained `UrlNamed { name }` / `PortNamed { name }`, APPENDED rather than added as fields on `Url`/`Port` exactly as the ticket instructed, so every existing postcard encoding stays byte-identical (an enum is encoded by variant index) and NO ProtocolVersion bump was needed — verified by the kamaji-proto codec suite passing untouched. The unnamed forms no longer mean \"index 0\": they resolve through `workload_spec::validate::select_mesh_port`, which takes the sole port when there is one, else the port named `http`, else RETURNS AN ERROR. `MeshLookup` also lost `Copy` (it now owns a String); the one call site that relied on it is `resolve_env_from_mesh`, now cloning.")
1106/// @yah:handoff("THE RULE LIVES IN ONE PLACE, which is the actual repair — the bug was not that a rule was wrong, it was that the rule was RE-DERIVED at every site, so all of them agreed about something false. `select_mesh_port(ident, &BTreeMap<String,u16>, &MeshLookup)` in workload-spec is now the only implementation; yubaba `StateMeshResolver` calls it, the workload-spec test fake calls it (it had been carrying its OWN copy of \"the first entry\", which is why the test suite confirmed the bug rather than catching it), and the `MeshResolver` trait doc now REQUIRES implementations to route through it instead of describing the rule for them to copy. A named lookup deliberately does NOT fall back to `http`: that would be the positional guess wearing a name.")
1107/// @yah:handoff("REQUIRED A TYPE CHANGE THE TICKET DID NOT NAME, and it is where the names were actually being lost: `yubaba::deploy::mesh_resolve::MeshAddress.ports` was a `Vec<u16>`. A bare number list CANNOT answer \"which of these is the API port\", so positional resolution was not a shortcut in that file — it was the only thing the type permitted, and the trait doc had written that limitation down as a rule. It is now the same `BTreeMap<String,u16>` that `kamaji::WorkloadState::ports` and `ServiceRecord::resolved_ports` already carry, so a name survives from manifest to dependent environment. Cheap to change: `MeshAddress` is constructed in exactly one file and only by tests.")
1108/// @yah:handoff("ONE CROSS-CRATE CONSTANT, pinned rather than duplicated silently. `select_mesh_port` needs the default port name and CANNOT import `kamaji::DEFAULT_PORT_NAME` — kamaji sits above workload-spec in the publish DAG (`yah-base <- {qed,kamaji} <- yubaba`), so the dep would invert the graph. So `workload_spec::validate::DEFAULT_PORT_NAME` states it, and `kamaji::tests::default_port_name_agrees_with_the_mesh_resolver` asserts all three spellings (kamaji DEFAULT_PORT_NAME, ports::HTTP, the validate const) are one string. Without that pin a future rename would make a dependent `FromMesh` URL and its own `PORT` env disagree about which listener is the default, silently.")
1109/// @yah:verify("cargo test --manifest-path oss/yah-base/Cargo.toml -p yah-workload-spec = 146/0 + 94/0 (87 before, so +7). The behaviour change is pinned by name: `several_unnamed_ports_is_an_error_not_the_first_one` (the case that previously rendered 5432 out of [5432,9100] and had a test LOCKING THAT IN), `several_ports_resolve_through_http_when_one_is_named_that`, `a_named_lookup_selects_that_port_and_nothing_else`, `a_named_lookup_for_an_absent_port_errors_rather_than_falling_back`, `a_sole_port_resolves_whatever_it_is_called` (sole beats the http rule on purpose — no ambiguity exists with one listener), `an_empty_port_map_is_no_ports_not_ambiguous`, `host_resolves_for_a_portless_peer`.")
1110/// @yah:verify("cargo test --manifest-path oss/yubaba/Cargo.toml -p yubaba --lib = 634 passed / 0 failed (632 before). Two new cases run the PRODUCTION resolver, not the fake: `several_unnamed_ports_error_rather_than_resolving_to_the_first` and `a_named_lookup_selects_that_port_through_the_state_resolver`. THREE PRE-EXISTING TESTS ASSERTED THE BUG and were rewritten rather than worked around — `url_renders_first_port_with_http_prefix` / `port_renders_first_port_as_string` (both crates) took a two-port peer and asserted the first one came back; their fixtures are now single-port and the multi-port case is its own explicitly-named test.")
1111/// @yah:verify("WHOLE-TREE on a settled tree: cargo test --manifest-path oss/kamaji/Cargo.toml --workspace --all-features = every target ok (kamaji lib 185/0, kamaji-bin 278/0, kamaji-proto codec suite untouched and green — the no-wire-bump evidence); yah-cloud --lib 1019/0/4 ignored; yah-local-driver --lib 99/0; cargo test -p yah --lib 1364 passed / 0 failed / 1 ignored; cargo check --workspace --all-targets = ZERO errors. R844 PURITY CANARY HELD: cargo test -p xtask --test main mirror_ingress = 11 passed / 0 failed.")
1112/// @yah:gotcha("MEASURED SCOPE, so nobody over- or under-reads this fix: THE FromMesh ENV PATH HAS NO PRODUCTION CALLER TODAY. `resolve_env_from_mesh` is called only from workload-spec own tests; `StateMeshResolver` is constructed only in its own module tests; and kamaji-bin `resolve_env` (native.rs:208) REFUSES an unresolved `EnvValue::FromMesh` outright with \"Yubaba must resolve mesh refs before dispatching to Kamaji\" — but nothing in yubaba calls the resolver on the deploy path. So the wrong rule had not yet handed a real workload a wrong number; it was a loaded gun, not a fired one. That is also why the fix was cheap (no call sites to migrate) and why it was worth doing NOW rather than after the path is wired.")
1113/// @yah:gotcha("GENERATED ARTIFACTS REGENERATED, and they carry MORE than this ticket. `.yah/schema/workload.toml.schema.json` and `packages/yah/workload-spec/index.ts` are generated from these Rust types and the pre-commit regen was disabled 2026-08-15, so they had gone stale at R844-F17 — the TS binding still said `ports: Array<number>` weeks after `MeshExpose.ports` became `Vec<MeshPort>`. Running `cargo run -p xtask -- emit-schemas` and the workload-spec `export-ts` bin swept BOTH F17 drift and this ticket. Diff is confined to the two expected surfaces (`MeshExpose.ports`, `MeshLookup`) and nothing else. Flagging per the shared-tree rule that a derived file is nobody property: whoever owns R844-F17 should know their type change is now reflected in the bindings.")
1114pub fn resolve_env_from_mesh(
1115 env: &[EnvVar],
1116 resolver: &dyn MeshResolver,
1117) -> Result<Vec<EnvVar>, MeshError> {
1118 env.iter()
1119 .map(|var| match &var.value {
1120 EnvValue::FromMesh { ident, kind } => {
1121 let value = resolver.resolve(ident, kind.clone())?;
1122 Ok(EnvVar {
1123 name: var.name.clone(),
1124 value: EnvValue::Literal { value },
1125 })
1126 }
1127 _ => Ok(var.clone()),
1128 })
1129 .collect()
1130}
1131
1132/// Run shape then semantic validation in the correct order.
1133///
1134/// Shape always runs first. If shape fails, `WorkloadValidationError::Shape`
1135/// is returned and semantic checks are skipped — callers never see a
1136/// `Semantic` error for a structurally invalid spec.
1137///
1138/// `machine_id` is forwarded to the capacity admission-control check.
1139/// `batch` is the set of co-deployed mesh idents for forward-reference
1140/// resolution; pass `&[]` for single-spec deployment.
1141pub fn all(
1142 spec: &WorkloadSpec,
1143 ctx: &dyn ValidationContext,
1144 machine_id: &MachineId,
1145 batch: &[MeshIdent],
1146) -> Result<(), WorkloadValidationError> {
1147 shape(spec)?;
1148 semantic(spec, ctx, machine_id, batch)
1149}