Skip to main content

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    EnvValue, EnvVar, ImageRef, MachineId, MeshIdent, MeshLookup, RestartPolicy, SecretRef,
18    SecretTarget, StaticAssetWorkload, VolumeSource, WorkloadSpec,
19};
20
21// ── Field paths ───────────────────────────────────────────────────────────────
22
23/// Identifies the field that caused a shape error or warning.
24///
25/// Structured as an enum so promoting to all-errors mode (collecting into
26/// `Vec<FieldError>` instead of returning on the first hit) is mechanical.
27#[derive(Debug, Clone, PartialEq)]
28pub enum FieldPath {
29    Name,
30    MeshIdentity,
31    TailscaleTag,
32    Replicas,
33    ImageTag,
34    Tier,
35    /// `volumes[index].<sub>` — e.g. `Volume(0, "source")`.
36    Volume(usize, &'static str),
37    /// Public port not found in `expose.mesh.ports`.
38    ExposeMeshPort(u16),
39    /// `expose.mesh.ports[index]` — a malformed port declaration (R844-F17):
40    /// an empty entry, a bad name, or a name/number repeated within the list.
41    MeshPort(usize),
42    /// `secrets[index].<sub>` — e.g. `Secret(0, "target.path")`.
43    Secret(usize, &'static str),
44    /// `healthcheck.<sub>`.
45    Healthcheck(&'static str),
46    RestartPolicy,
47    /// `image` — registry says the image/tag is unknown.
48    Image,
49    /// `depends_on[index]` — mesh ident is not a known deployed workload.
50    DependsOn(usize),
51    /// `expose.public.hostname` — hostname is not in an owned CF zone.
52    Hostname,
53    /// `resources` — machine lacks sufficient capacity.
54    Resources,
55    /// `aliases[key]` — alias target filename is not in the `[[asset]]` catalog.
56    AssetAlias(String),
57    /// `asset[index].<sub>` — e.g. `Asset(0, "source")` for the XOR rule.
58    Asset(usize, &'static str),
59}
60
61impl fmt::Display for FieldPath {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self {
64            FieldPath::Name => write!(f, "name"),
65            FieldPath::MeshIdentity => write!(f, "expose.mesh.identity"),
66            FieldPath::TailscaleTag => write!(f, "expose.operator.tailscale_tag"),
67            FieldPath::Replicas => write!(f, "replicas"),
68            FieldPath::ImageTag => write!(f, "image.tag"),
69            FieldPath::Tier => write!(f, "tier"),
70            FieldPath::Volume(i, sub) => write!(f, "volumes[{i}].{sub}"),
71            FieldPath::ExposeMeshPort(port) => write!(f, "expose.public.port ({port})"),
72            FieldPath::MeshPort(i) => write!(f, "expose.mesh.ports[{i}]"),
73            FieldPath::Secret(i, sub) => write!(f, "secrets[{i}].{sub}"),
74            FieldPath::Healthcheck(sub) => write!(f, "healthcheck.{sub}"),
75            FieldPath::RestartPolicy => write!(f, "restart_policy"),
76            FieldPath::Image => write!(f, "image"),
77            FieldPath::DependsOn(i) => write!(f, "depends_on[{i}]"),
78            FieldPath::Hostname => write!(f, "expose.public.hostname"),
79            FieldPath::Resources => write!(f, "resources"),
80            FieldPath::AssetAlias(key) => write!(f, "aliases[{key}]"),
81            FieldPath::Asset(i, sub) => write!(f, "asset[{i}].{sub}"),
82        }
83    }
84}
85
86// ── Hard errors ───────────────────────────────────────────────────────────────
87
88/// A hard constraint violation that makes a spec impossible to deploy.
89///
90/// V1 surfaces the first error found. When the UI needs per-field
91/// highlighting, wrap in `Vec<ShapeError>` and collect instead of returning
92/// early — the `FieldPath` enum is already the common currency.
93#[derive(Debug, Error, PartialEq)]
94pub enum ShapeError {
95    #[error("field {path}: {reason}")]
96    Field { path: FieldPath, reason: String },
97}
98
99// ── Soft warnings ─────────────────────────────────────────────────────────────
100
101/// A soft check that passed but may indicate misconfiguration.
102#[derive(Debug, Clone, PartialEq)]
103pub struct ShapeWarning {
104    pub path: FieldPath,
105    pub message: String,
106}
107
108impl fmt::Display for ShapeWarning {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        write!(f, "warning at {}: {}", self.path, self.message)
111    }
112}
113
114// ── Internal helpers ──────────────────────────────────────────────────────────
115
116/// V1 known tier values. Unknown tiers produce a warning, not an error
117/// (cluster config may add custom tiers).
118const KNOWN_TIERS: &[&str] = &["public", "tenant", "private", "infra"];
119
120fn dns_label_re() -> &'static Regex {
121    static RE: OnceLock<Regex> = OnceLock::new();
122    RE.get_or_init(|| Regex::new(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$").unwrap())
123}
124
125fn env_name_re() -> &'static Regex {
126    static RE: OnceLock<Regex> = OnceLock::new();
127    RE.get_or_init(|| Regex::new(r"^[A-Z_][A-Z0-9_]*$").unwrap())
128}
129
130/// Validates a single DNS label: `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`, ≤ 63 chars.
131fn check_dns_label(value: &str, path: FieldPath) -> Result<(), ShapeError> {
132    if value.len() > 63 {
133        return Err(ShapeError::Field {
134            path,
135            reason: format!("length {} exceeds maximum 63", value.len()),
136        });
137    }
138    if !dns_label_re().is_match(value) {
139        return Err(ShapeError::Field {
140            path,
141            reason: format!(
142                "{:?} must match ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",
143                value
144            ),
145        });
146    }
147    Ok(())
148}
149
150/// Validates a dot-separated mesh identity where each segment is a DNS label.
151/// Total length ≤ 63. Example valid value: `"noisetable-api.pdx"`.
152fn check_mesh_ident(value: &str, path: FieldPath) -> Result<(), ShapeError> {
153    if value.len() > 63 {
154        return Err(ShapeError::Field {
155            path,
156            reason: format!("length {} exceeds maximum 63", value.len()),
157        });
158    }
159    for segment in value.split('.') {
160        if !dns_label_re().is_match(segment) {
161            return Err(ShapeError::Field {
162                path,
163                reason: format!(
164                    "segment {:?} in {:?} must match ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",
165                    segment, value
166                ),
167            });
168        }
169    }
170    Ok(())
171}
172
173/// The longest a port name may be. Matches IANA's service-name limit, which is
174/// what Kubernetes uses for the same field and what any tool that has to render
175/// a port name in a fixed column already assumes.
176const MESH_PORT_NAME_MAX: usize = 15;
177
178/// Validates `expose.mesh.ports` (R844-F17): every entry states something, every
179/// name is a DNS label short enough to be a service name, and nothing is
180/// declared twice.
181///
182/// The uniqueness rules are the load-bearing half. A repeated *name* would make
183/// `name -> port` ambiguous at exactly the moment a consumer asks for it —
184/// `ServiceRecord::port("http")` and the `PORT_HTTP` variable both resolve
185/// through that map — and a repeated *number* is a workload asking to bind one
186/// socket twice. Both are caught here rather than at bring-up because the
187/// author can still see the manifest.
188fn check_mesh_ports(
189    mesh: &crate::MeshExpose,
190    warnings: &mut Vec<ShapeWarning>,
191) -> Result<(), ShapeError> {
192    let mut seen_names: Vec<&str> = Vec::new();
193    let mut seen_numbers: Vec<u16> = Vec::new();
194
195    for (i, port) in mesh.ports.iter().enumerate() {
196        let path = FieldPath::MeshPort(i);
197
198        if port.name.is_none() && port.number.is_none() {
199            return Err(ShapeError::Field {
200                path,
201                reason: "declares neither a name nor a number — write a number \
202                         (8080), a name (\"http\"), or both \
203                         ({ name = \"http\", port = 8080 })"
204                    .to_string(),
205            });
206        }
207
208        if let Some(name) = port.name.as_deref() {
209            if name.len() > MESH_PORT_NAME_MAX {
210                return Err(ShapeError::Field {
211                    path,
212                    reason: format!(
213                        "port name {name:?} is {} characters; the maximum is \
214                         {MESH_PORT_NAME_MAX}",
215                        name.len()
216                    ),
217                });
218            }
219            if !dns_label_re().is_match(name) {
220                return Err(ShapeError::Field {
221                    path,
222                    reason: format!(
223                        "port name {name:?} must match \
224                         ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$"
225                    ),
226                });
227            }
228            if seen_names.contains(&name) {
229                return Err(ShapeError::Field {
230                    path,
231                    reason: format!(
232                        "port name {name:?} is declared twice; a name is how a \
233                         consumer selects one port, so it has to pick out \
234                         exactly one"
235                    ),
236                });
237            }
238            seen_names.push(name);
239        }
240
241        match port.number {
242            Some(number) => {
243                if seen_numbers.contains(&number) {
244                    return Err(ShapeError::Field {
245                        path,
246                        reason: format!(
247                            "port {number} is declared twice; a workload cannot \
248                             bind the same port on two listeners"
249                        ),
250                    });
251                }
252                seen_numbers.push(number);
253            }
254            // Still a warning rather than an error, but R844-F21 changed what
255            // it has to say. A name-only port IS allocated now — on the native
256            // backend, which owns the workload's network namespace: kamaji
257            // picks the number, remembers it per `(ident, name)` across a
258            // restart, and hands it to the process as `PORT_<NAME>`.
259            //
260            // It is still unbindable on a container backend, where the ports
261            // are the image's and both backends refuse the spelling outright
262            // (`kamaji::reject_unresolved_ports`). Shape validation cannot tell
263            // which backend a spec will land on — placement decides that later
264            // — so naming the split is the most this layer can honestly say,
265            // and it is why an error here would be wrong.
266            None => warnings.push(ShapeWarning {
267                path,
268                message: format!(
269                    "port {:?} declares no number: the native backend allocates \
270                     one and tells the process via PORT_{}, but a container \
271                     backend refuses it — a container's ports are its image's. \
272                     State the number ({{ name = {:?}, port = <n> }}) if this \
273                     workload runs as a container.",
274                    port.name.as_deref().unwrap_or_default(),
275                    port.name
276                        .as_deref()
277                        .unwrap_or_default()
278                        .to_uppercase()
279                        .replace(|c: char| !c.is_ascii_alphanumeric(), "_"),
280                    port.name.as_deref().unwrap_or_default(),
281                ),
282            }),
283        }
284    }
285
286    Ok(())
287}
288
289// ── Public API ────────────────────────────────────────────────────────────────
290
291/// Run shape validation — sync, no I/O.
292///
293/// Returns `Ok(warnings)` when all hard constraints pass; the `Vec` is empty
294/// for a clean spec. Returns `Err` on the first hard constraint violation.
295/// Callers that only need hard errors can discard the Ok value with
296/// `.map(|_| ())`.
297///
298/// Hard constraints checked:
299/// - `name`, `expose.mesh.identity`: DNS-label format, ≤ 63 chars.
300/// - `expose.operator.tailscale_tag`: `"tag:<dns-label>"`, ≤ 63 chars.
301/// - `replicas`: 0–100.
302/// - `image.tag`: non-empty when `digest` is `None`.
303/// - `volumes[*].source = Bind`: only allowed when `tier = "infra"`.
304/// - `expose.mesh.ports[*]`: each entry states a name and/or a number; names are
305///   DNS labels ≤ 15 chars; no name and no number is declared twice (R844-F17).
306/// - `expose.public.port`: must appear in `expose.mesh.ports`.
307/// - `secrets[*].target`: file paths must be absolute; env-var names must
308///   match `^[A-Z_][A-Z0-9_]*$`.
309///
310/// Soft checks (produce warnings, not errors):
311/// - `expose.mesh.ports[*]`: a name with no number — nothing allocates from the
312///   manifest yet, so nothing binds it (R844-F17).
313/// - Unknown tier value.
314/// - `RestartPolicy::Never` without `annotations["yah.forge"] = "true"`.
315/// - `healthcheck.initial_delay < stop_policy.grace_period * 2`.
316pub fn shape(spec: &WorkloadSpec) -> Result<Vec<ShapeWarning>, ShapeError> {
317    let mut warnings: Vec<ShapeWarning> = Vec::new();
318
319    // name: single DNS label, ≤ 63 chars
320    check_dns_label(&spec.name, FieldPath::Name)?;
321
322    // expose.mesh.identity: dot-separated DNS name, ≤ 63 total
323    check_mesh_ident(&spec.expose.mesh.identity.0, FieldPath::MeshIdentity)?;
324
325    // expose.operator.tailscale_tag: "tag:<dns-label>", ≤ 63 chars (optional)
326    if let Some(op) = &spec.expose.operator {
327        let tag = &op.tailscale_tag;
328        if tag.len() > 63 {
329            return Err(ShapeError::Field {
330                path: FieldPath::TailscaleTag,
331                reason: format!("length {} exceeds maximum 63", tag.len()),
332            });
333        }
334        let rest = tag.strip_prefix("tag:").ok_or_else(|| ShapeError::Field {
335            path: FieldPath::TailscaleTag,
336            reason: format!("{:?} must start with \"tag:\"", tag),
337        })?;
338        if !dns_label_re().is_match(rest) {
339            return Err(ShapeError::Field {
340                path: FieldPath::TailscaleTag,
341                reason: format!(
342                    "the part after \"tag:\" in {:?} must match \
343                     ^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",
344                    tag
345                ),
346            });
347        }
348    }
349
350    // replicas: 0..=100
351    if spec.replicas > 100 {
352        return Err(ShapeError::Field {
353            path: FieldPath::Replicas,
354            reason: format!("{} exceeds maximum 100", spec.replicas),
355        });
356    }
357
358    // image.tag: non-empty (informational identifier; digest is the source of
359    // truth and is structurally required at the type level).
360    if spec.image.tag.is_empty() {
361        return Err(ShapeError::Field {
362            path: FieldPath::ImageTag,
363            reason: "tag is empty; provide a human-readable tag alongside the digest".into(),
364        });
365    }
366
367    // tier: warn on unknown (cluster config may add custom tiers)
368    if !KNOWN_TIERS.contains(&spec.tier.0.as_str()) {
369        warnings.push(ShapeWarning {
370            path: FieldPath::Tier,
371            message: format!(
372                "\"{}\" is not in the known tier set (public/tenant/private/infra); \
373                 yubaba may reject it if the cluster config does not include this tier",
374                spec.tier.0
375            ),
376        });
377    }
378
379    // volumes[*]: Bind rejected unless tier = "infra"
380    for (i, vol) in spec.volumes.iter().enumerate() {
381        if matches!(&vol.source, VolumeSource::Bind { .. }) && spec.tier.0 != "infra" {
382            return Err(ShapeError::Field {
383                path: FieldPath::Volume(i, "source"),
384                reason: format!(
385                    "Bind mounts are only allowed when tier = \"infra\" \
386                     (current tier: {:?})",
387                    spec.tier.0
388                ),
389            });
390        }
391    }
392
393    // expose.mesh.ports[*]: names well-formed, nothing declared twice (R844-F17)
394    check_mesh_ports(&spec.expose.mesh, &mut warnings)?;
395
396    // expose.public.port must appear in expose.mesh.ports
397    if let Some(public) = &spec.expose.public {
398        if !spec.expose.mesh.declares_number(public.port) {
399            return Err(ShapeError::Field {
400                path: FieldPath::ExposeMeshPort(public.port),
401                reason: format!(
402                    "port {} must appear in expose.mesh.ports {:?} \
403                     before it can be exposed publicly",
404                    public.port,
405                    spec.expose.mesh.numbers()
406                ),
407            });
408        }
409    }
410
411    // secrets[*]: target paths absolute; env-var names valid identifiers
412    for (i, secret) in spec.secrets.iter().enumerate() {
413        match &secret.target {
414            SecretTarget::File { path, .. } => {
415                if !path.is_absolute() {
416                    return Err(ShapeError::Field {
417                        path: FieldPath::Secret(i, "target.path"),
418                        reason: format!("{:?} is not an absolute path", path),
419                    });
420                }
421            }
422            SecretTarget::EnvVar { name } => {
423                if !env_name_re().is_match(name) {
424                    return Err(ShapeError::Field {
425                        path: FieldPath::Secret(i, "target.name"),
426                        reason: format!(
427                            "{:?} is not a valid env-var identifier (^[A-Z_][A-Z0-9_]*$)",
428                            name
429                        ),
430                    });
431                }
432            }
433        }
434    }
435
436    // soft: RestartPolicy::Never without yah.forge=true annotation
437    if matches!(spec.restart_policy, RestartPolicy::Never) {
438        let is_forge = spec
439            .annotations
440            .get("yah.forge")
441            .map(|v| v == "true")
442            .unwrap_or(false);
443        if !is_forge {
444            warnings.push(ShapeWarning {
445                path: FieldPath::RestartPolicy,
446                message: "restart_policy=Never is intended for forge runs; \
447                          add annotation yah.forge=true to suppress this warning"
448                    .into(),
449            });
450        }
451    }
452
453    // soft: healthcheck.initial_delay >= stop_policy.grace_period * 2
454    if let Some(hc) = &spec.healthcheck {
455        let min_recommended = spec.stop_policy.grace_period.as_ms().saturating_mul(2);
456        if hc.initial_delay.as_ms() < min_recommended {
457            warnings.push(ShapeWarning {
458                path: FieldPath::Healthcheck("initial_delay"),
459                message: format!(
460                    "initial_delay ({}ms) is less than stop_policy.grace_period * 2 ({}ms); \
461                     a SIGTERM during startup may catch a still-initialising container",
462                    hc.initial_delay.as_ms(),
463                    min_recommended
464                ),
465            });
466        }
467    }
468
469    Ok(warnings)
470}
471
472// ── StaticAsset validator ─────────────────────────────────────────────────────
473
474/// Shape-validate a `kind = "static-asset"` workload.
475///
476/// Enforces the closed-catalog invariant: every value in `[aliases]` must be a
477/// `filename` present in `[[asset]]`. A mirror's `[asset_aliases]` overrides
478/// are bound by the same rule and are validated separately at sync time when
479/// both the workload and mirror are loaded together.
480pub fn shape_static_asset(workload: &StaticAssetWorkload) -> Result<(), ShapeError> {
481    // XOR rule (W164 / R438-T2): every [[asset]] row must set exactly one of
482    // `source` (legacy local bytes) or `derive` (fetch + optional transform).
483    // Both-set is ambiguous (which one wins?); neither-set leaves the
484    // reconciler with no bytes to upload.
485    for (i, entry) in workload.assets.iter().enumerate() {
486        match (entry.source.is_some(), entry.derive.is_some()) {
487            (true, true) => {
488                return Err(ShapeError::Field {
489                    path: FieldPath::Asset(i, "source"),
490                    reason: format!(
491                        "asset {:?}: both `source` and `derive` are set; pick exactly one",
492                        entry.filename
493                    ),
494                });
495            }
496            (false, false) => {
497                return Err(ShapeError::Field {
498                    path: FieldPath::Asset(i, "source"),
499                    reason: format!(
500                        "asset {:?}: neither `source` nor `derive` is set; pick exactly one",
501                        entry.filename
502                    ),
503                });
504            }
505            _ => {}
506        }
507    }
508
509    let filenames: std::collections::HashSet<&str> =
510        workload.assets.iter().map(|a| a.filename.as_str()).collect();
511
512    for (alias_key, alias_target) in &workload.aliases {
513        if !filenames.contains(alias_target.as_str()) {
514            return Err(ShapeError::Field {
515                path: FieldPath::AssetAlias(alias_key.clone()),
516                reason: format!(
517                    "alias target {:?} is not present in the [[asset]] catalog; \
518                     add a matching [[asset]] row or correct the filename",
519                    alias_target
520                ),
521            });
522        }
523    }
524
525    Ok(())
526}
527
528// ── Semantic layer ────────────────────────────────────────────────────────────
529
530/// Transient error from a [`ValidationContext`] lookup.
531///
532/// Distinct from a semantic "resource not found" failure. `ContextError` means
533/// the lookup itself could not complete (network timeout, auth failure, etc.),
534/// not that the resource is definitively absent.
535#[derive(Debug, Error, Clone, PartialEq)]
536#[error("context lookup failed: {0}")]
537pub struct ContextError(pub String);
538
539/// A semantic constraint violation: the spec references a resource that is not
540/// known to the cluster at validation time.
541#[derive(Debug, Error, PartialEq)]
542pub enum SemanticError {
543    #[error("field {path}: {reason}")]
544    Unknown { path: FieldPath, reason: String },
545}
546
547/// Top-level validation error spanning both shape and semantic layers.
548///
549/// `Shape` always wins: if the spec is structurally invalid, semantic checks
550/// never run.
551#[derive(Debug, Error, PartialEq)]
552pub enum WorkloadValidationError {
553    /// Hard shape constraint failed — spec is structurally invalid.
554    #[error("shape: {0}")]
555    Shape(ShapeError),
556
557    /// Semantic check failed — spec references an unknown cluster resource.
558    #[error("semantic: {0}")]
559    Semantic(SemanticError),
560
561    /// Transient ValidationContext lookup failure — the check itself failed.
562    #[error("context: {0}")]
563    Context(ContextError),
564}
565
566impl From<ShapeError> for WorkloadValidationError {
567    fn from(e: ShapeError) -> Self { WorkloadValidationError::Shape(e) }
568}
569
570impl From<ContextError> for WorkloadValidationError {
571    fn from(e: ContextError) -> Self { WorkloadValidationError::Context(e) }
572}
573
574/// Read-only view of yubaba state used for semantic validation.
575///
576/// Defined here so clients (desktop, CLI, agents) can run semantic checks
577/// without depending on the yubaba crate. Yubaba implements this trait.
578///
579/// Each method returns `Result<bool, ContextError>` so transient failures are
580/// distinguishable from definitive "not found" answers.
581pub trait ValidationContext {
582    /// True when the registry confirms the image exists.
583    fn image_exists(&self, image: &ImageRef) -> Result<bool, ContextError>;
584
585    /// True when the named secret exists in the yubaba secret store.
586    fn secret_exists(&self, secret: &SecretRef) -> Result<bool, ContextError>;
587
588    /// True when `ident` is a known deployed workload OR appears in `batch`
589    /// (the set of specs co-deployed in the same request — allows forward
590    /// references within a single deployment batch).
591    fn mesh_ident_known(&self, ident: &MeshIdent, batch: &[MeshIdent]) -> Result<bool, ContextError>;
592
593    /// True when `hostname` falls under a Cloudflare zone owned by this cluster.
594    fn cf_zone_owned(&self, hostname: &str) -> Result<bool, ContextError>;
595
596    /// True when `tag` (e.g. `"tag:noisetable-ops"`) is in the cluster's
597    /// Tailscale ACL tag list.
598    fn tailscale_tag_known(&self, tag: &str) -> Result<bool, ContextError>;
599
600    /// True when `machine_id` has sufficient remaining capacity to host the
601    /// given spec's resource requirements.
602    ///
603    /// Implementors: read memory via [`WorkloadSpec::memory_request_mb`], not
604    /// `spec.resources.memory_mb`. The latter is a cgroup ceiling, and using
605    /// it as a capacity floor is what made every build-worker smaller than
606    /// `for_forge`'s 32 GiB ceiling unschedulable in `admit_workload`. Only a
607    /// test implementation of this trait exists today, so the bug is not live
608    /// here — this note is to keep it from arriving with the first real one.
609    fn capacity_for(&self, spec: &WorkloadSpec, machine_id: &MachineId) -> Result<bool, ContextError>;
610}
611
612/// Run semantic validation — requires yubaba state via [`ValidationContext`].
613///
614/// Shape validation is NOT run here. Callers MUST run [`shape`] first; use
615/// [`all`] to enforce this automatically.
616///
617/// `machine_id` is the target machine for admission-control capacity checks.
618/// `batch` is the set of mesh idents being co-deployed (pass `&[]` for
619/// single-spec deployment); these count as "known" for `depends_on` resolution.
620pub fn semantic(
621    spec: &WorkloadSpec,
622    ctx: &dyn ValidationContext,
623    machine_id: &MachineId,
624    batch: &[MeshIdent],
625) -> Result<(), WorkloadValidationError> {
626    if !ctx.image_exists(&spec.image)? {
627        return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
628            path: FieldPath::Image,
629            reason: format!(
630                "image {}/{}:{} not found in registry",
631                spec.image.registry, spec.image.repository, spec.image.tag
632            ),
633        }));
634    }
635
636    for (i, secret) in spec.secrets.iter().enumerate() {
637        if !ctx.secret_exists(&secret.source)? {
638            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
639                path: FieldPath::Secret(i, "source"),
640                reason: format!("secret source at index {i} not found in yubaba secret store"),
641            }));
642        }
643    }
644
645    for (i, dep) in spec.depends_on.iter().enumerate() {
646        if !ctx.mesh_ident_known(dep, batch)? {
647            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
648                path: FieldPath::DependsOn(i),
649                reason: format!("mesh ident {:?} is not a known deployed workload", dep.0),
650            }));
651        }
652    }
653
654    if let Some(public) = &spec.expose.public {
655        if !ctx.cf_zone_owned(&public.hostname)? {
656            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
657                path: FieldPath::Hostname,
658                reason: format!(
659                    "hostname {:?} is not under a Cloudflare zone owned by this cluster",
660                    public.hostname
661                ),
662            }));
663        }
664    }
665
666    if let Some(op) = &spec.expose.operator {
667        if !ctx.tailscale_tag_known(&op.tailscale_tag)? {
668            return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
669                path: FieldPath::TailscaleTag,
670                reason: format!(
671                    "tailscale tag {:?} is not in the cluster's ACL tag list",
672                    op.tailscale_tag
673                ),
674            }));
675        }
676    }
677
678    if !ctx.capacity_for(spec, machine_id)? {
679        return Err(WorkloadValidationError::Semantic(SemanticError::Unknown {
680            path: FieldPath::Resources,
681            reason: format!(
682                "machine {:?} lacks capacity (memory={}MB cpu_millis={} ephemeral={}MB)",
683                machine_id.0,
684                spec.resources.memory_mb,
685                spec.resources.cpu_millis,
686                spec.resources.ephemeral_storage_mb
687            ),
688        }));
689    }
690
691    Ok(())
692}
693
694// ── Mesh resolution layer ─────────────────────────────────────────────────────
695
696/// Failure surface for [`MeshResolver`] lookups.
697///
698/// `NotDeployed` means the dependency hasn't been observed in mesh state yet
699/// (yubaba's deploy step waits on this — see [`crate::EnvValue::FromMesh`]).
700/// `NoPorts` means the dependency is deployed but its `MeshExpose.ports`
701/// list is empty, so a port-based lookup can't render a value. `Lookup`
702/// covers transient failures from the underlying state read.
703#[derive(Debug, Error, Clone, PartialEq)]
704pub enum MeshError {
705    #[error("mesh ident {ident:?} is not yet deployed")]
706    NotDeployed { ident: String },
707
708    #[error(
709        "mesh ident {ident:?} exposes no ports; {lookup:?} requires at least one"
710    )]
711    NoPorts { ident: String, lookup: MeshLookup },
712
713    /// The peer exposes several ports and the lookup did not say which
714    /// (R844-B22). Deliberately an error rather than a pick — see
715    /// [`MeshLookup`]'s docs.
716    #[error(
717        "mesh ident {ident:?} exposes {} ports ({}) and none is named \"http\", \
718         so {lookup:?} cannot say which one to use. Name the port in the \
719         lookup (kind = \"port_named\", name = \"…\"), or name one of the \
720         peer's ports \"http\" in its expose.mesh.ports.",
721        .names.len(),
722        .names.join(", ")
723    )]
724    AmbiguousPort {
725        ident: String,
726        lookup: MeshLookup,
727        names: Vec<String>,
728    },
729
730    /// The lookup named a port the peer does not expose (R844-B22).
731    #[error(
732        "mesh ident {ident:?} exposes no port named {name:?}; it has {}",
733        if .available.is_empty() { "none".to_string() } else { .available.join(", ") }
734    )]
735    NoSuchPort {
736        ident: String,
737        name: String,
738        available: Vec<String>,
739    },
740
741    #[error("mesh state lookup failed: {0}")]
742    Lookup(String),
743}
744
745/// The port name a peer's sole/default listener carries. Agrees with
746/// `kamaji::DEFAULT_PORT_NAME` by convention rather than by import: kamaji sits
747/// *above* workload-spec in the publish DAG (`yah-base <- {qed,kamaji} <-
748/// yubaba`), so depending on it here would invert the graph. The two are pinned
749/// together by `default_port_name_agrees_with_the_supervisor` in this file's
750/// tests.
751pub const DEFAULT_PORT_NAME: &str = "http";
752
753/// Pick the port a [`MeshLookup`] refers to out of a peer's `name -> port` map
754/// (R844-B22) — the one place the rule lives, so every resolver answers the
755/// same way.
756///
757/// - A **named** lookup takes that port, or errors naming what the peer does
758///   have. No fallback: a lookup that asked for `wss` and silently got `http`
759///   would be the positional guess wearing a name.
760/// - An **unnamed** lookup takes the sole port when there is one, else the port
761///   named [`DEFAULT_PORT_NAME`], else errors. It never takes "the first",
762///   which is what this function exists to stop.
763pub fn select_mesh_port(
764    ident: &str,
765    ports: &std::collections::BTreeMap<String, u16>,
766    lookup: &MeshLookup,
767) -> Result<u16, MeshError> {
768    if let Some(name) = lookup.port_name() {
769        return ports.get(name).copied().ok_or_else(|| MeshError::NoSuchPort {
770            ident: ident.to_string(),
771            name: name.to_string(),
772            available: ports.keys().cloned().collect(),
773        });
774    }
775
776    let mut entries = ports.iter();
777    match (entries.next(), entries.next()) {
778        (None, _) => Err(MeshError::NoPorts {
779            ident: ident.to_string(),
780            lookup: lookup.clone(),
781        }),
782        (Some((_, &only)), None) => Ok(only),
783        _ => ports
784            .get(DEFAULT_PORT_NAME)
785            .copied()
786            .ok_or_else(|| MeshError::AmbiguousPort {
787                ident: ident.to_string(),
788                lookup: lookup.clone(),
789                names: ports.keys().cloned().collect(),
790            }),
791    }
792}
793
794/// Resolve [`crate::EnvValue::FromMesh`] references to literal env values.
795///
796/// Defined in workload-spec so clients (agents, desktop, CLI) can render
797/// specs against fake mesh state without depending on the yubaba crate.
798/// Yubaba's production implementation (in `yubaba::deploy::mesh_resolve`)
799/// reads from raft state.
800///
801/// **Resolution rules** (R844-B22 replaced the positional ones):
802/// - [`MeshLookup::Host`] — the bare DNS-ish identifier as authored (e.g.
803///   `"noisetable-db.pdx"`). Needs no port and resolves for a portless peer.
804/// - [`MeshLookup::Url`] — `"http://<ident>:<port>"`.
805/// - [`MeshLookup::Port`] — that port stringified, e.g. `"5432"`.
806/// - [`MeshLookup::UrlNamed`] / [`MeshLookup::PortNamed`] — the same, at the
807///   peer's port of that name.
808///
809/// **Which port** is [`select_mesh_port`]'s decision, and implementations must
810/// route through it rather than re-deriving: a sole port, else the one named
811/// [`DEFAULT_PORT_NAME`], else an error. It is emphatically *not* "the first
812/// entry", which is what this trait's doc used to promise — declaration order
813/// is not a statement about which listener a dependent should dial, and acting
814/// as if it were is how a workload gets handed a metrics port as its API URL.
815///
816/// Because the rule is name-based rather than positional, a `Url` and a `Port`
817/// resolved in the same deploy agree by construction; the old doc had to ask
818/// implementations to make the lookup atomic to get that.
819pub trait MeshResolver {
820    fn resolve(&self, ident: &MeshIdent, kind: MeshLookup) -> Result<String, MeshError>;
821}
822
823/// Render every [`EnvValue::FromMesh`] entry in `env` to a [`EnvValue::Literal`]
824/// using `resolver`; pass through `Literal` and `FromSecret` values unchanged.
825///
826/// Returns the first resolution error encountered. Callers should run this
827/// after yubaba's stage-3 mesh peering completes (see
828/// `yubaba::deploy::env_validate::run` doc), at containerd-spec assembly.
829///
830/// `FromSecret` values are deliberately untouched here — secret resolution
831/// is the secrets layer's job (R090-F5), not the mesh resolver's.
832///
833/// @yah:ticket(R844-B22, "MeshLookup::Url and ::Port resolve &quot;the first entry in expose.mesh.ports&quot; — the positional guess this relay abolishes, in the env-injection path")
834/// @yah:status(review)
835/// @yah:at(2026-09-04T14:10:34Z)
836/// @yah:assignee(agent:bundle-anthropic-ashguard)
837/// @yah:parent(R844)
838/// @yah:severity(medium)
839/// @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://&lt;ident&gt;:&lt;port&gt;\\\"` 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.")
840/// @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.")
841/// @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.")
842/// @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.")
843/// @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.")
844/// @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.")
845/// @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.")
846/// @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`.")
847/// @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.")
848/// @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.")
849/// @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.")
850/// @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.")
851pub fn resolve_env_from_mesh(
852    env: &[EnvVar],
853    resolver: &dyn MeshResolver,
854) -> Result<Vec<EnvVar>, MeshError> {
855    env.iter()
856        .map(|var| match &var.value {
857            EnvValue::FromMesh { ident, kind } => {
858                let value = resolver.resolve(ident, kind.clone())?;
859                Ok(EnvVar {
860                    name: var.name.clone(),
861                    value: EnvValue::Literal { value },
862                })
863            }
864            _ => Ok(var.clone()),
865        })
866        .collect()
867}
868
869/// Run shape then semantic validation in the correct order.
870///
871/// Shape always runs first. If shape fails, `WorkloadValidationError::Shape`
872/// is returned and semantic checks are skipped — callers never see a
873/// `Semantic` error for a structurally invalid spec.
874///
875/// `machine_id` is forwarded to the capacity admission-control check.
876/// `batch` is the set of co-deployed mesh idents for forward-reference
877/// resolution; pass `&[]` for single-spec deployment.
878pub fn all(
879    spec: &WorkloadSpec,
880    ctx: &dyn ValidationContext,
881    machine_id: &MachineId,
882    batch: &[MeshIdent],
883) -> Result<(), WorkloadValidationError> {
884    shape(spec)?;
885    semantic(spec, ctx, machine_id, batch)
886}