tatara-process 0.2.574

Process CRD — K8s clusters, workloads, migrations, tests as Unix processes in the tatara convergence lattice
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//! Hostname helpers — typed FQDN formatting matching `nix/lib/fleet-
//! domains.nix`'s `mkHostname` pattern.
//!
//! The substrate move: every FQDN this codebase emits is computed
//! here. Two functions ([`fmt_fqdn`] for the per-instance form +
//! [`fmt_fqdn_stable`] for the unprefixed stable-claim form) and one
//! deterministic ephemeral-id derivation ([`ephemeral_id_from_spec`])
//! are the single source of truth — no string `format!()` of DNS
//! syntax anywhere else in the tree.
//!
//! Forms:
//!
//! ```text
//!   Per-instance: ${app}.${ephemeral_id}.${cluster}.${location}.${domain}
//!   Stable:       ${app}.${cluster}.${location}.${domain}
//! ```
//!
//! Where `${ephemeral_id}` is:
//!
//! * `RoutingHostname.instance` when set — a named slot like
//!   `demo-prod` or `pr-1234`.
//! * `EPHEMERAL_ID_HASH_LEN` (= 8) hex chars of
//!   `BLAKE3(canonical_spec_json)` when unset — a content-hash slot
//!   that changes only when the Process's spec changes.
//!
//! All four FQDN segments are validated as RFC 1123 DNS labels at
//! the boundary — lowercase alphanumeric + hyphen, 1–63 chars, no
//! leading/trailing hyphen. Validation errors surface as typed
//! [`HostnameError`] variants so callers can render targeted
//! operator messages.

use serde::Serialize;

use crate::routing::RoutingHostname;

/// Number of hex chars from BLAKE3 to use as the content-hash form
/// of `ephemeral_id`. 8 = 32 bits of entropy; collision probability
/// at 1k concurrent Processes ≈ 1 in 8.5 million. Comfortable for
/// any single cluster's working set, room to grow.
pub const EPHEMERAL_ID_HASH_LEN: usize = 8;

/// Reserved 2-part forms forbidden as `app` values (saguão control
/// plane — see pleme-io CLAUDE.md §Fleet hostname pattern).
const RESERVED_APP_LABELS: &[&str] = &["auth", "cracha"];

/// Why a hostname can't be formatted. Typed so callers can branch.
#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum HostnameError {
    #[error("invalid DNS label {label:?} for segment {segment}: {reason}")]
    InvalidLabel {
        segment: &'static str,
        label: String,
        reason: &'static str,
    },
    #[error("app label {0:?} is reserved for the saguão control plane")]
    ReservedApp(String),
}

/// Substrate extension trait over `Result<T, HostnameError>` — the ONE
/// substrate owner of the `.map_err(|e| anyhow::anyhow!("<ctx>: {e}"))`
/// wrap-shape every reconciler consumer restated by hand at the
/// hostname-formatter → anyhow error boundary. Peer of
/// [`crate::kube_error::KubeResultExt`] on the wrap-shape axis; the two
/// traits partition the flatten-wrap space by underlying error type
/// (`kube::Error` on that peer, [`HostnameError`] on this one).
///
/// Pre-lift the shape was hand-authored at THREE sites in
/// `tatara-reconciler::render::render_routing` — each of the three
/// `HostnameError`-returning hostname primitives ([`ephemeral_id_from_spec`],
/// [`fmt_fqdn`], [`fmt_fqdn_stable`]) had ITS consumer restate the
/// SAME closure at the R9 routing-edge render — capture the
/// [`HostnameError`], prepend a static context slug identifying which
/// hostname primitive faulted, delegate the tail to [`HostnameError`]'s
/// `Display` impl via the `{e}` slot — differing only in the context
/// slug prefix each callsite stamped (`"ephemeral_id_from_spec"` /
/// `"fmt_fqdn (per-instance)"` / `"fmt_fqdn_stable"`). Three
/// hand-authored callsites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
/// threshold.
///
/// Post-lift each callsite reads
/// `<hostname-primitive>().hostname_ctx("<slug>")?` and the wrap-shape
/// lives at ONE substrate owner here. The composed [`anyhow::Error`]'s
/// `Display` is byte-identical to the pre-lift chain
/// (`format!("{ctx}: {e}")`, threading the [`HostnameError`]'s own
/// `Display` verbatim into the `{e}` slot), so operator-facing log
/// output and any error-chain greps still match bytewise. A regression
/// that drifts the separator, swaps the two slots, or wraps the
/// [`HostnameError`] with a chain-form `source` (which would change
/// `Display` output on the `err` slot) surfaces at
/// [`tests::hostname_ctx_static_str_context_matches_pre_lift_format_bytewise`]
/// rather than as silent operator-facing drift across the three
/// pre-lift consumers.
///
/// ### Naming — `hostname_ctx`, not `anyhow::Context::context`
///
/// Same discipline as [`crate::kube_error::KubeResultExt::kube_ctx`] —
/// `anyhow::Context::context` wraps the source in a chain (so `Display`
/// emits only the context slug and callers reach the [`HostnameError`]
/// via [`std::error::Error::source`] traversal), while this trait's
/// `hostname_ctx` FLATTENS to a display-prefix shape (`"<ctx>: <HostnameError
/// display>"`) — the pre-lift wire format every consumer's log output
/// already encoded. Sharing the name would let a caller who has
/// `anyhow::Context` in scope resolve to the WRONG method (a chain-wrap
/// instead of the display-prefix flatten) and silently change every
/// operator log message.
///
/// ### Static-slug only (no `_with` peer yet)
///
/// Every current callsite composes its slug at compile time
/// (`"ephemeral_id_from_spec"`, `"fmt_fqdn (per-instance)"`,
/// `"fmt_fqdn_stable"`); no consumer needs a `format!`-composed
/// runtime slug. The static-`&'static str` binding keeps the substrate
/// contract minimal — a future dynamic-slug consumer would add a
/// `hostname_ctx_with` peer here matching the `kube_ctx_with` shape,
/// but until then this trait exposes only the static peer.
///
/// ### `#[must_use]`
///
/// Every consumer threads the `?` short-circuit onto its handler's
/// `Result<_, anyhow::Error>` return — dropping the wrap swallows the
/// hostname-format failure entirely, which is never the intended
/// semantic (a rejected DNS label at emit time silently produces a
/// resource with a `""` FQDN slot that the K8s API server accepts and
/// then no downstream Ingress / DNSEndpoint dispatcher can route to).
/// The attribute surfaces that as a warning at every call site.
///
/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
/// [`HostnameError`] → anyhow-with-display-prefix wrap-shape recurred
/// at three hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
/// duplication trigger, and is lifted to ONE substrate owner here).
/// THEORY.md §II.1 invariant 5 (composition preserves proofs — a
/// regression that drifts the display-prefix separator or the byte-
/// shape at ONE site surfaces here at the substrate pin rather than
/// as silent operator-facing skew across every render_routing tick).
pub trait HostnameResultExt<T>: Sized {
    /// Wrap the [`HostnameError`] (if any) with a static context
    /// prefix, producing an [`anyhow::Result`] whose error `Display`
    /// reads exactly `"<context>: <HostnameError display>"`.
    #[must_use = "an error wrap that isn't threaded via `?` swallows the hostname-format failure"]
    fn hostname_ctx(self, context: &'static str) -> anyhow::Result<T>;
}

impl<T> HostnameResultExt<T> for Result<T, HostnameError> {
    #[inline]
    fn hostname_ctx(self, context: &'static str) -> anyhow::Result<T> {
        self.map_err(|e| anyhow::anyhow!("{context}: {e}"))
    }
}

/// Format the per-instance FQDN.
///
/// ```
/// use tatara_process::hostname::fmt_fqdn;
/// let fqdn = fmt_fqdn("api", "demo-prod", "pleme-dev", "use1", "quero.lol").unwrap();
/// assert_eq!(fqdn, "api.demo-prod.pleme-dev.use1.quero.lol");
/// ```
pub fn fmt_fqdn(
    app: &str,
    ephemeral_id: &str,
    cluster: &str,
    location: &str,
    domain: &str,
) -> Result<String, HostnameError> {
    validate_app(app)?;
    validate_label("ephemeral_id", ephemeral_id)?;
    validate_label("cluster", cluster)?;
    validate_label("location", location)?;
    validate_domain("domain", domain)?;
    Ok(format!(
        "{app}.{ephemeral_id}.{cluster}.{location}.{domain}"
    ))
}

/// Format the stable-claim FQDN (no `ephemeral_id` segment).
///
/// ```
/// use tatara_process::hostname::fmt_fqdn_stable;
/// let fqdn = fmt_fqdn_stable("api", "pleme-dev", "use1", "quero.lol").unwrap();
/// assert_eq!(fqdn, "api.pleme-dev.use1.quero.lol");
/// ```
pub fn fmt_fqdn_stable(
    app: &str,
    cluster: &str,
    location: &str,
    domain: &str,
) -> Result<String, HostnameError> {
    validate_app(app)?;
    validate_label("cluster", cluster)?;
    validate_label("location", location)?;
    validate_domain("domain", domain)?;
    Ok(format!("{app}.{cluster}.{location}.{domain}"))
}

/// Compute the content-hash form of `ephemeral_id` for a given
/// `ProcessSpec`. Stable across reconciles of the same spec; new
/// spec content ⇒ new hash ⇒ new DNS slot.
///
/// Uses [`EPHEMERAL_ID_HASH_LEN`] hex chars of BLAKE3 over the
/// canonical JSON of the spec.
pub fn ephemeral_id_from_spec<T: Serialize>(spec: &T) -> Result<String, HostnameError> {
    // Canonical-bytes projection rides through the ONE substrate
    // primitive [`crate::three_pillar::canonical_bytes`] — the
    // strict, error-propagating peer of `three_pillar::pillar_bytes`
    // that owns the 2-link `serde_json::to_value → serde_json::to_vec`
    // canonicalization chain. Pre-lift this site read through a
    // module-private `canonical_json` helper (removed) that restated
    // the same 2-link chain byte-for-byte alongside the peer at
    // `tatara-export-worker::canonical_json` — two hand-authored
    // sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold.
    // Post-lift both consumers name the payload ONCE and route
    // through the ONE substrate owner; the discard of the concrete
    // `serde_json::Error` diagnostic rides through the local
    // `HostnameError::InvalidLabel` projection at this callsite so
    // the operator-facing wording stays byte-identical to the
    // pre-lift shape.
    let bytes =
        crate::three_pillar::canonical_bytes(spec).map_err(|_| HostnameError::InvalidLabel {
            segment: "spec",
            label: "<unserializable>".into(),
            reason: "spec failed to canonicalize",
        })?;
    Ok(short_hex_blake3(&bytes, EPHEMERAL_ID_HASH_LEN))
}

/// Resolve the `ephemeral_id` for a single [`RoutingHostname`]
/// entry. Named slot wins if set; otherwise the content-hash form
/// is computed from the surrounding `ProcessSpec` (caller passes
/// in via `fallback_hash`).
///
/// The split-arg design keeps this pure — the spec hash is computed
/// once by the caller (via [`ephemeral_id_from_spec`]) and reused
/// across every hostname on the same Process.
pub fn resolve_ephemeral_id<'a>(hostname: &'a RoutingHostname, fallback_hash: &'a str) -> &'a str {
    match &hostname.instance {
        Some(s) if !s.is_empty() => s.as_str(),
        _ => fallback_hash,
    }
}

// ─── Validation ────────────────────────────────────────────────────

fn validate_label(segment: &'static str, label: &str) -> Result<(), HostnameError> {
    if label.is_empty() || label.len() > 63 {
        return Err(HostnameError::InvalidLabel {
            segment,
            label: label.to_string(),
            reason: "must be 1–63 characters",
        });
    }
    if label.starts_with('-') || label.ends_with('-') {
        return Err(HostnameError::InvalidLabel {
            segment,
            label: label.to_string(),
            reason: "must not start or end with a hyphen",
        });
    }
    if !label
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
    {
        return Err(HostnameError::InvalidLabel {
            segment,
            label: label.to_string(),
            reason: "must contain only [a-z0-9-]",
        });
    }
    Ok(())
}

/// Validate a caller-supplied `app` label at the fleet-hostname
/// boundary — the ONE substrate primitive owning the two-step (RFC 1123
/// DNS label + saguão-reservation reject) check every hostname composer
/// runs on its `app` slot BEFORE stamping it into an emitted FQDN.
///
/// Pre-lift the two-step check was hand-authored at TWO adjacent public
/// FQDN composers in this module past the ★★ PRIME-DIRECTIVE ≥ 2
/// duplication threshold:
///
/// * [`fmt_fqdn`] — the per-instance form; the 4-line prelude
///   preceded the sibling `validate_label("ephemeral_id", …)` +
///   cluster / location / domain checks.
/// * [`fmt_fqdn_stable`] — the unprefixed stable-claim form; the same
///   4-line prelude preceded the cluster / location / domain checks
///   with no `ephemeral_id` slot in between.
///
/// Both restated the SAME 4-line prelude verbatim: (1)
/// `validate_label("app", app)?` to enforce the RFC 1123 shape (1–63
/// chars, lowercase alphanumeric + hyphen, no leading / trailing
/// hyphen), then (2) an early-return
/// `HostnameError::ReservedApp(app.to_string())` when the label
/// appears in the module-private [`RESERVED_APP_LABELS`] set
/// (currently `"auth"` / `"cracha"` — the saguão control-plane
/// reservations declared in pleme-io CLAUDE.md § Fleet hostname
/// pattern).
///
/// Post-lift each callsite reads `validate_app(app)?` and the ordered
/// two-step check lives at ONE substrate owner. The step ORDER is
/// load-bearing: `validate_label` runs first so a reserved label whose
/// spelling ALSO violates RFC 1123 (an operator who typed `"AUTH"`
/// instead of `"auth"`) surfaces as
/// [`HostnameError::InvalidLabel`] (the underlying shape defect),
/// not as [`HostnameError::ReservedApp`] (the higher-level policy
/// gate) — matching the pre-lift order both composers hand-authored.
/// A regression that swapped the two steps would silently re-classify
/// every such input and callers pattern-matching on the two variants
/// would branch differently.
///
/// A future extension to the reserved set (adding a third saguão name,
/// a per-cluster reservation surface, a normalized-form lookup that
/// treats `"Auth"` and `"auth"` as the same reservation) lands at THIS
/// ONE substrate primitive and both [`fmt_fqdn`] + [`fmt_fqdn_stable`]
/// inherit the upgrade mechanically — no per-composer edit at either
/// call site, no drift risk for a third future FQDN-shape composer
/// that plugs into the same reservation policy.
///
/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
/// 4-line two-step check recurred at two hand-authored composer
/// preludes past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger and
/// lifts to ONE substrate owner here). THEORY.md §II.1 invariant 5
/// (composition preserves proofs — the pin block below binds the
/// primitive at fail-before-pass-after granularity so a regression
/// that reorders the two steps, drops one, or drifts the typed error
/// variant surfaces at THESE pins rather than as silent fleet-
/// hostname skew across every downstream FQDN emit).
fn validate_app(app: &str) -> Result<(), HostnameError> {
    validate_label("app", app)?;
    if RESERVED_APP_LABELS.contains(&app) {
        return Err(HostnameError::ReservedApp(app.to_string()));
    }
    Ok(())
}

fn validate_domain(segment: &'static str, domain: &str) -> Result<(), HostnameError> {
    if domain.is_empty() {
        return Err(HostnameError::InvalidLabel {
            segment,
            label: domain.to_string(),
            reason: "must not be empty",
        });
    }
    // Multi-label domain — every dot-separated piece must be a valid label.
    for piece in domain.split('.') {
        validate_label(segment, piece)?;
    }
    Ok(())
}

fn short_hex_blake3(bytes: &[u8], len: usize) -> String {
    // Delegate the 2-link `blake3::hash → hex` step to the substrate
    // primitive so the ephemeral-id prefix stays byte-identical to
    // every receipt/attestation hex-digest workspace-wide; take a
    // stable prefix of the shared full-length hex.
    crate::hash::hex_blake3(bytes).chars().take(len).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Deserialize;

    #[test]
    fn fmt_fqdn_per_instance() {
        let f = fmt_fqdn("api", "demo-prod", "pleme-dev", "use1", "quero.lol").unwrap();
        assert_eq!(f, "api.demo-prod.pleme-dev.use1.quero.lol");
    }

    #[test]
    fn fmt_fqdn_stable_form() {
        let f = fmt_fqdn_stable("api", "pleme-dev", "use1", "quero.lol").unwrap();
        assert_eq!(f, "api.pleme-dev.use1.quero.lol");
    }

    #[test]
    fn fmt_fqdn_with_multilevel_domain() {
        let f = fmt_fqdn("api", "env-a", "rio", "us", "internal.example.com").unwrap();
        assert_eq!(f, "api.env-a.rio.us.internal.example.com");
    }

    #[test]
    fn reserved_app_rejected() {
        let r = fmt_fqdn("auth", "x", "y", "z", "example.com");
        assert!(matches!(r, Err(HostnameError::ReservedApp(_))));
        let r = fmt_fqdn_stable("cracha", "y", "z", "example.com");
        assert!(matches!(r, Err(HostnameError::ReservedApp(_))));
    }

    #[test]
    fn empty_label_rejected() {
        let r = fmt_fqdn("", "x", "y", "z", "example.com");
        assert!(matches!(
            r,
            Err(HostnameError::InvalidLabel { segment: "app", .. })
        ));
    }

    #[test]
    fn too_long_label_rejected() {
        let long = "a".repeat(64);
        let r = fmt_fqdn(&long, "x", "y", "z", "example.com");
        assert!(matches!(r, Err(HostnameError::InvalidLabel { .. })));
    }

    #[test]
    fn uppercase_label_rejected() {
        let r = fmt_fqdn("API", "x", "y", "z", "example.com");
        assert!(matches!(r, Err(HostnameError::InvalidLabel { .. })));
    }

    #[test]
    fn leading_hyphen_label_rejected() {
        let r = fmt_fqdn("api", "-bad", "y", "z", "example.com");
        assert!(matches!(r, Err(HostnameError::InvalidLabel { .. })));
    }

    #[test]
    fn underscore_label_rejected() {
        let r = fmt_fqdn("api", "x_y", "z", "w", "example.com");
        assert!(matches!(r, Err(HostnameError::InvalidLabel { .. })));
    }

    #[test]
    fn empty_domain_rejected() {
        let r = fmt_fqdn("api", "x", "y", "z", "");
        assert!(matches!(r, Err(HostnameError::InvalidLabel { .. })));
    }

    // ─── Content-hash derivation ─────────────────────────────────

    #[derive(Serialize, Deserialize)]
    struct TestSpec {
        a: u32,
        b: String,
    }

    #[test]
    fn ephemeral_id_is_8_hex_chars() {
        let spec = TestSpec {
            a: 1,
            b: "x".into(),
        };
        let id = ephemeral_id_from_spec(&spec).unwrap();
        assert_eq!(id.len(), EPHEMERAL_ID_HASH_LEN);
        assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn ephemeral_id_is_deterministic() {
        let s1 = TestSpec {
            a: 1,
            b: "x".into(),
        };
        let s2 = TestSpec {
            a: 1,
            b: "x".into(),
        };
        assert_eq!(
            ephemeral_id_from_spec(&s1).unwrap(),
            ephemeral_id_from_spec(&s2).unwrap()
        );
    }

    #[test]
    fn ephemeral_id_changes_with_spec() {
        let s1 = TestSpec {
            a: 1,
            b: "x".into(),
        };
        let s2 = TestSpec {
            a: 2,
            b: "x".into(),
        };
        let s3 = TestSpec {
            a: 1,
            b: "y".into(),
        };
        let id1 = ephemeral_id_from_spec(&s1).unwrap();
        let id2 = ephemeral_id_from_spec(&s2).unwrap();
        let id3 = ephemeral_id_from_spec(&s3).unwrap();
        assert_ne!(id1, id2);
        assert_ne!(id1, id3);
        assert_ne!(id2, id3);
    }

    #[test]
    fn ephemeral_id_lowercase_valid_dns_label() {
        // BLAKE3 hex is lowercase by design; the validator must
        // accept the output as a valid DNS label.
        let spec = TestSpec {
            a: 42,
            b: "anything".into(),
        };
        let id = ephemeral_id_from_spec(&spec).unwrap();
        validate_label("ephemeral_id", &id).unwrap();
    }

    // ─── resolve_ephemeral_id ────────────────────────────────────

    #[test]
    fn resolve_named_slot_wins() {
        let h = RoutingHostname::instanced("api", "demo-prod");
        assert_eq!(resolve_ephemeral_id(&h, "fallback"), "demo-prod");
    }

    #[test]
    fn resolve_empty_named_falls_back() {
        let h = RoutingHostname {
            app: "api".into(),
            instance: Some(String::new()),
            cluster: None,
        };
        assert_eq!(resolve_ephemeral_id(&h, "abc123de"), "abc123de");
    }

    #[test]
    fn resolve_unset_named_falls_back() {
        let h = RoutingHostname::content_hashed("api");
        assert_eq!(resolve_ephemeral_id(&h, "abc123de"), "abc123de");
    }

    // ─── End-to-end ──────────────────────────────────────────────

    // ─── HostnameResultExt::hostname_ctx substrate pins ──────────
    //
    // Fail-before-pass-after granularity: the `HostnameResultExt::
    // hostname_ctx` trait method did not exist before this commit,
    // so each test below fails to compile pre-lift. Post-lift they
    // collectively pin the display-prefix wrap-shape at ONE substrate
    // owner — a regression that drifts the separator, swaps the two
    // slots, wraps the `HostnameError` with a chain-form `source`, or
    // promotes the pass-through arm to a synthesis (an empty `Ok(())`,
    // a mutated context slug) surfaces HERE rather than as silent
    // operator-facing skew across the three pre-lift consumers whose
    // log output already encoded the flat `"<ctx>: <HostnameError
    // display>"` shape.

    fn sample_err() -> HostnameError {
        HostnameError::InvalidLabel {
            segment: "app",
            label: "BAD".into(),
            reason: "must contain only [a-z0-9-]",
        }
    }

    #[test]
    fn hostname_ctx_static_str_context_matches_pre_lift_format_bytewise() {
        // Byte-shape parity pin: the wrap output of `hostname_ctx
        // ("<slug>")` MUST be `Display`-identical to the pre-lift
        // hand-authored `.map_err(|e| anyhow!("<slug>: {e}"))` chain.
        // A regression that inserted a separator character (`"<slug>::
        // <hostname>"`), dropped the space after the colon, or swapped
        // the two slots (`"<hostname>: <slug>"`) surfaces HERE rather
        // than as silent drift at every downstream log-output consumer.
        let raw: Result<(), HostnameError> = Err(sample_err());
        let via_trait = raw.hostname_ctx("fmt_fqdn (per-instance)").unwrap_err();
        let pre_lift = anyhow::anyhow!("fmt_fqdn (per-instance): {}", sample_err());
        assert_eq!(
            format!("{via_trait}"),
            format!("{pre_lift}"),
            "hostname_ctx wrap must be Display-identical to pre-lift anyhow! chain"
        );
    }

    #[test]
    fn hostname_ctx_ok_arm_is_a_pure_passthrough() {
        // Ok-arm invariant: `hostname_ctx` on `Ok(t)` MUST return
        // `Ok(t)` verbatim — no side-effect on the payload, no
        // synthesis of a context-tagged error, no allocation. Peer to
        // the Err-arm byte-shape pin; a regression that promoted the
        // Ok arm to ALWAYS produce a synthesis Error would silently
        // break every successful hostname-format call in the pre-lift
        // consumer set.
        let raw: Result<&'static str, HostnameError> = Ok("api.demo-prod.pleme-dev.use1.quero.lol");
        assert_eq!(
            raw.hostname_ctx("noop").unwrap(),
            "api.demo-prod.pleme-dev.use1.quero.lol"
        );
    }

    #[test]
    fn hostname_ctx_threads_the_underlying_hostname_error_display_verbatim() {
        // Display-tail invariant: the wrapped `anyhow::Error`'s
        // `Display` output MUST contain the `HostnameError`'s own
        // `Display` output verbatim as the tail past `"<ctx>: "`. A
        // regression that inserted a normalization (uppercase, JSON
        // encoding, truncation) between the composed `{e}` slot and
        // the underlying thiserror-derived Display impl would surface
        // HERE rather than as silent operator-facing skew across the
        // three consumers whose grep patterns already encoded the
        // canonical `HostnameError` variant wordings ("invalid DNS
        // label ...", "app label ... is reserved").
        let raw: Result<(), HostnameError> = Err(HostnameError::ReservedApp("auth".into()));
        let wrapped = raw.hostname_ctx("fmt_fqdn_stable").unwrap_err();
        let expected_tail = format!("{}", HostnameError::ReservedApp("auth".into()));
        let expected = format!("fmt_fqdn_stable: {expected_tail}");
        assert_eq!(format!("{wrapped}"), expected);
        // Also assert the tail appears verbatim as a suffix — a change
        // in the thiserror-derived Display for ReservedApp would fail
        // both this assertion and the RECEIPT_VERSION-in-tail invariant
        // its docstring pins.
        assert!(
            format!("{wrapped}").ends_with(&expected_tail),
            "wrap must end with the HostnameError Display verbatim"
        );
    }

    #[test]
    fn hostname_ctx_composes_over_ephemeral_id_from_spec_call_shape() {
        // End-to-end composition pin: the substrate trait method
        // composes cleanly over the `ephemeral_id_from_spec` return
        // shape at a real callsite (the `render_routing` R9 seed).
        // A regression that specialized the trait bound to only one
        // hostname primitive's Result shape would surface HERE.
        #[derive(Serialize)]
        struct NoSuchThingAsAnUnserializableStruct {
            a: u32,
        }
        let v = NoSuchThingAsAnUnserializableStruct { a: 1 };
        let composed: anyhow::Result<String> =
            ephemeral_id_from_spec(&v).hostname_ctx("ephemeral_id_from_spec");
        assert!(composed.is_ok());
        assert_eq!(composed.unwrap().len(), EPHEMERAL_ID_HASH_LEN);
    }

    // ─── validate_app substrate pins ─────────────────────────────
    //
    // Fail-before-pass-after granularity: the `validate_app` helper
    // did not exist pre-lift — both [`fmt_fqdn`] and [`fmt_fqdn_stable`]
    // hand-authored the two-step (RFC 1123 label + reserved-name reject)
    // check inline. Post-lift the two composers thread the same
    // primitive, so the pins below pin the primitive's SHAPE + STEP
    // ORDER + typed-variant surface at the substrate — a regression
    // that (a) reorders the two steps, (b) drops the reserved-name
    // gate silently, or (c) promotes the `HostnameError::ReservedApp`
    // arm to a generic `InvalidLabel` surfaces HERE rather than as
    // silent skew at every downstream FQDN emit.

    #[test]
    fn validate_app_accepts_valid_lowercase_alphanumeric_label() {
        // Happy-path pin: a valid `app` label passes the two-step
        // check with `Ok(())`. A regression that inverted the return
        // arm (rejected everything, matched no reserved) surfaces
        // HERE rather than as every FQDN emit refusing every input.
        validate_app("api").unwrap();
        validate_app("gateway").unwrap();
        validate_app("demo-app").unwrap();
        validate_app("a").unwrap();
    }

    #[test]
    fn validate_app_rejects_empty_label_with_invalid_label_variant() {
        // Step-1 delegation pin: an empty `app` MUST surface as
        // `HostnameError::InvalidLabel { segment: "app", .. }` from
        // the underlying `validate_label("app", app)?` call — NOT as
        // `ReservedApp` (which would silently reclassify the shape
        // defect as a policy rejection).
        assert!(matches!(
            validate_app(""),
            Err(HostnameError::InvalidLabel { segment: "app", .. })
        ));
    }

    #[test]
    fn validate_app_rejects_uppercase_label_with_invalid_label_variant() {
        // Step-1 delegation pin: casing-invalid labels reach through
        // to `validate_label`'s [a-z0-9-] check. A regression that
        // short-circuited the reserved-check on a case-insensitive
        // match ("AUTH" reads as reserved without going through the
        // RFC 1123 gate first) would surface HERE.
        assert!(matches!(
            validate_app("API"),
            Err(HostnameError::InvalidLabel { segment: "app", .. })
        ));
    }

    #[test]
    fn validate_app_rejects_too_long_label_with_invalid_label_variant() {
        // Step-1 delegation pin: 64-char labels violate the RFC 1123
        // upper bound and surface at the `validate_label` gate.
        let long = "a".repeat(64);
        assert!(matches!(
            validate_app(&long),
            Err(HostnameError::InvalidLabel { segment: "app", .. })
        ));
    }

    #[test]
    fn validate_app_rejects_reserved_auth_label_with_reserved_app_variant() {
        // Step-2 pin: the currently-reserved `"auth"` slot surfaces
        // as `HostnameError::ReservedApp("auth")` — the typed
        // control-plane rejection callers pattern-match on. A
        // regression that dropped this variant would silently
        // accept the reservation and let a tenant deploy under the
        // saguão namespace.
        assert!(matches!(
            validate_app("auth"),
            Err(HostnameError::ReservedApp(ref s)) if s == "auth"
        ));
    }

    #[test]
    fn validate_app_rejects_reserved_cracha_label_with_reserved_app_variant() {
        // Sibling pin to the `"auth"` reservation — pins the second
        // currently-reserved label. A regression that dropped one
        // reservation but not the other would surface HERE.
        assert!(matches!(
            validate_app("cracha"),
            Err(HostnameError::ReservedApp(ref s)) if s == "cracha"
        ));
    }

    #[test]
    fn validate_app_step_order_puts_rfc_1123_check_before_reserved_check() {
        // Load-bearing order pin: `validate_label` runs FIRST so a
        // reserved label whose spelling ALSO violates RFC 1123
        // (uppercase, hyphen at end, etc.) surfaces as
        // `InvalidLabel` — the underlying SHAPE defect — not as
        // `ReservedApp` (the higher-level POLICY gate). Callers who
        // pattern-match on the two variants branch DIFFERENTLY on
        // shape defects vs policy rejections, so a swap of the two
        // steps would silently re-route every uppercase-reserved
        // input into the wrong error arm.
        assert!(matches!(
            validate_app("AUTH"),
            Err(HostnameError::InvalidLabel { segment: "app", .. })
        ));
        assert!(matches!(
            validate_app("Cracha"),
            Err(HostnameError::InvalidLabel { segment: "app", .. })
        ));
    }

    #[test]
    fn validate_app_matches_pre_lift_two_step_chain_bytewise_across_every_variant_shape() {
        // Byte-shape parity pin: the substrate primitive's return
        // MUST equal the pre-lift 4-line hand-authored chain for
        // every representative input shape. A regression that
        // drifted the primitive's semantics away from the pre-lift
        // composer preludes surfaces HERE rather than as silent
        // skew at either `fmt_fqdn` / `fmt_fqdn_stable` consumer.
        fn pre_lift(app: &str) -> Result<(), HostnameError> {
            validate_label("app", app)?;
            if RESERVED_APP_LABELS.contains(&app) {
                return Err(HostnameError::ReservedApp(app.to_string()));
            }
            Ok(())
        }
        for input in [
            // Happy path.
            "api",
            "gateway",
            "demo-app",
            "a",
            // Step-1 rejections.
            "",
            "API",
            "-bad",
            "bad-",
            "with_underscore",
            // Step-2 rejections.
            "auth",
            "cracha",
            // Step-1 wins over step-2 (uppercase reserved).
            "AUTH",
            "Cracha",
        ] {
            let via_primitive = validate_app(input);
            let via_pre_lift = pre_lift(input);
            match (via_primitive, via_pre_lift) {
                (Ok(()), Ok(())) => {}
                (Err(a), Err(b)) => assert_eq!(a, b, "variant mismatch for {input:?}"),
                (a, b) => panic!("arm mismatch for {input:?}: primitive={a:?} pre_lift={b:?}"),
            }
        }
    }

    #[test]
    fn validate_app_covers_every_currently_reserved_label_at_the_primitive() {
        // Coherence sweep: iterate the RESERVED_APP_LABELS set and
        // verify each element rejects at the substrate. A future
        // addition to the reserved set that forgets to update the
        // primitive would surface HERE rather than as silent
        // acceptance at every FQDN emit.
        for reserved in RESERVED_APP_LABELS {
            assert!(
                matches!(validate_app(reserved), Err(HostnameError::ReservedApp(ref s)) if s == reserved),
                "RESERVED_APP_LABELS entry {reserved:?} must surface as ReservedApp at the substrate"
            );
        }
    }

    #[test]
    fn fmt_fqdn_routes_app_slot_through_validate_app_primitive() {
        // Delegation pin: the per-instance composer routes its `app`
        // slot check through `validate_app`, NOT through a re-open-
        // coded restatement of the two-step chain. A regression that
        // inlined the pre-lift check at the composer prelude would
        // reintroduce the duplication the lift removed; this pin
        // catches it by asserting the composer surfaces the SAME
        // typed error the primitive would for a representative
        // input in each of the two rejection arms.
        assert!(matches!(
            fmt_fqdn("AUTH", "x", "y", "z", "example.com"),
            Err(HostnameError::InvalidLabel { segment: "app", .. })
        ));
        assert!(matches!(
            fmt_fqdn("auth", "x", "y", "z", "example.com"),
            Err(HostnameError::ReservedApp(ref s)) if s == "auth"
        ));
    }

    #[test]
    fn fmt_fqdn_stable_routes_app_slot_through_validate_app_primitive() {
        // Sibling delegation pin — same shape as the per-instance
        // pin above but for the stable-claim composer. Both
        // composers now share the primitive; a regression that
        // re-inlined the chain at either site surfaces at ONE of
        // the two pins rather than at every downstream FQDN emit.
        assert!(matches!(
            fmt_fqdn_stable("Cracha", "y", "z", "example.com"),
            Err(HostnameError::InvalidLabel { segment: "app", .. })
        ));
        assert!(matches!(
            fmt_fqdn_stable("cracha", "y", "z", "example.com"),
            Err(HostnameError::ReservedApp(ref s)) if s == "cracha"
        ));
    }

    #[test]
    fn end_to_end_named_and_unnamed_for_same_process() {
        let spec = TestSpec {
            a: 1,
            b: "x".into(),
        };
        let hash = ephemeral_id_from_spec(&spec).unwrap();

        let h_named = RoutingHostname::instanced("api", "demo-prod");
        let h_anon = RoutingHostname::content_hashed("gateway");

        let id_named = resolve_ephemeral_id(&h_named, &hash);
        let id_anon = resolve_ephemeral_id(&h_anon, &hash);

        let fqdn_named =
            fmt_fqdn(&h_named.app, id_named, "pleme-dev", "use1", "quero.lol").unwrap();
        let fqdn_anon = fmt_fqdn(&h_anon.app, id_anon, "pleme-dev", "use1", "quero.lol").unwrap();

        assert_eq!(fqdn_named, "api.demo-prod.pleme-dev.use1.quero.lol");
        assert!(fqdn_anon.starts_with("gateway."));
        assert!(fqdn_anon.ends_with(".pleme-dev.use1.quero.lol"));
        // 5 named segments (app + eph_id + cluster + location + domain),
        // but `domain` itself splits as `quero.lol` ⇒ 6 dot-delimited
        // pieces. The shape, not the count, is the invariant.
        assert_eq!(fqdn_anon.matches('.').count(), 5);
    }
}