caixa_core/aplicacao.rs
1//! Typed Aplicacao — the fourth caixa kind that turns a graph of
2//! Servicos into a single declarative application (mesh).
3//!
4//! See `theory/MESH-COMPOSITION.md` for the design frame: an
5//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
6//! `:contratos` (inter-Servico edges), declares mesh-level
7//! `:politicas` (timeouts, retries, breakers, mTLS), pins
8//! `:placement` strategy (single-node / replicated / sharded), and
9//! exposes `:entrada` (gateway).
10//!
11//! ```lisp
12//! (defcaixa
13//! :nome "checkout"
14//! :versao "0.1.0"
15//! :kind Aplicacao
16//! :membros ((:caixa "catalog" :versao "^0.1")
17//! (:caixa "cart" :versao "^0.1")
18//! (:caixa "payment" :versao "^0.2"))
19//! :contratos ((:de "cart" :para "catalog"
20//! :wit "wasi:http/proxy" :endpoint "/products/:id")
21//! (:de "cart" :para "payment"
22//! :wit "wasi:http/proxy" :endpoint "/charge"))
23//! :politicas ((:timeout "30s")
24//! (:retries 3)
25//! (:circuit-breaker (:max-failures 5 :window "60s"))
26//! (:mtls-required t))
27//! :placement (:estrategia replicated
28//! :clusters ("rio" "mar" "plo"))
29//! :entrada (:host "checkout.quero.cloud"
30//! :para "cart"
31//! :paths ("/api/cart" "/api/products")))
32//! ```
33//!
34//! All the typed slots compose with the M2 primitives the Servicos
35//! they reference already declare (`:limits`, `:behavior`,
36//! `:upgrade-from`). The Aplicacao adds the *graph-level*
37//! standardization on top.
38
39use std::time::Duration;
40
41use serde::{Deserialize, Serialize};
42use thiserror::Error;
43
44use crate::supervisor; // we reuse the duration-string codec at module scope
45
46// ── inter-Servico contracts ──────────────────────────────────────────
47
48/// One typed edge in the Aplicacao graph. The build refuses any
49/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
50/// (M3+) cross-checks the `:wit` shape against both Servicos'
51/// declared imports/exports.
52#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct WitContract {
55 /// Caller Servico — must reference an entry in the Aplicacao's
56 /// `:membros`. The Servico's caixa.lisp must declare a matching
57 /// `:capabilities` import for the `:wit` world.
58 pub de: String,
59
60 /// Callee Servico — must reference an entry in `:membros`. The
61 /// Servico must declare a matching `:capabilities` export.
62 pub para: String,
63
64 /// WIT world reference — e.g. `"wasi:http/proxy"`,
65 /// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
66 /// M4 promotes these to a typed enum once the WIT registry
67 /// stabilizes in tatara-lisp.
68 pub wit: String,
69
70 /// HTTP endpoint path, present when `:wit` is HTTP-shaped.
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub endpoint: Option<String>,
73
74 /// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub subject: Option<String>,
77
78 /// Key/value or queue slot, present when `:wit` is store-shaped.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub slot: Option<String>,
81}
82
83/// Canonical lowercase byte-prefix set the substrate's WIT-shape
84/// dispatch routes `wasi:http/*` / `http:*` values through as the
85/// HTTP-shaped arm. The single source of truth every consumer that
86/// classifies a `:wit` value as HTTP-shaped consults —
87/// [`WitContract::is_http`] on the typed contract, the
88/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
89/// helper, and every future renderer that routes an L7 emission off a
90/// bare `&str` (the M4 per-edge WIT registry resolver, the future
91/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
92/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
93/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
94/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
95/// substrate's accept-set and this crate's dispatch-set is a
96/// build-time compile error (unused-import), not a per-renderer
97/// silent L7-→-L4 demotion at apply time.
98///
99/// [iwr]: crate::render::is_wit_world_ref
100pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];
101
102/// Canonical lowercase byte-prefix set the substrate's WIT-shape
103/// dispatch routes `nats:*` / `kafka:*` values through as the
104/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
105/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
106/// HTTP constant's docstring for the full lift rationale.
107pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];
108
109/// Canonical lowercase byte-prefix set the substrate's WIT-shape
110/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
111/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
112/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
113/// HTTP constant's docstring for the full lift rationale.
114pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];
115
116/// True when `wit` — a raw `:contratos :wit` value — starts with any
117/// entry in the `prefixes` accept-set. The single canonical
118/// prefix-driven WIT-shape classification combinator every peer
119/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
120/// [`wit_shape_is_store`]) routes through, closing the 3-site
121/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
122/// combinator the prior open-coded implementations each carried.
123///
124/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
125/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
126/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
127/// one new `wit_shape_is_<name>` one-liner routing through this
128/// combinator, not a fourth copy of the `iter().any(starts_with)`
129/// combinator paired to its own prefix-set. Same "one canonical
130/// combinator, thin per-arm projections" discipline the peer
131/// [`WitTarget::payload_pair`] (6788ed6) already established for the
132/// downstream per-arm `(field, payload)` dispatch, extended to the
133/// upstream per-arm `PREFIXES → bool` dispatch.
134///
135/// Declared `pub const fn` — the four peer classifiers
136/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
137/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) route through
138/// this combinator in `const`-eval context, so the raw `&str → bool`
139/// WIT-shape dispatch reaches every substrate-side `const`-context
140/// consumer (the module-scope `const _: () = assert!(…)` canonical-
141/// accept-set + partition-witness pins immediately below the four
142/// peer classifiers, any future M4
143/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
144/// webhook `const fn` per-`:contratos :wit` shape-arm resolver over a
145/// raw &str, any future `const fn` per-`:contratos`-edge WIT-registry
146/// prefix-set overlay resolver over the substrate primitive that fans
147/// on the shape arm at compile time) through the same typed dispatch
148/// on the substrate primitive at const-eval time as at runtime. The
149/// prior `prefixes.iter().any(|p| wit.starts_with(p))` body carried
150/// non-`const` bounds on stable Rust 1.94 (`.iter()` / `.any()` /
151/// `str::starts_with(&str)` via the non-`const` `Pattern` trait); the
152/// new body routes the per-prefix probe through a manual byte-level
153/// `starts_with` loop over the paired `str::as_bytes` (`pub const fn`)
154/// slice projections, dispatching through primitive-`u8` `!=` and
155/// `usize` comparison + `pub const fn` `<[u8]>::len` and const-stable
156/// slice indexing (since Rust 1.79) — every operation `const`-eval-
157/// callable on stable, no iterator methods, no `Pattern` trait.
158#[must_use]
159pub const fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
160 let bytes = wit.as_bytes();
161 let mut i = 0;
162 while i < prefixes.len() {
163 let prefix = prefixes[i].as_bytes();
164 if prefix.len() <= bytes.len() {
165 let mut j = 0;
166 let mut matches = true;
167 while j < prefix.len() {
168 if bytes[j] != prefix[j] {
169 matches = false;
170 break;
171 }
172 j += 1;
173 }
174 if matches {
175 return true;
176 }
177 }
178 i += 1;
179 }
180 false
181}
182
183/// True when `wit` — a raw `:contratos :wit` value — targets an
184/// HTTP-shaped WIT world (starts with any prefix in
185/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
186/// consumer routes L7-HTTP emission through, whether they carry a
187/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
188/// here) or only the raw `wit` string (the positive-sweep test's
189/// payload-dispatch helper, future renderers that classify off a
190/// bare `&str`). Lifting to a free function makes the shape-dispatch
191/// arm reachable without materializing a scratch [`WitContract`] at
192/// every classification point, and pins the six-prefix accept-set at
193/// one place so future additions (e.g. an `"https:"` peer of
194/// `"http:"`) reach every consumer by construction. Routes through
195/// the lifted [`wit_shape_matches`] combinator so the
196/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
197/// canonical primitive, not one open-coded copy per peer arm.
198///
199/// Declared `pub const fn` — routes through the peer `pub const fn`
200/// [`wit_shape_matches`] combinator so every substrate-side
201/// `const`-context WIT-shape-arm-classifier consumer (the module-scope
202/// `const _: () = assert!(…)` canonical-accept-set + partition-witness
203/// pins immediately below, any future M4 admission-webhook
204/// `const fn` per-`:contratos :wit` HTTP-arm resolver over a raw &str)
205/// reaches through the same typed dispatch on the substrate primitive
206/// at const-eval time as at runtime.
207#[must_use]
208pub const fn wit_shape_is_http(wit: &str) -> bool {
209 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
210}
211
212/// True when `wit` — a raw `:contratos :wit` value — targets a
213/// pub-sub-shaped WIT world (starts with any prefix in
214/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
215/// [`wit_shape_is_store`] on the shape-dispatch axis; see
216/// [`wit_shape_is_http`] for the lift rationale. Routes through the
217/// lifted [`wit_shape_matches`] combinator.
218///
219/// Declared `pub const fn` — sibling in `const`-eval posture to the
220/// peer [`wit_shape_is_http`] classifier; see that function's `const`
221/// posture-block for the full rationale.
222#[must_use]
223pub const fn wit_shape_is_pubsub(wit: &str) -> bool {
224 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
225}
226
227/// True when `wit` — a raw `:contratos :wit` value — targets a
228/// key/value-store-shaped WIT world (starts with any prefix in
229/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
230/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
231/// [`wit_shape_is_http`] for the lift rationale. Routes through the
232/// lifted [`wit_shape_matches`] combinator.
233///
234/// Declared `pub const fn` — sibling in `const`-eval posture to the
235/// peer [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] classifiers;
236/// see [`wit_shape_is_http`]'s `const` posture-block for the full
237/// rationale.
238#[must_use]
239pub const fn wit_shape_is_store(wit: &str) -> bool {
240 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
241}
242
243/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
244/// the three known payload-shape WIT worlds; the payload-less
245/// capability arm of the 4-way WIT-shape partition on the raw
246/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
247/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
248/// dispatch axis — closes the free-function classifier family the
249/// three payload-arm predicates opened onto the exact-inverse
250/// disjunction of the trio, so any downstream consumer that must
251/// classify a raw `:wit` `&str` onto the payload-less capability arm
252/// (a future substrate-side capability-shape-only emitter — the M4
253/// per-Aplicacao WIT-registry capability-import materializer, the
254/// future `feira app graph --capability` filter, the future per-
255/// cluster capability-scope reconciler that skips L4/L7 emission for
256/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
257/// CR admission webhook's per-shape histogram) reaches for exactly
258/// one typed dispatch at the substrate primitive rather than an
259/// open-coded per-consumer `!wit_shape_is_http(wit) &&
260/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
261/// negation — each of which would silently misclassify a future 4th
262/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
263/// layer shape, an `oci:*` capability-import carrier per the sibling
264/// [`wit_shape_matches`] docstring's trajectory bullet) as
265/// capability without a compile-time signal at the consumer site.
266///
267/// Fourth arm on the free-function WIT-shape-predicate family — closes
268/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
269/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
270/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
271/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
272/// the post-projection [`WitTarget`]-side
273/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
274/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
275/// [`WitTarget`] variant now carries a matched peer predicate on both
276/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
277/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
278/// [`WitContract`] surface (the sibling 4-arm predicate family
279/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
280/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
281/// pinned in load-bearing by the sibling
282/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
283/// partition-witness pin and the peer
284/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
285/// delegation pin.
286///
287/// Prior to this lift the "not one of the three known payload shapes"
288/// classification only reached the raw `&str` axis by materializing a
289/// scratch [`WitContract`] and delegating through
290/// [`WitContract::is_capability`] — a five-field constructor at every
291/// classification point for a pure `&str → bool` question, and a
292/// dependency on the payload-carrier scalar layout the classifier
293/// does not read. Same "one canonical combinator, thin per-arm
294/// projections" discipline the peer [`wit_shape_is_http`] /
295/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
296/// established, extended to close the 4-arm partition on the raw
297/// `&str` axis.
298///
299/// Note: purely syntactic classification on the negated `:wit` prefix-
300/// set — unlike [`WitContract::target`], which additionally rejects
301/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
302/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
303/// payload-shape mismatches. An empty or structurally malformed `wit`
304/// string returns `true` here (the prefix set matches nothing), and
305/// the surrounding validate-side gate cascade is where the
306/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
307/// diagnostic surfaces — this function is the classifier, not the
308/// validator.
309///
310/// Declared `pub const fn` — closes the 4-arm classifier family's
311/// `const`-eval-surface pass on the payload-less capability arm,
312/// peer of the sibling `pub const fn` [`wit_shape_is_http`] /
313/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] classifiers, so
314/// the raw `&str → bool` WIT-shape partition on the capability arm
315/// reaches every substrate-side `const`-context consumer through one
316/// typed dispatch. See [`wit_shape_is_http`]'s `const` posture-block
317/// for the full rationale.
318#[must_use]
319pub const fn wit_shape_is_capability(wit: &str) -> bool {
320 !wit_shape_is_http(wit) && !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)
321}
322
323// Compile-time pins on the 4-arm WIT-shape classifier family — the
324// module-scope const-eval assertions below trip at caixa-core build
325// time (not test time) if a future edit rewires any of the four
326// classifier's arm-set away from the accept-set MESH-COMPOSITION §II.3
327// pins. Anchor the `const`-eval-surface posture of the four peer
328// classifiers on canonical accept-set samples (one per WIT_*_SHAPE_PREFIXES
329// prefix) plus pairwise-exclusion samples asserting the trio partitions
330// the payload-carrying arm-set and the capability arm carries the
331// complementary payload-less remainder. Any future accidental downgrade
332// of one classifier to non-`const` fails these items at caixa-core build
333// time; any future prefix-set edit that overlaps two arms (e.g. a `kv:`
334// prefix accidentally re-emitted under `WIT_HTTP_SHAPE_PREFIXES`) trips
335// the corresponding partition-witness item. Peer of the sibling M3
336// [`PlacementStrategy::requires_shard_key`] partition pins at
337// aplicacao.rs:5121-5123 on the sibling closed-set typed-enum
338// discriminator axis.
339const _: () = assert!(wit_shape_is_http("wasi:http/proxy"));
340const _: () = assert!(wit_shape_is_http("http:incoming"));
341const _: () = assert!(wit_shape_is_pubsub("nats:events"));
342const _: () = assert!(wit_shape_is_pubsub("kafka:topic"));
343const _: () = assert!(wit_shape_is_store("wasi:keyvalue/store"));
344const _: () = assert!(wit_shape_is_store("kv:cache"));
345const _: () = assert!(wit_shape_is_capability("wasi:filesystem/preopens"));
346const _: () = assert!(wit_shape_is_capability(""));
347// Pairwise-exclusion pins — the three payload-carrying arms are
348// pairwise disjoint on the canonical accept-set samples, and the
349// capability arm is the exact-inverse disjunction of the trio
350// (the free-function classifier family's 4-way partition witness).
351const _: () = assert!(!wit_shape_is_http("nats:events"));
352const _: () = assert!(!wit_shape_is_http("kv:cache"));
353const _: () = assert!(!wit_shape_is_pubsub("wasi:http/proxy"));
354const _: () = assert!(!wit_shape_is_pubsub("wasi:keyvalue/store"));
355const _: () = assert!(!wit_shape_is_store("wasi:http/proxy"));
356const _: () = assert!(!wit_shape_is_store("nats:events"));
357const _: () = assert!(!wit_shape_is_capability("wasi:http/proxy"));
358const _: () = assert!(!wit_shape_is_capability("nats:events"));
359const _: () = assert!(!wit_shape_is_capability("wasi:keyvalue/store"));
360
361impl WitContract {
362 /// Substrate-canonical per-`:contratos` caller-Servico scalar
363 /// accessor every consumer that reads the edge's source endpoint
364 /// keys off — returns the author-declared `:contratos :de`
365 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
366 /// own [`String`] storage.
367 ///
368 /// The `:contratos :de` slot names the caller-side member Servico
369 /// on a typed inter-Servico edge (validated by
370 /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
371 /// Aplicacao declares — a stray `:de` that doesn't name a member is
372 /// [`AplicacaoError::ContratoMemberMissing`], not a silent
373 /// caller-attachment miss at cluster-apply time). Peer of the
374 /// sibling [`WitContract::destination`] accessor on the same
375 /// per-`:contratos` entry — the pair `( source(), destination() )`
376 /// jointly names the typed edge every renderer that fans on the
377 /// caller-callee identity keys off (the
378 /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
379 /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
380 /// map, the per-edge dedup key, the per-edge membership-lookup
381 /// diagnostic).
382 ///
383 /// Prior to this lift the `.de` byte-string was accessed inline at
384 /// four caixa-core sites (the two validate-side membership lookups
385 /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
386 /// tuple's caller-arm at
387 /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
388 /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
389 /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
390 /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
391 /// — five open-coded `.de.as_str()` field-accesses that expressed
392 /// no compile-time link back to the typed slot. A future extension
393 /// of the `:contratos :de` axis to a richer author surface (a
394 /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
395 /// canary flow, a per-cluster caller-alias table the operator pins
396 /// through a future `:placement`-scoped slot, the M4
397 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
398 /// admission-webhook that promotes the scalar to a caller-set
399 /// projection) would have had to be threaded through every
400 /// open-coded copy in lockstep or one consumer would silently
401 /// disagree with the peers on which caller Servico a given edge
402 /// resolves to. Lifting the resolution rule to a typed method on
403 /// the substrate primitive means every downstream caller-facing
404 /// consumer reaches for one typed dispatch — the resolver's
405 /// accept-set migrates as a unit on any future axis addition.
406 ///
407 /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
408 /// (6db982c) accessor on the analogous per-ingress-Servico scalar
409 /// axis — same "one typed dispatch on the substrate primitive,
410 /// thin projections at each consumer" discipline extended onto the
411 /// per-`:contratos` caller-Servico byte-string axis.
412 #[must_use]
413 pub fn source(&self) -> &str {
414 self.de.as_str()
415 }
416
417 /// Substrate-canonical per-`:contratos` callee-Servico scalar
418 /// accessor every consumer that reads the edge's destination
419 /// endpoint keys off — returns the author-declared
420 /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
421 /// from the typed slot's own [`String`] storage.
422 ///
423 /// The `:contratos :para` slot names the callee-side member Servico
424 /// on a typed inter-Servico edge (validated by
425 /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
426 /// Aplicacao declares — a stray `:para` that doesn't name a member
427 /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
428 /// callee-attachment miss at cluster-apply time). Callee-side twin
429 /// of the sibling [`WitContract::source`] accessor — the pair
430 /// jointly names the typed edge every renderer that fans on the
431 /// caller-callee identity keys off, and this accessor is also the
432 /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
433 /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
434 /// composes with `destination()` at every emit site that projects a
435 /// per-edge destination Servico's L4 listener port.
436 ///
437 /// Prior to this lift the `.para` byte-string was accessed inline
438 /// at five sites — four caixa-core (the validate-side membership
439 /// lookup at `!names.contains(c.para.as_str())`, the per-edge
440 /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
441 /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
442 /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
443 /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
444 /// — with no compile-time link back to the typed slot. A future
445 /// extension of the `:contratos :para` axis to a richer author
446 /// surface (a multi-callee weighted-fan-out overlay for canary /
447 /// blue-green routing on typed edges, a per-cluster callee-alias
448 /// table the operator pins through a future `:placement`-scoped
449 /// slot, the M4 CR materializer's per-CR admission-webhook that
450 /// promotes the scalar to a callee-set projection) would have had
451 /// to be threaded through every open-coded copy in lockstep or one
452 /// consumer would silently disagree on which callee Servico a given
453 /// edge resolves to (a per-CNP `endpointSelector` that names a
454 /// different destination than its L4 port resolver reads for, a
455 /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
456 /// as distinct while the adjacency map collapses them, or vice
457 /// versa). Lifting to a typed method on the substrate primitive
458 /// means every downstream callee-facing consumer reaches for one
459 /// typed dispatch.
460 ///
461 /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
462 /// (6db982c) accessor — both name the "destination-Servico
463 /// byte-string" concept on their respective mesh-slot atoms (per-
464 /// ingress apex vs. per-typed-edge callee), and both extend the
465 /// substrate-primitive-owns-the-resolver discipline onto the
466 /// per-slot destination-Servico scalar axis. Composes with
467 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
468 /// emit-side per-edge L4 port reader — the composition
469 /// `spec.port_for_destination(c.destination())` pins the CNP per-
470 /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
471 /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
472 /// `spec.port_for_destination(entrada.destination())`.
473 #[must_use]
474 pub fn destination(&self) -> &str {
475 self.para.as_str()
476 }
477
478 /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
479 /// accessor every consumer that reads the edge's WIT world
480 /// discriminator keys off — returns the author-declared
481 /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
482 /// the typed slot's own [`String`] storage.
483 ///
484 /// The `:contratos :wit` slot names the WIT world the typed edge
485 /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
486 /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
487 /// be a well-shaped WIT world reference via
488 /// [`crate::render::is_wit_world_ref`] and by
489 /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
490 /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
491 /// [`WitContract::source`] / [`WitContract::destination`] accessors
492 /// on the same per-`:contratos` entry — the triple
493 /// `( source(), destination(), world_ref() )` jointly names the
494 /// typed edge every renderer that fans on the caller-callee-shape
495 /// identity keys off (the per-edge dedup key at
496 /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
497 /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
498 /// [`caixa_mesh::cilium_network_policies`], the
499 /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
500 /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
501 /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
502 ///
503 /// Prior to this lift the `.wit` byte-string was accessed inline at
504 /// five sites — three caixa-core (the `WitContract::is_*` shape-
505 /// dispatch predicates' `&self.wit` arg, the validate-side empty
506 /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
507 /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
508 /// printer's `{}` format-slot at `c.wit`) — five open-coded
509 /// `.wit` field-accesses that expressed no compile-time link back to
510 /// the typed slot. A future extension of the `:contratos :wit` axis
511 /// to a richer author surface (an M4 promotion from `String` to a
512 /// typed WIT-world enum once the WIT registry stabilizes in tatara-
513 /// lisp per this struct's own `:wit` field docstring, a per-cluster
514 /// WIT-alias table the operator pins through a future
515 /// `:placement`-scoped slot, a canonicalization pass that lowercases
516 /// `wasi:*` prefixes) would have had to be threaded through every
517 /// open-coded copy in lockstep or one consumer would silently
518 /// disagree with the peers on which WIT shape a given edge resolves
519 /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
520 /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
521 /// empty-check that missed a whitespace-only string a peer accessor
522 /// stripped, or vice versa). Lifting to a typed method on the
523 /// substrate primitive means every downstream WIT-shape-facing
524 /// consumer reaches for one typed dispatch — the resolver's
525 /// accept-set migrates as a unit on any future axis addition.
526 ///
527 /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
528 /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
529 /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
530 /// 6db982c), per-`:membros` [`Membro::nome`] /
531 /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
532 /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
533 /// on the substrate primitive, thin projections at each consumer"
534 /// discipline extended onto the last unlifted per-`:contratos`
535 /// scalar (the WIT-world-reference arm).
536 ///
537 /// [fag]: caixa-feira/src/cmd/app.rs
538 #[must_use]
539 pub fn world_ref(&self) -> &str {
540 self.wit.as_str()
541 }
542
543 /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
544 /// payload-target scalar accessor every consumer that reads the
545 /// edge's L7 HTTP request path payload keys off — returns the
546 /// author-declared `:contratos :endpoint` byte-string verbatim as
547 /// an `Option<&str>`, borrowed from the typed slot's own
548 /// `Option<String>` storage; `None` when the slot is absent (the
549 /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
550 /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
551 /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
552 /// [`WitTarget::Capability`] edge carries none of the three).
553 ///
554 /// The `:contratos :endpoint` slot carries the HTTP request path
555 /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
556 /// — same shape required of `:entrada :paths`, gated by the shared
557 /// [`crate::render::is_gateway_api_http_path`] predicate) that
558 /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
559 /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
560 /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
561 /// downstream consumer that reads the payload keys off this scalar
562 /// (the [`WitContract::target`] Http-arm payload extraction that
563 /// materializes [`WitTarget::Http { endpoint }`] under the paired
564 /// [`WitTarget::HTTP_FIELD_NAME`] label, the
565 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
566 /// key's endpoint arm that pins the payload as part of the six-tuple
567 /// dedup key alongside the sibling `:subject`/`:slot` arms, the
568 /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
569 /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
570 /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
571 /// emission path that lands the payload verbatim as a Cilium L7
572 /// `path:` rule).
573 ///
574 /// Prior to this lift the `.endpoint` field was accessed inline at
575 /// two production sites in `caixa-core/src/aplicacao.rs` — the
576 /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
577 /// self.endpoint.as_deref();` binding at the top of the method, and
578 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
579 /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
580 /// field-accesses that expressed no compile-time link back to the
581 /// typed slot. A future extension of the `:contratos :endpoint`
582 /// axis to a richer author surface (an M4 promotion from
583 /// `Option<String>` to a typed HTTP path-template enum once the
584 /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
585 /// this struct's own `:wit` field docstring, a per-cluster endpoint-
586 /// alias table the operator pins through a future `:placement`-
587 /// scoped slot, a canonicalization pass that percent-encodes non-
588 /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
589 /// materializer applies per-tenant) would have had to be threaded
590 /// through both open-coded copies in lockstep or the two consumers
591 /// would silently disagree on which HTTP path a given edge resolves
592 /// to — the [`WitContract::target`] payload-extraction reading
593 /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
594 /// the operator-resolved `"/tenant-a/lookup"` would silently split
595 /// the [`WitTarget::Http`]-arm rendered payload from the actual
596 /// dedup-key uniqueness axis, a two-consumer split at the validator
597 /// far from the source `caixa.lisp` with no field naming the
598 /// payload-drift root cause. Lifting the resolution rule to a typed
599 /// method on the substrate primitive means every downstream
600 /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
601 /// L7-payload surface reaches for exactly one typed dispatch — the
602 /// resolver's accept-set migrates as a unit on any future axis
603 /// addition.
604 ///
605 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
606 /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
607 /// accessors on the M3 mesh-slot family — same "one typed dispatch
608 /// on the substrate primitive, thin projections at each consumer"
609 /// discipline extended onto the per-`:contratos` HTTP-shaped
610 /// payload-carrier `Option<String>` optional-scalar axis. First
611 /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
612 /// atom — opens the "optional per-slot payload-carrier scalar"
613 /// projection pattern the sibling per-`:contratos` `:subject` /
614 /// `:slot` future lifts fold on, matching the closed
615 /// per-`:contratos` scalar-value accessor family
616 /// ([`WitContract::source`] / [`WitContract::destination`] /
617 /// [`WitContract::world_ref`]) already lifted onto the mandatory-
618 /// scalar `String` axes. Named `endpoint()` to match the storage
619 /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
620 /// author-facing label const; the accessor's identity name maps
621 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
622 /// docstring already carries.
623 #[must_use]
624 pub fn endpoint(&self) -> Option<&str> {
625 self.endpoint.as_deref()
626 }
627
628 /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
629 /// payload-target scalar accessor every consumer that reads the
630 /// edge's NATS / Kafka publish subject payload keys off — returns
631 /// the author-declared `:contratos :subject` byte-string verbatim
632 /// as an `Option<&str>`, borrowed from the typed slot's own
633 /// `Option<String>` storage; `None` when the slot is absent (the
634 /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
635 /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
636 /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
637 /// [`WitTarget::Capability`] edge carries none of the three).
638 ///
639 /// The `:contratos :subject` slot carries the NATS / Kafka publish
640 /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
641 /// per-edge target selector — `orders.paid`, `events.>`, whatever
642 /// subject namespace the author names on the pub-sub edge) that
643 /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
644 /// arm's `subject: &'a str` payload when the edge's `:wit` world
645 /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
646 /// downstream consumer that reads the payload keys off this scalar
647 /// (the [`WitContract::target`] PubSub-arm payload extraction that
648 /// materializes [`WitTarget::PubSub { subject }`] under the paired
649 /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
650 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
651 /// key's subject arm that pins the payload as part of the six-tuple
652 /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
653 /// future M4 per-edge WIT registry resolver's pub-sub-arm
654 /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
655 /// materializer's per-edge NATS admission webhook, the future
656 /// caixa-mesh L4 CNP emission path that lands the payload verbatim
657 /// as a NATS subject the operator pins per-CR).
658 ///
659 /// Prior to this lift the `.subject` field was accessed inline at
660 /// two production sites in `caixa-core/src/aplicacao.rs` — the
661 /// [`WitContract::target`] payload-shape dispatch's `let subject =
662 /// self.subject.as_deref();` binding at the top of the method, and
663 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
664 /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
665 /// field-accesses that expressed no compile-time link back to the
666 /// typed slot. A future extension of the `:contratos :subject` axis
667 /// to a richer author surface (an M4 promotion from `Option<String>`
668 /// to a typed NATS-subject-template enum once the WIT registry
669 /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
670 /// struct's own `:wit` field docstring, a per-cluster subject-alias
671 /// table the operator pins through a future `:placement`-scoped
672 /// slot, a canonicalization pass that lowercases / dedupes wildcard
673 /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
674 /// applies per-tenant) would have had to be threaded through both
675 /// open-coded copies in lockstep or the two consumers would silently
676 /// disagree on which NATS subject a given edge resolves to — the
677 /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
678 /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
679 /// resolved `"tenant-a.orders.paid"` would silently split the
680 /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
681 /// key uniqueness axis, a two-consumer split at the validator far
682 /// from the source `caixa.lisp` with no field naming the payload-
683 /// drift root cause. Lifting the resolution rule to a typed method
684 /// on the substrate primitive means every downstream pub-sub-payload-
685 /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
686 /// surface reaches for exactly one typed dispatch — the resolver's
687 /// accept-set migrates as a unit on any future axis addition.
688 ///
689 /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
690 /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
691 /// carrier axis — second `Option<&str>`-return accessor on the
692 /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
693 /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
694 /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
695 /// key/value-store arm as the last unlifted per-`:contratos`
696 /// `Option<String>` axis. Named `subject()` to match the storage
697 /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
698 /// author-facing label const; the accessor's identity name maps
699 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
700 /// docstring already carries.
701 #[must_use]
702 pub fn subject(&self) -> Option<&str> {
703 self.subject.as_deref()
704 }
705
706 /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
707 /// shaped payload-target scalar accessor every consumer that reads
708 /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
709 /// off — returns the author-declared `:contratos :slot` byte-string
710 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
711 /// own `Option<String>` storage; `None` when the slot is absent
712 /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
713 /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
714 /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
715 /// [`WitTarget::Capability`] edge carries none of the three).
716 ///
717 /// The `:contratos :slot` slot carries the key/value store
718 /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
719 /// arm's per-edge target selector — `carts/{cart_id}`,
720 /// `sessions/{tenant}/{sid}`, whatever key-template the author
721 /// names on the store edge) that [`WitContract::target`] projects
722 /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
723 /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
724 /// accept-set. Every downstream consumer that reads the payload
725 /// keys off this scalar (the [`WitContract::target`] Store-arm
726 /// payload extraction that materializes [`WitTarget::Store { slot }`]
727 /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
728 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
729 /// key's store arm that pins the payload as part of the six-tuple
730 /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
731 /// the future M4 per-edge WIT registry resolver's store-arm
732 /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
733 /// materializer's per-edge key/value admission webhook, the future
734 /// caixa-mesh L4 CNP emission path that lands the payload verbatim
735 /// as a key-template the operator pins per-CR).
736 ///
737 /// Prior to this lift the `.slot` field was accessed inline at two
738 /// production sites in `caixa-core/src/aplicacao.rs` — the
739 /// [`WitContract::target`] payload-shape dispatch's `let slot =
740 /// self.slot.as_deref();` binding at the top of the method, and
741 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
742 /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
743 /// field-accesses that expressed no compile-time link back to the
744 /// typed slot. A future extension of the `:contratos :slot` axis
745 /// to a richer author surface (an M4 promotion from `Option<String>`
746 /// to a typed key-template enum once the WIT registry stabilizes
747 /// key-template parameter shapes in tatara-lisp per this struct's
748 /// own `:wit` field docstring, a per-cluster slot-alias table the
749 /// operator pins through a future `:placement`-scoped slot, a
750 /// canonicalization pass that lowercases the bucket prefix, a
751 /// per-CR fully-qualified rewrite the M4 CR materializer applies
752 /// per-tenant) would have had to be threaded through both
753 /// open-coded copies in lockstep or the two consumers would
754 /// silently disagree on which key-template a given edge resolves
755 /// to — the [`WitContract::target`] payload-extraction reading
756 /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
757 /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
758 /// would silently split the [`WitTarget::Store`]-arm rendered
759 /// payload from the actual dedup-key uniqueness axis, a
760 /// two-consumer split at the validator far from the source
761 /// `caixa.lisp` with no field naming the payload-drift root cause.
762 /// Lifting the resolution rule to a typed method on the substrate
763 /// primitive means every downstream store-payload-facing consumer
764 /// of the Aplicacao's per-`:contratos` payload surface reaches for
765 /// exactly one typed dispatch — the resolver's accept-set migrates
766 /// as a unit on any future axis addition.
767 ///
768 /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
769 /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
770 /// accessors on the M3 mesh-slot payload-carrier axis — third and
771 /// final `Option<&str>`-return accessor on the per-`:contratos`
772 /// mesh-slot atom, closes the last unlifted per-`:contratos`
773 /// `Option<String>` axis and completes the "optional per-slot
774 /// payload-carrier scalar" projection pattern the peer HTTP /
775 /// pub-sub arms established across the three payload-shape
776 /// dispatch arms. Named `slot()` to match the storage field's
777 /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
778 /// author-facing label const; the accessor's identity name maps
779 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
780 /// docstring already carries.
781 #[must_use]
782 pub fn slot(&self) -> Option<&str> {
783 self.slot.as_deref()
784 }
785
786 /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
787 /// caller-callee-pair accessor every consumer that constructs an
788 /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
789 /// caller-callee pair keys off — returns the author-declared
790 /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
791 /// owned `(String, String)` tuple, projected through the lifted
792 /// [`WitContract::source`] / [`WitContract::destination`] scalar
793 /// accessors so any future rebrand on the caller-arm / callee-arm
794 /// projection axis (an M4 per-cluster caller-alias table the
795 /// operator pins through a future `:placement`-scoped slot, a
796 /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
797 /// a per-`:membros` alias overlay from the future `:membros
798 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
799 /// acknowledges) reaches every diagnostic-construction site by
800 /// construction.
801 ///
802 /// The `(de, para)` pair is the "typed-edge caller-callee identity in
803 /// owned form" primitive every per-`:contratos` diagnostic variant on
804 /// [`AplicacaoError`] carries alongside its payload-shape arm — the
805 /// nine variants [`AplicacaoError::EmptyWit`],
806 /// [`AplicacaoError::ContratoEndpointEmpty`],
807 /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
808 /// [`AplicacaoError::ContratoEndpointInvalid`],
809 /// [`AplicacaoError::ContratoSubjectEmpty`],
810 /// [`AplicacaoError::ContratoSubjectInvalid`],
811 /// [`AplicacaoError::ContratoSlotEmpty`],
812 /// [`AplicacaoError::ContratoSlotInvalid`], and
813 /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
814 /// para: String` field pair the constructor site reads verbatim off
815 /// the [`WitContract`] the diagnostic points at, so a diagnostic
816 /// whose `de:` and `para:` labels silently drift off the source
817 /// caller/callee — a per-cluster caller-alias rewrite that landed on
818 /// one variant's inline `de: c.de.clone()` field access but not on
819 /// its sibling variant's, an accidental swap of the `de:` and `para:`
820 /// arms in a copy-paste of the constructor block — would emit a
821 /// build-time error whose "which caixa is at fault" question the
822 /// operator answers wrongly, far from the source `caixa.lisp`.
823 ///
824 /// Prior to this lift the `(self.de.clone(), self.para.clone())`
825 /// pair was inlined at seven [`WitContract::target`] error-
826 /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
827 /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
828 /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
829 /// the [`AplicacaoError::ContratoSubjectEmpty`] /
830 /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
831 /// the [`AplicacaoError::ContratoSlotEmpty`] /
832 /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
833 /// two [`AplicacaoSpec::validate`] error-construction sites (the
834 /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
835 /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
836 /// insert-first-seen closure) — nine open-coded `.de.clone() +
837 /// .para.clone()` pairs that expressed no compile-time contract that
838 /// the caller-arm and callee-arm arms of the same diagnostic
839 /// construction reach for the same [`WitContract`] instance or that
840 /// the `de:` and `para:` label pair binds to the fields the author
841 /// declared. Any future rebrand on the axis — an M4 per-cluster
842 /// caller/callee-alias rewrite the operator pins through a future
843 /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
844 /// per-CR fully-qualified namespace prefix the M4
845 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
846 /// per-tenant, a canonicalization pass that lowercases the caller +
847 /// callee identifiers post-parse — would have had to be threaded
848 /// through every open-coded copy in lockstep or one variant's
849 /// diagnostic would silently name a different caller/callee pair
850 /// than its peer, silently degrading the "which caixa is at fault"
851 /// self-locating signal every operator-facing typed diagnostic
852 /// exists to carry. Lifting the pair to a typed method on the
853 /// substrate primitive means every downstream diagnostic-construction
854 /// site reaches for exactly one typed dispatch — the resolver's
855 /// projection migrates as a unit on any future axis addition.
856 ///
857 /// Peer of the sibling per-`:contratos` scalar accessor family
858 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
859 /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
860 /// scalar-value axes — first composite-projection accessor on the
861 /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
862 /// form `.clone()` field-accesses that pair the sibling
863 /// caller/callee accessors' `&str`-return borrowed-form outputs onto
864 /// one typed dispatch. Named `edge_pair()` to reflect the identity
865 /// name of the projected tuple (the typed-edge caller-callee pair,
866 /// distinct from the sibling triple-projection
867 /// [`WitContract::edge_triple`] accessor that folds the local `edge`
868 /// closure in [`WitContract::target`] + the paired
869 /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
870 /// site's `(de, para, wit)` triple onto one typed dispatch).
871 #[must_use]
872 pub fn edge_pair(&self) -> (String, String) {
873 (self.source().to_string(), self.destination().to_string())
874 }
875
876 /// Owned form of the `(:contratos :de, :contratos :para, :contratos
877 /// :wit)` triple every per-edge diagnostic constructor that names
878 /// all three axes threads verbatim into its `de:` / `para:` /
879 /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
880 /// / missing-target / invalid-wit / capability-with-payload arms
881 /// (eight sites all shape `let (de, para, wit) = edge();
882 /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
883 /// accessor landed) and the sibling
884 /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
885 /// constructor (which paired `edge_pair()` for the `(de, para)`
886 /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
887 /// typed-dispatch + raw-field-access shape the sibling accessor
888 /// family already flagged as a drift risk). Nine total call sites
889 /// collapse onto this helper.
890 ///
891 /// Lifted with the same one-source-of-truth discipline
892 /// [`WitContract::edge_pair`] carries on the paired
893 /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
894 /// arms compose through the lifted [`WitContract::source`] /
895 /// [`WitContract::destination`] / [`WitContract::world_ref`]
896 /// scalar accessors byte-for-byte (pinned by the paired
897 /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
898 /// composition-pin), so any future rebrand on the per-`:contratos`
899 /// caller / callee / world-ref axis (an M4 per-cluster
900 /// caller/callee-alias rewrite the operator pins through a future
901 /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
902 /// per-CR fully-qualified namespace prefix the M4
903 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
904 /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
905 /// on `source()` / `destination()`, a per-CR canonicalization pass
906 /// that lowercases the WIT world ref post-parse) migrates as a
907 /// single caixa-core edit rather than a coordinated rewrite of
908 /// nine open-coded triple-constructors.
909 ///
910 /// Peer of the sibling per-`:contratos` composite-projection
911 /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
912 /// composite-value axes — closes the last unlifted owned-form
913 /// composite-tuple axis on the per-`:contratos` diagnostic-
914 /// construction surface. Named `edge_triple()` to reflect the
915 /// identity name of the projected tuple (the typed-edge
916 /// caller-callee-wit triple, sibling to the caller-callee-only
917 /// pair `edge_pair()` returns).
918 #[must_use]
919 pub fn edge_triple(&self) -> (String, String, String) {
920 (
921 self.source().to_string(),
922 self.destination().to_string(),
923 self.world_ref().to_string(),
924 )
925 }
926
927 /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
928 /// dedups typed edges keys off — routes through the lifted
929 /// [`WitContract::source`] / [`WitContract::destination`] /
930 /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
931 /// [`WitContract::subject`] / [`WitContract::slot`] scalar
932 /// accessors so the tuple's six arms and the [`ContratoIdentity`]
933 /// type alias's six axes migrate as a unit on any future axis
934 /// addition (adding a seventh field to [`WitContract`] is one
935 /// [`ContratoIdentity`] alias edit + one accessor addition + one
936 /// arm here, not a coordinated rewrite of every open-coded
937 /// six-tuple builder that dedups on the identity axis).
938 ///
939 /// Sibling of [`WitContract::edge_pair`] /
940 /// [`WitContract::edge_triple`] on the composite-projection axis:
941 /// the pair projects the caller-callee axes, the triple extends it
942 /// with the world-ref, this method extends it with the three
943 /// payload-carrier axes. Every projection returns the same six
944 /// scalar accessors' outputs; the three methods differ only in
945 /// which arms they surface.
946 #[must_use]
947 pub fn identity(&self) -> ContratoIdentity<'_> {
948 (
949 self.source(),
950 self.destination(),
951 self.world_ref(),
952 self.endpoint(),
953 self.subject(),
954 self.slot(),
955 )
956 }
957
958 /// True when this contract targets an HTTP-shaped WIT world.
959 #[must_use]
960 pub fn is_http(&self) -> bool {
961 wit_shape_is_http(self.world_ref())
962 }
963
964 /// True when this contract targets a pub-sub-shaped WIT world.
965 #[must_use]
966 pub fn is_pubsub(&self) -> bool {
967 wit_shape_is_pubsub(self.world_ref())
968 }
969
970 /// True when this contract targets a key/value-shaped WIT world.
971 #[must_use]
972 pub fn is_store(&self) -> bool {
973 wit_shape_is_store(self.world_ref())
974 }
975
976 /// True when this contract targets *none* of the three known payload-
977 /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
978 /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
979 /// open on the [`WitContract`] surface. Returns the exact-inverse
980 /// disjunction of the peer trio — `true` when none of the three
981 /// prefix-set predicates matches the raw `:contratos :wit` value; the
982 /// author-declared WIT world is a pure typed capability edge with no
983 /// payload selector (the shape [`WitContract::target`] projects onto
984 /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
985 /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
986 ///
987 /// The `:contratos :wit` shape-space is closed at four arms
988 /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
989 /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
990 /// everything else on the payload-less capability arm), and every
991 /// downstream consumer that must filter contratos by shape-class
992 /// keys off the four sibling predicates (the [`WitContract::target`]
993 /// dispatch's implicit `else` after the three payload-shape arm
994 /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
995 /// every future substrate-side capability-shape-only emitter — the
996 /// M4 per-Aplicacao WIT-registry capability-import materializer, the
997 /// future `feira app graph --capability` per-Aplicacao capability-
998 /// column filter, the future per-cluster capability-scope reconciler
999 /// that skips L4/L7 emission for payload-less edges since Cilium
1000 /// can't introspect WASI capability calls, the future
1001 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1002 /// shape shape-count histogram). Every such consumer reaches for one
1003 /// typed dispatch on the substrate primitive so the "which arm
1004 /// carries the capability-only shape?" answer lives at one caixa-core
1005 /// edit rather than open-coded across per-consumer
1006 /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1007 /// negations, each of which would silently drop a future fourth
1008 /// payload-arm addition without a compile-time signal at the
1009 /// consumer site.
1010 ///
1011 /// Prior to this lift the "not one of the three known payload
1012 /// shapes" classification sat inline at [`WitContract::target`]'s
1013 /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1014 /// [`WitTarget::Capability`] admission arm after the three `if
1015 /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1016 /// { … }` guards) with no named accessor for downstream consumers
1017 /// to reach through. A future substrate-side capability-only
1018 /// filter or a future capability-scope reconciler would have had to
1019 /// re-inline the same triplet negation at every emit site with no
1020 /// compile-time link back to the sibling trio, and a future arm
1021 /// addition (a hypothetical fourth payload-shape prefix set — a
1022 /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1023 /// import carrier per the sibling [`wit_shape_matches`] docstring's
1024 /// trajectory bullet) would land the new predicate on the payload-
1025 /// carrying trio and silently misclassify the new shape as
1026 /// capability at every triplet-negation consumer site, propagating
1027 /// the drift far from the caixa-core prefix-set commit.
1028 ///
1029 /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1030 /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1031 /// trio into a 4-way partition witness on the raw `:contratos :wit`
1032 /// axis, mirroring the paired post-projection [`WitTarget`]
1033 /// `gen_platform::IsVariant`-derived 4-way predicate set
1034 /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1035 /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1036 /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1037 /// arm-set). The two typed axes — pre-projection on the raw
1038 /// `:contratos :wit` string, post-projection on the validated typed
1039 /// view — now carry a matched 4-arm predicate discipline: every
1040 /// arm on the closed [`WitTarget`] set has a peer pre-projection
1041 /// predicate on the [`WitContract`] surface, and any future
1042 /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1043 /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1044 /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1045 /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1046 /// pre-projection axis through a matching peer prefix-set + peer
1047 /// predicate lift by construction — the compile-time exhaustiveness
1048 /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1049 /// the post-projection accessor family stays in sync, and the sibling
1050 /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1051 /// partition-witness pin locks the pre-projection classification in
1052 /// load-bearing so a peer prefix-set addition that widened one arm's
1053 /// accept-set without shrinking the [`Self::is_capability`] accept-set
1054 /// surfaces as a test failure at caixa-core build time rather than a
1055 /// silent per-consumer split at renderer emit time.
1056 ///
1057 /// Composes byte-for-byte through the lifted peer trio
1058 /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1059 /// any future rebrand of any prefix-set const flows through this
1060 /// method by construction without a coordinated per-consumer rewrite
1061 /// (pinned by the sibling
1062 /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1063 /// composition-witness).
1064 ///
1065 /// Note: purely syntactic classification on the `:wit` prefix-set —
1066 /// unlike [`Self::target`], which additionally rejects value-shape-
1067 /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1068 /// package) via [`crate::render::is_wit_world_ref`] and payload-
1069 /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1070 /// structurally malformed returns `true` from `is_capability()` (the
1071 /// prefix set matches nothing), and the surrounding
1072 /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1073 /// is where the [`AplicacaoError::EmptyWit`] /
1074 /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1075 /// predicate is the classifier, not the validator.
1076 #[must_use]
1077 pub fn is_capability(&self) -> bool {
1078 wit_shape_is_capability(self.world_ref())
1079 }
1080
1081 /// True when this contract's caller equals its callee — a
1082 /// structurally degenerate typed edge that no `:contratos` entry can
1083 /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1084 /// Servico B" is an *inter*-Servico contract between two distinct
1085 /// graph nodes). A Servico contracting with itself resolves to an
1086 /// in-process call the wasm-engine never routes through the mesh at
1087 /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1088 /// per-edge policy can express the intended shape — the pub-sub
1089 /// path silently rendered a self-allow rule that is a no-op (intra-
1090 /// pod traffic bypasses the mesh entirely), and the synchronous
1091 /// paths surfaced as a misleading `ContratoCycle` whose path was
1092 /// `["cart", "cart"]` — framing a self-edge as a multi-node
1093 /// deadlock. Every downstream consumer that must reject the shape
1094 /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1095 /// gate at caixa-core/src/aplicacao.rs:5559, every future
1096 /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1097 /// axis, every future adjacency-graph builder that must skip self-
1098 /// edges rather than fold them into an incidental cycle) now keys
1099 /// off exactly one typed dispatch on the substrate primitive, so
1100 /// any future rebrand on the axis (an M4-typed-caller enum whose
1101 /// identity comparison rule the accessor could route through, an
1102 /// operator-side per-cluster caller/callee-alias table the
1103 /// materializer resolves per-CR before the equality probe, a
1104 /// promotion of the pointwise `==` to a set-membership check once
1105 /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1106 /// so a per-replica self-edge is rejected under the same predicate)
1107 /// migrates as a single caixa-core edit rather than a coordinated
1108 /// rewrite of every downstream self-edge consumer. Composes
1109 /// byte-for-byte through the lifted [`Self::source`] /
1110 /// [`Self::destination`] scalar accessors — the accessor pair every
1111 /// per-`:contratos` scalar-value axis already routes through — so
1112 /// any future rebrand of the underlying `:de` / `:para` storage
1113 /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1114 /// a per-Aplicacao interning arena the M4 CR materializer authors,
1115 /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1116 /// same one body without a coordinated per-consumer rewrite.
1117 ///
1118 /// Sibling in shape to the peer per-`:contratos` shape-predicate
1119 /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1120 /// on the `:wit` world-ref axis — extended onto the per-edge
1121 /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1122 /// partition the WIT-shape-space; `is_self_loop` partitions the
1123 /// caller-callee identity-space. Named `is_self_loop()` to reflect
1124 /// the graph-theoretic identity of the shape (a loop from a graph
1125 /// node to itself, distinct from the sibling multi-node
1126 /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1127 /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1128 /// variant already carrying the term.
1129 #[must_use]
1130 pub fn is_self_loop(&self) -> bool {
1131 self.source() == self.destination()
1132 }
1133
1134 /// Typed view of the contract's payload target. Enforces that the
1135 /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1136 /// fields agree, and that each carried value is itself
1137 /// value-shape valid:
1138 ///
1139 /// - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1140 /// non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1141 /// `PathPrefix` invariant — same shape required of `:entrada
1142 /// :paths`)
1143 /// - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1144 /// non-empty (NATS / Kafka publish without a subject is a
1145 /// no-op subscribe, never the author's intent)
1146 /// - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1147 /// non-empty (an empty slot template addresses the bucket
1148 /// root, defeating the per-key isolation the slot exists for)
1149 /// - Anything else ⇒ none of the three; the contract is a pure
1150 /// typed capability edge with no payload selector.
1151 ///
1152 /// Translates the Apollo Federation discipline ("conflicts are
1153 /// errors at compile time, not warnings at runtime";
1154 /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1155 /// a contract whose WIT shape disagrees with its target field, or
1156 /// whose target field carries a value-shape-invalid string, is a
1157 /// build error — not a silent renderer drop. The returned
1158 /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1159 /// non-empty (and absolute, for `Http`); every downstream consumer
1160 /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1161 /// the M4 per-edge policy resolver) can rely on that without
1162 /// re-checking.
1163 pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1164 // Route the HTTP-shaped payload-target extraction through the
1165 // lifted [`WitContract::endpoint`] accessor rather than the raw
1166 // `self.endpoint.as_deref()` field access — the two production
1167 // consumers of the per-`:contratos :endpoint` HTTP-shaped
1168 // payload-carrier scalar (this method's Http-arm payload
1169 // extraction, the [`AplicacaoSpec::validate`] duplicate-
1170 // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1171 // off exactly one typed dispatch on the substrate primitive, so
1172 // any future rebrand on the axis (an M4 per-cluster endpoint-
1173 // alias rewrite, a per-CR fully-qualified path prefix the M4
1174 // materializer applies per-tenant, an M4 promotion from
1175 // `Option<String>` to a typed HTTP path-template enum) migrates
1176 // as a single caixa-core edit rather than a coordinated rewrite
1177 // of the two call sites — peer of the sibling M3 per-`:placement`
1178 // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1179 // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1180 // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1181 let endpoint = self.endpoint();
1182 let subject = self.subject();
1183 // Route the store-arm payload-carrier scalar through the
1184 // lifted [`WitContract::slot`] accessor rather than the raw
1185 // `self.slot.as_deref()` field access — the two production
1186 // consumers of the per-`:contratos :slot` key/value-store-
1187 // shaped payload-carrier scalar (this method's Store-arm
1188 // payload extraction, the [`AplicacaoSpec::validate`]
1189 // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1190 // arm) now key off exactly one typed dispatch on the substrate
1191 // primitive. Closes the last unlifted per-`:contratos`
1192 // `Option<String>` axis, completing the payload-carrier
1193 // accessor family peer of the sibling per-`:contratos`
1194 // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1195 // (90de675) lifts across the HTTP / pub-sub arms.
1196 let slot = self.slot();
1197 // Route the local `(de, para, wit)` triple-projection closure
1198 // through the lifted [`WitContract::edge_triple`] typed accessor
1199 // rather than re-inlining `(self.de.clone(), self.para.clone(),
1200 // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1201 // triple-carrying diagnostic constructors below (wrong-target /
1202 // missing-target on all three payload arms + capability-with-
1203 // payload + invalid-wit) now key off exactly one typed dispatch
1204 // on the substrate-primitive composite projection, sibling to
1205 // the peer [`WitContract::edge_pair`]-routed
1206 // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1207 // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1208 // diagnostic constructors on the same per-`:contratos`
1209 // diagnostic-construction surface.
1210 let edge = || self.edge_triple();
1211
1212 // The `:wit` value drives every downstream dispatch — the
1213 // is_http/is_pubsub/is_store prefix matchers below, the
1214 // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1215 // exclusion. Until this gate landed `target()` accepted any
1216 // non-empty string and silently demoted unrecognized shapes to
1217 // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1218 // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1219 // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1220 // package, the paste-from-binary footgun a multi-line blob
1221 // accidentally landing in the slot, the un-percent-encoded
1222 // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1223 // routing, got L4-only" footgun. Empty is still pre-checked at
1224 // the [`AplicacaoSpec::validate`] call site via the narrower
1225 // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1226 // validate layer); the value-shape gate here picks up the
1227 // structurally-invalid non-empty cases the empty check misses,
1228 // and remains correct under direct `target()` calls outside
1229 // validate (the predicate's defensive empty arm returns a
1230 // parser-shaped reason rather than silently falling through to
1231 // the Capability arm). Same trajectory as c4213a4 (WitContract
1232 // endpoint/subject/slot value-shape gates lifted into
1233 // `target()`) on the peer payload axes.
1234 if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
1235 let (de, para, wit) = edge();
1236 return Err(AplicacaoError::ContratoWitInvalid {
1237 de,
1238 para,
1239 wit,
1240 reason,
1241 });
1242 }
1243
1244 if self.is_http() {
1245 if subject.is_some() || slot.is_some() {
1246 let (de, para, wit) = edge();
1247 return Err(AplicacaoError::ContratoWrongTarget {
1248 de,
1249 para,
1250 wit,
1251 expected: WitTarget::HTTP_FIELD_NAME,
1252 });
1253 }
1254 let ep = endpoint.ok_or_else(|| {
1255 let (de, para, wit) = edge();
1256 AplicacaoError::ContratoMissingTarget {
1257 de,
1258 para,
1259 wit,
1260 expected: WitTarget::HTTP_FIELD_NAME,
1261 }
1262 })?;
1263 if ep.is_empty() {
1264 let (de, para) = self.edge_pair();
1265 return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1266 }
1267 if !ep.starts_with('/') {
1268 let (de, para) = self.edge_pair();
1269 return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1270 de,
1271 para,
1272 endpoint: ep.to_string(),
1273 });
1274 }
1275 // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1276 // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1277 // API v1 HTTPPathMatch.value admission grammar with the
1278 // sibling `:entrada :paths` axis. Until this gate landed
1279 // `target()` only refused the empty string + the missing-
1280 // leading-`/` form; a structurally invalid endpoint
1281 // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1282 // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1283 // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1284 // path-traversal segment, the >1024-byte slug) silently
1285 // passed validate and the failure surfaced at apply time
1286 // as a Cilium policy rejection / silent traffic drop, far
1287 // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1288 // grammar `:entrada :paths` already gates (55410e4), now
1289 // shared with `:contratos :endpoint` through the lifted
1290 // `crate::render::is_gateway_api_http_path` predicate.
1291 if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1292 let (de, para) = self.edge_pair();
1293 return Err(AplicacaoError::ContratoEndpointInvalid {
1294 de,
1295 para,
1296 endpoint: ep.to_string(),
1297 reason,
1298 });
1299 }
1300 return Ok(WitTarget::Http { endpoint: ep });
1301 }
1302 if self.is_pubsub() {
1303 if endpoint.is_some() || slot.is_some() {
1304 let (de, para, wit) = edge();
1305 return Err(AplicacaoError::ContratoWrongTarget {
1306 de,
1307 para,
1308 wit,
1309 expected: WitTarget::PUBSUB_FIELD_NAME,
1310 });
1311 }
1312 let s = subject.ok_or_else(|| {
1313 let (de, para, wit) = edge();
1314 AplicacaoError::ContratoMissingTarget {
1315 de,
1316 para,
1317 wit,
1318 expected: WitTarget::PUBSUB_FIELD_NAME,
1319 }
1320 })?;
1321 if s.is_empty() {
1322 let (de, para) = self.edge_pair();
1323 return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1324 }
1325 // The `:subject` lands at runtime as the NATS subject the
1326 // producer publishes to and the consumer subscribes from.
1327 // Until this gate landed `target()` only refused the
1328 // empty string; a structurally invalid subject
1329 // (`"foo..bar"` — empty token between separators,
1330 // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1331 // server's subject parser rejects, `"foo bar"` —
1332 // un-percent-encoded whitespace, `"foo.café"` —
1333 // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1334 // empty leading/trailing tokens, the >256-byte
1335 // paste-from-binary slug) silently passed validate and
1336 // the failure surfaced at runtime as a NATS server-side
1337 // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1338 // a silent message drop, far from the source caixa.lisp.
1339 // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1340 // trajectory `:contratos :endpoint` (4f0390b) and
1341 // `:contratos :wit` (6226bf4) already gate, now shared
1342 // with `:contratos :subject` through the lifted
1343 // `crate::render::is_nats_subject` predicate.
1344 if let Err(reason) = crate::render::is_nats_subject(s) {
1345 let (de, para) = self.edge_pair();
1346 return Err(AplicacaoError::ContratoSubjectInvalid {
1347 de,
1348 para,
1349 subject: s.to_string(),
1350 reason,
1351 });
1352 }
1353 return Ok(WitTarget::PubSub { subject: s });
1354 }
1355 if self.is_store() {
1356 if endpoint.is_some() || subject.is_some() {
1357 let (de, para, wit) = edge();
1358 return Err(AplicacaoError::ContratoWrongTarget {
1359 de,
1360 para,
1361 wit,
1362 expected: WitTarget::STORE_FIELD_NAME,
1363 });
1364 }
1365 let sl = slot.ok_or_else(|| {
1366 let (de, para, wit) = edge();
1367 AplicacaoError::ContratoMissingTarget {
1368 de,
1369 para,
1370 wit,
1371 expected: WitTarget::STORE_FIELD_NAME,
1372 }
1373 })?;
1374 if sl.is_empty() {
1375 let (de, para) = self.edge_pair();
1376 return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1377 }
1378 // Value-shape gate on the third (and last) typed payload
1379 // axis the `WitContract::target` dispatch carries — the
1380 // peer of [`crate::render::is_gateway_api_http_path`] for
1381 // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1382 // for `:subject` (63e18a0). Until this gate landed
1383 // `target()` only refused the empty string; a structurally
1384 // invalid slot (`"check out/$order"` — un-percent-encoded
1385 // whitespace whose runtime behavior varies unpredictably
1386 // across kv backends, `"checkout/\x01order"` — control
1387 // character that Redis admits but corrupts on next read
1388 // and DynamoDB rejects outright, `"chéckout/$order"` —
1389 // un-percent-encoded non-ASCII byte each backend re-encodes
1390 // differently, `"checkout\n/$order"` — embedded newline,
1391 // the 513-byte paste-from-binary slug) silently passed
1392 // validate and surfaced at runtime as a per-backend kv
1393 // write rejection (DynamoDB / etcd) or as a silent
1394 // next-read corruption (Redis-via-RESP3), far from the
1395 // source caixa.lisp with no field naming which `:contratos`
1396 // edge carried the typo. The lifted predicate makes the
1397 // kv-backend intersection-floor a substrate-level
1398 // invariant at validate time, not a runtime "this passed
1399 // validate but the kv backend rejected on first write"
1400 // surprise — closes the typed payload-axis value-shape
1401 // trajectory across all three legs of the four
1402 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1403 // that caixa-mesh + the future kv emitters land in.
1404 if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1405 let (de, para) = self.edge_pair();
1406 return Err(AplicacaoError::ContratoSlotInvalid {
1407 de,
1408 para,
1409 slot: sl.to_string(),
1410 reason,
1411 });
1412 }
1413 return Ok(WitTarget::Store { slot: sl });
1414 }
1415
1416 // Unrecognized WIT world — must not carry any payload target.
1417 if endpoint.is_some() || subject.is_some() || slot.is_some() {
1418 let (de, para, wit) = edge();
1419 return Err(AplicacaoError::ContratoWrongTarget {
1420 de,
1421 para,
1422 wit,
1423 expected: WitTarget::CAPABILITY_EXPECTED,
1424 });
1425 }
1426 Ok(WitTarget::Capability)
1427 }
1428
1429 /// Substrate-canonical post-validation projection of the typed
1430 /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1431 /// downstream of an [`AplicacaoSpec`] that has already crossed the
1432 /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1433 /// [`typed_view`]-shaped entry point that composes `validate` into
1434 /// the projection) reaches through when it needs the typed
1435 /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1436 /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1437 /// coherence for every `:contratos` entry. The peer accessor to the
1438 /// [`Self::target`] `Result`-returning validator on the same
1439 /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1440 /// pre-validation validator that computes the projection *and* raises
1441 /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1442 /// (`:wit`, payload) mismatch; this method is the post-validation
1443 /// projection every downstream consumer reaches through once the
1444 /// pre-validation gate has succeeded.
1445 ///
1446 /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1447 ///
1448 /// Prior to this lift the "call `.target()` then `.expect(…)` with
1449 /// the same message" pattern sat inline at two production sites with
1450 /// no compile-time link between them: the
1451 /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1452 /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1453 /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1454 /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1455 /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1456 /// (`c.target().expect("validated by typed_view").graph_label()`),
1457 /// each open-coding the same `.target().expect("validated by
1458 /// typed_view")` pair with the message spelled twice. A future
1459 /// vocabulary shift on the panic-message axis (a tightening from
1460 /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1461 /// validate"` as the substrate's validator entry-point vocabulary
1462 /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1463 /// panic to a `debug_assert` under a `--release` build profile) would
1464 /// have had to be threaded through both open-coded call sites in
1465 /// lockstep or one consumer would silently disagree with the peer on
1466 /// which invariant the panic message names. Same "same shape written
1467 /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1468 /// discipline the sibling [`Self::edge_pair`] /
1469 /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1470 /// lifts already establish on the paired composite-projection axis;
1471 /// this lift extends it onto the post-validation typed-view axis.
1472 ///
1473 /// Every future downstream consumer of the projected typed view
1474 /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1475 /// CR materializer's per-edge admission webhook, the future
1476 /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1477 /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1478 /// resolver, the future `feira app graph --l7` / `--pubsub` /
1479 /// `--kv` per-shape column emitters) reaches through this one typed
1480 /// dispatch on the substrate primitive rather than an open-coded
1481 /// per-consumer `.target().expect(…)` pair with the message
1482 /// re-inlined. The invariant the accessor's panic path pins — "this
1483 /// call is only reachable after [`AplicacaoSpec::validate`] has
1484 /// succeeded on the containing spec" — is the substrate's answer to
1485 /// give exactly once, at the primitive, not once per consumer.
1486 ///
1487 /// # Panics
1488 ///
1489 /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1490 /// would return an `Err` — i.e. if this contract's
1491 /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1492 /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1493 /// this accessor only from a code path that has already reached the
1494 /// containing [`AplicacaoSpec`] through a validating entry-point
1495 /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1496 /// [`typed_view`] compose, the future M4 CR admission webhook's
1497 /// per-CR validate). Use [`Self::target`] instead on any pre-
1498 /// validation code path.
1499 ///
1500 /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1501 #[must_use]
1502 pub fn target_projected(&self) -> WitTarget<'_> {
1503 self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1504 }
1505
1506 /// Canonical panic message the [`Self::target_projected`]
1507 /// post-validation projection accessor threads through when the
1508 /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1509 /// has succeeded" precondition. Lifted as a `pub const` on the
1510 /// [`WitContract`] surface so the byte-string lives in one place
1511 /// across the substrate — the [`Self::target_projected`] method
1512 /// body, the two prior production call sites' comments now naming
1513 /// the const, and every future consumer that must format-match the
1514 /// panic-message shape (a future test suite that asserts the panic-
1515 /// message byte-string across a fuzzed invalid-contract corpus,
1516 /// a future custom-panic hook in `caixa-operator` that surfaces the
1517 /// message with per-`:contratos` telemetry, the future admission
1518 /// webhook's per-CR validate-error report) reaches through the same
1519 /// canonical `&'static str`. A future rebrand on the panic-message
1520 /// axis (a tightening from `"validated by typed_view"` to `"validated
1521 /// by AplicacaoSpec::validate"` as the substrate's validator
1522 /// entry-point vocabulary sharpens once caixa-core grows a
1523 /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1524 /// [`typed_view`]) lands at one caixa-core edit rather than a
1525 /// coordinated per-consumer sweep — same "one canonical declaration
1526 /// per axis, next to the accessor that reads it" discipline the peer
1527 /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1528 /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1529 /// const family already establishes on the paired per-consumer-axis
1530 /// diagnostic-scalar surface.
1531 pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1532}
1533
1534/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1535/// gate (see [`AplicacaoSpec::validate`]): every field that
1536/// distinguishes one contract from another, in declaration order
1537/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1538/// with equal [`ContratoIdentity`]s are the same typed edge declared
1539/// twice — the graph-edge analogue of duplicate `:membros` /
1540/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1541/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1542/// clippy's `type_complexity` lint (and so a future axis added to
1543/// `WitContract` is one alias edit, not a coordinated rewrite of
1544/// every set instantiation).
1545pub type ContratoIdentity<'a> = (
1546 &'a str,
1547 &'a str,
1548 &'a str,
1549 Option<&'a str>,
1550 Option<&'a str>,
1551 Option<&'a str>,
1552);
1553
1554/// Typed view of a [`WitContract`]'s payload target. Each variant
1555/// carries the field its WIT shape requires; constructing a `Http`
1556/// view without an endpoint is impossible by the type system.
1557///
1558/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1559/// instead of probing `Option<String>` fields one by one — the
1560/// "which payload field is set?" question is answered once, at
1561/// validation time.
1562#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1563pub enum WitTarget<'a> {
1564 /// HTTP-shaped WIT world. Carries the configured request path.
1565 Http { endpoint: &'a str },
1566 /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1567 ///
1568 /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1569 /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1570 /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1571 /// method name byte-identical to the sibling
1572 /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1573 /// arm-discriminator that routes through
1574 /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1575 /// through `matches!` on the variant), so the two arm-discriminator
1576 /// axes — target-side variant-arm and shape-side ref-prefix — reach
1577 /// every downstream consumer through the same `is_pubsub()` name.
1578 #[is_variant(name = "pubsub")]
1579 PubSub { subject: &'a str },
1580 /// Key-value-shaped WIT world. Carries the slot template.
1581 Store { slot: &'a str },
1582 /// A typed capability edge with no payload selector — the WIT
1583 /// world stands on its own (rare; reserved for plain capability
1584 /// imports or M4-and-later WIT worlds we haven't shaped yet).
1585 Capability,
1586}
1587
1588impl<'a> WitTarget<'a> {
1589 /// Canonical author-facing `:contratos` payload field name for the
1590 /// HTTP-shaped arm — the `expected: &'static str` scalar the
1591 /// [`AplicacaoError::ContratoMissingTarget`] /
1592 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1593 /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1594 /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1595 /// the `feira app graph` verb prints. Peer of
1596 /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1597 /// on the payload-field-name axis; declared as a peer const next
1598 /// to the [`WitTarget::Http`] variant so a future rename on the
1599 /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1600 /// :endpoint …)))` field lands in exactly one place, not scattered
1601 /// across the [`WitContract::target`] gate's six `expected:`
1602 /// literals, the label template, and every downstream consumer
1603 /// that prints a per-arm prefix. Same trajectory as the peer
1604 /// [`WitTarget::label`] lift (174e96a): a single source of truth
1605 /// for the arm's shape, next to the variant declaration.
1606 pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1607 /// Canonical author-facing `:contratos` payload field name for the
1608 /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1609 /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1610 /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1611 pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1612 /// Canonical author-facing `:contratos` payload field name for the
1613 /// key/value-store-shaped arm. Peer of
1614 /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1615 /// on the payload-field-name axis; see
1616 /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1617 pub const STORE_FIELD_NAME: &'static str = "slot";
1618
1619 /// Canonical stable human-readable label the payload-less
1620 /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1621 /// the byte-string every consumer that formats a payload-less
1622 /// typed capability edge as text lands on (the
1623 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1624 /// naming which identical edge was declared twice, the future
1625 /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1626 /// policy resolver's audit view, the operator's mesh-graph audit).
1627 /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1628 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1629 /// author-facing label-scalar consts — the same
1630 /// "one canonical declaration per arm, next to the variant, so a
1631 /// future rename lands in one place" discipline extended to the
1632 /// payload-less arm. Until this lift landed the byte-string sat
1633 /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1634 /// match arm, once in the pin test asserting the label's
1635 /// [`WitTarget::Capability`] output — with no compile-time link
1636 /// between the two: a rebrand on either side (an operator-facing
1637 /// vocabulary shift, a per-consumer disambiguation like
1638 /// `"(capability — no payload; typed edge only)"`) would silently
1639 /// desynchronize until a downstream consumer surfaced the drift at
1640 /// runtime.
1641 pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1642
1643 /// Canonical `expected:` scalar the
1644 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1645 /// through for the payload-less [`WitTarget::Capability`] arm — the
1646 /// byte-string authors read as "this WIT world's shape is not one
1647 /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1648 /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1649 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1650 /// [`Self::STORE_FIELD_NAME`] consts on the
1651 /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1652 /// same "which payload field name goes in the diagnostic" dispatch
1653 /// the three payload-arm consts cover, extended to the payload-less
1654 /// arm. Until this lift landed the byte-string sat twice — once
1655 /// inline in the [`Self::target`] Capability-arm rejection at the
1656 /// production dispatch, once in the pin test asserting the
1657 /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1658 /// no compile-time link between the two: a rebrand on either side
1659 /// (an author-facing vocabulary shift to `"capability"` /
1660 /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1661 /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1662 /// [`WitTarget::Capability`] into per-shape peers) would silently
1663 /// desynchronize until a downstream consumer surfaced the drift at
1664 /// runtime. Same "one canonical declaration per arm, next to the
1665 /// variant, so a future rename lands in one place" discipline the
1666 /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1667 /// established for the payload-less arm's human-readable label
1668 /// axis; this lift extends it onto the peer diagnostic-scalar axis
1669 /// so both halves of the "how does the Capability arm surface at
1670 /// its two consumer axes (human-readable label, wrong-target
1671 /// diagnostic)" pipeline route through peer consts declared next
1672 /// to the variant.
1673 ///
1674 /// Pairwise-distinctness against the three payload-arm scalars
1675 /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1676 /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1677 /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1678 /// test — the 4-way closure of the 3-way
1679 /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1680 /// the `ContratoWrongTarget::expected` axis, matching the peer
1681 /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1682 /// scalar-value distinctness discipline the sibling M3 typed-enum
1683 /// discriminator axis already carries.
1684 pub const CAPABILITY_EXPECTED: &'static str = "none";
1685
1686 /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1687 /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1688 /// as under [`Self::graph_label`] — the sibling
1689 /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1690 /// payload-column axis (the graph verb spells payload-less as
1691 /// `(capability-only)`, distinct from the duplicate-`:contratos`
1692 /// diagnostic's `(capability — no payload)` on the human-readable
1693 /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1694 /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1695 /// family — extends the "one canonical declaration per arm, next to
1696 /// the variant, so a future rename lands in one place" discipline
1697 /// onto the third payload-less-arm consumer axis (`feira app graph`
1698 /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1699 /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1700 /// axis).
1701 ///
1702 /// Until this lift landed the byte-string sat inline in
1703 /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1704 /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1705 /// `"(capability-only)".to_string()` literal, with no compile-time link
1706 /// back to the [`WitTarget::Capability`] variant declaration nor to
1707 /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1708 /// peer consts already carrying the "one canonical declaration per
1709 /// payload-less-arm consumer axis" discipline. A rebrand on either
1710 /// side (the graph verb's operator-facing vocabulary tightening from
1711 /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1712 /// the WIT registry vocabulary sharpens, an M4 split of
1713 /// [`Self::Capability`] into per-shape peers) would silently
1714 /// desynchronize the graph-verb byte-string from the paired
1715 /// per-arm-adjacent const and land two spellings of the same axis in
1716 /// two spots.
1717 pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1718
1719 /// The `(author-facing field name, payload)` pair this typed target
1720 /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1721 /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1722 /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1723 /// [`Self::Store`], `None` for the payload-less
1724 /// [`Self::Capability`] arm.
1725 ///
1726 /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1727 /// (formats `":{field} {payload:?}"` on `Some`, falls to
1728 /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1729 /// (returns the first component) route through, so a future
1730 /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1731 /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1732 /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1733 /// exactly one new match-arm here (a compile-time exhaustiveness
1734 /// error otherwise), not a coordinated three-way rewrite of the
1735 /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1736 /// + every downstream consumer that reaches for the pair.
1737 ///
1738 /// Until this lift landed the three payload arms sat in
1739 /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1740 /// invocations (one per variant, each hand-quoting the paired
1741 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1742 /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1743 /// "same shape, written N times" duplication THEORY.md §I.3.5
1744 /// ("Generation first, composition second, hand-authoring last;
1745 /// the duplication budget is zero") promotes to a build-time
1746 /// concern, with each per-arm site paired to its own const with no
1747 /// compile-time link between the format template and the arm's
1748 /// payload extraction.
1749 #[must_use]
1750 pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1751 match *self {
1752 WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1753 WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1754 WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1755 WitTarget::Capability => None,
1756 }
1757 }
1758
1759 /// The canonical author-facing `:contratos` payload field name
1760 /// this typed target arm carries (`Http` → `Some("endpoint")`,
1761 /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1762 /// `None` for the payload-less `Capability` arm.
1763 ///
1764 /// Routes through [`Self::payload_pair`] — the single 4-arm
1765 /// dispatch [`Self::label`] also reads — so a future variant
1766 /// addition is one match-arm edit at [`Self::payload_pair`], not a
1767 /// per-consumer rewrite. Same "exhaustive-match at one canonical
1768 /// dispatch, thin projections at each consumer" trajectory the
1769 /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1770 /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1771 #[must_use]
1772 pub const fn field_name(&self) -> Option<&'static str> {
1773 match self.payload_pair() {
1774 Some((f, _)) => Some(f),
1775 None => None,
1776 }
1777 }
1778
1779 /// The underlying scalar the payload-carrying arm carries — the
1780 /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1781 /// subject ([`Self::PubSub`] `:subject`), or slot template
1782 /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1783 /// `&'a str` storage — or `None` on the payload-less
1784 /// [`Self::Capability`] arm.
1785 ///
1786 /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1787 /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1788 /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1789 /// the paired sub-selector axis. Both per-half accessors read from
1790 /// one authoritative match, so a future [`WitTarget`] variant
1791 /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1792 /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1793 /// on [`Self::payload_pair`] and both per-half projections + every
1794 /// downstream consumer picks the new arm up by construction — no
1795 /// coordinated N-way rewrite across the paired accessor dispatches,
1796 /// the [`Self::label`] / [`Self::graph_label`] format templates,
1797 /// and every future WIT-registry-shaped consumer.
1798 ///
1799 /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1800 /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1801 /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1802 /// both per-half projections as thin readers, every downstream
1803 /// consumer through the same match" discipline extended onto the
1804 /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1805 /// gap between the two paired-dispatch surfaces: the peer
1806 /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1807 /// the first-component projection until this lift; the second-
1808 /// component sibling now sits alongside so both halves reach every
1809 /// future consumer through the same substrate-primitive dispatch.
1810 ///
1811 /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1812 #[must_use]
1813 pub const fn payload(&self) -> Option<&'a str> {
1814 match self.payload_pair() {
1815 Some((_, p)) => Some(p),
1816 None => None,
1817 }
1818 }
1819
1820 /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1821 /// consumer that fans on the L7-HTTP-shaped payload keys off —
1822 /// returns the [`Self::Http`]-arm's author-declared request path
1823 /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1824 /// projected target is [`Self::Http { endpoint }`], `None` on the
1825 /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
1826 /// [`Self::Capability`], each of which carries no HTTP endpoint by
1827 /// definition).
1828 ///
1829 /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
1830 /// `path:` rule payload every substrate-side L7-introspecting
1831 /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
1832 /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
1833 /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
1834 /// on the L7 introspection branch; every peer WIT shape stays
1835 /// L4-only because Cilium can't introspect NATS / key-value / plain
1836 /// capability edges), and every future L7-introspecting consumer
1837 /// of the projected target's HTTP endpoint (the future M4
1838 /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
1839 /// materializer's per-edge L7 admission-webhook overlay, the
1840 /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
1841 /// path bucket-key resolver, the future per-`:contratos`-edge
1842 /// mTLS-required overlay's HTTP-shape scope filter, the future
1843 /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
1844 /// through the same typed dispatch.
1845 ///
1846 /// Prior to this lift the sole production consumer of the projected-
1847 /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
1848 /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
1849 /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
1850 /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
1851 /// }`) — reached the payload through a raw per-arm `if let` pattern-
1852 /// match that expressed no compile-time link back to the substrate
1853 /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
1854 /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
1855 /// scalar accessor on the peer per-`:contratos` raw-field axis but
1856 /// with no post-projection peer on the typed-view surface. A future
1857 /// [`WitTarget`] variant addition that splits [`Self::Http`] into
1858 /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
1859 /// gRPC-shaped worlds per this enum's own docstring at
1860 /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
1861 /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
1862 /// would have had to be threaded through the caixa-mesh L7 emit
1863 /// branch's raw `if let` in lockstep — either coalescing the two
1864 /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
1865 /// emit path per-arm — with no substrate-primitive dispatch making
1866 /// the "which arms count as L7-HTTP-shaped for path-emission
1867 /// purposes" question the substrate's answer to give. Lifting the
1868 /// resolution to a typed method on the substrate primitive means
1869 /// every downstream L7-HTTP-facing consumer of the Aplicacao's
1870 /// projected-target HTTP endpoint reaches for exactly one typed
1871 /// dispatch — the resolver's accept-set migrates as a unit on any
1872 /// future arm-family widening, and the caixa-mesh L7 emit branch
1873 /// reads through the same substrate primitive.
1874 ///
1875 /// Peer of the sibling pre-projection [`WitContract::endpoint`]
1876 /// (7020470) `Option<&str>` scalar accessor on the raw
1877 /// `:contratos :endpoint` field-access axis — same "one typed
1878 /// dispatch on the substrate primitive, thin projections at each
1879 /// consumer" discipline extended onto the peer post-projection typed-
1880 /// view surface (the [`WitContract::endpoint`] pre-projection
1881 /// accessor returns `Some` for any author-declared `:endpoint`
1882 /// value regardless of the paired `:wit` world's HTTP-shape
1883 /// classification — the raw slot before validation crosses it —
1884 /// while this post-projection [`Self::http_endpoint`] accessor
1885 /// returns `Some` iff the target has been projected onto the
1886 /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
1887 /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
1888 /// coherence; the two accessors close the pre-projection /
1889 /// post-projection pair on the HTTP-endpoint axis). Sibling of the
1890 /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
1891 /// the three payload-carrying arms) — extends the per-arm
1892 /// projection family onto the [`Self::Http`] specialization axis
1893 /// that the pan-arm accessor's shape blends into a single arm-
1894 /// agnostic view; paired with [`Self::pubsub_subject`] /
1895 /// [`Self::store_slot`] on the sibling per-arm axes so every
1896 /// per-payload-arm shape carries a named post-projection accessor
1897 /// on the same shape as `http_endpoint`, closing the per-arm-shape
1898 /// accept-set the substrate primitive owns.
1899 #[must_use]
1900 pub const fn http_endpoint(&self) -> Option<&'a str> {
1901 match *self {
1902 WitTarget::Http { endpoint } => Some(endpoint),
1903 WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1904 }
1905 }
1906
1907 /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
1908 /// consumer that fans on the pub-sub-shaped payload keys off —
1909 /// returns the [`Self::PubSub`]-arm's author-declared event-stream
1910 /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
1911 /// the projected target is [`Self::PubSub { subject }`], `None` on
1912 /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
1913 /// [`Self::Capability`], each of which carries no NATS-shaped
1914 /// subject by definition).
1915 ///
1916 /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
1917 /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
1918 /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
1919 /// CR materializer's `spec.subjects[]` projection, the future
1920 /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
1921 /// bucket-key resolver, the future `feira app graph --pubsub`
1922 /// per-Aplicacao subject column, any future substrate-lifted
1923 /// pub-sub-shape emitter that reads a projected `WitTarget` in the
1924 /// same shape [`caixa_mesh::cilium_network_policies`] reads the
1925 /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
1926 /// future pub-sub-shape consumer reaches for the same typed
1927 /// dispatch this accessor exposes so the "which arm carries the
1928 /// subject scalar?" answer lives at one caixa-core edit rather
1929 /// than open-coded across per-consumer `if let WitTarget::PubSub
1930 /// { subject } = c.target()…` pattern-matches.
1931 ///
1932 /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
1933 /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
1934 /// the pre-projection [`WitContract::subject`] scalar accessor on
1935 /// the raw `:contratos :subject` field-access axis — same "one
1936 /// typed dispatch on the substrate primitive, thin projections at
1937 /// each consumer" discipline extended onto the per-arm pub-sub
1938 /// post-projection axis. The pre-projection accessor returns
1939 /// `Some` for any author-declared `:subject` value regardless of
1940 /// the paired `:wit` world's pub-sub-shape classification (the raw
1941 /// slot before validation crosses it); this post-projection
1942 /// accessor returns `Some` iff the target has been projected onto
1943 /// the [`Self::PubSub`] arm, i.e. only after the
1944 /// [`WitContract::target`] gate has admitted the
1945 /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
1946 /// the pre-/post-projection pair on the pub-sub-subject axis to
1947 /// match the pair the [`WitContract::endpoint`] +
1948 /// [`Self::http_endpoint`] surfaces already close on the peer
1949 /// HTTP-endpoint axis.
1950 ///
1951 /// Sibling of the unified pan-arm [`Self::payload`]
1952 /// (`Option<&'a str>` for any of the three payload-carrying arms) —
1953 /// extends the per-arm projection family onto the [`Self::PubSub`]
1954 /// specialization axis that the pan-arm accessor's shape blends
1955 /// into a single arm-agnostic view; the pair
1956 /// (`pubsub_subject`, `store_slot`) closes the trio
1957 /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
1958 /// payload arm now carries its own per-arm-shape post-projection
1959 /// accessor.
1960 #[must_use]
1961 pub const fn pubsub_subject(&self) -> Option<&'a str> {
1962 match *self {
1963 WitTarget::PubSub { subject } => Some(subject),
1964 WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1965 }
1966 }
1967
1968 /// Substrate-canonical per-arm key/value-store-slot scalar accessor
1969 /// every consumer that fans on the store-shaped payload keys off —
1970 /// returns the [`Self::Store`]-arm's author-declared slot template
1971 /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
1972 /// projected target is [`Self::Store { slot }`], `None` on the
1973 /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
1974 /// [`Self::Capability`], each of which carries no
1975 /// key/value-store slot by definition).
1976 ///
1977 /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
1978 /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
1979 /// every future substrate-side store-introspecting per-`(:de,
1980 /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
1981 /// namespace / prefix reconciler's per-slot projection, the future
1982 /// per-store-backend routing overlay's slot-shape gate, the future
1983 /// `feira app graph --store` per-Aplicacao slot column, any future
1984 /// substrate-lifted store-shape emitter that reads a projected
1985 /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
1986 /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
1987 /// Every future store-shape consumer reaches for the same typed
1988 /// dispatch this accessor exposes so the "which arm carries the
1989 /// slot scalar?" answer lives at one caixa-core edit rather than
1990 /// open-coded across per-consumer
1991 /// `if let WitTarget::Store { slot } = c.target()…`
1992 /// pattern-matches.
1993 ///
1994 /// Peer of the sibling [`Self::http_endpoint`] +
1995 /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
1996 /// axes and of the pre-projection [`WitContract::slot`] scalar
1997 /// accessor on the raw `:contratos :slot` field-access axis — same
1998 /// "one typed dispatch on the substrate primitive, thin projections
1999 /// at each consumer" discipline extended onto the per-arm store
2000 /// post-projection axis. Closes the pre-/post-projection pair on
2001 /// the store-slot axis to match the pairs the
2002 /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2003 /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2004 /// already close on the peer HTTP-endpoint and pub-sub-subject
2005 /// axes; the substrate-side pre-/post-projection accessor family
2006 /// now spans all three payload arms as a matched trio, so any
2007 /// future arm-shape widening (a `Rest`/`Grpc` split of
2008 /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2009 /// lands one accessor without threading through the sibling
2010 /// pre-projection or the peer per-arm post-projection surfaces a
2011 /// compile-time exhaustiveness error at the substrate primitive,
2012 /// not a silent per-consumer split at renderer emit time.
2013 ///
2014 /// Sibling of the unified pan-arm [`Self::payload`]
2015 /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2016 /// closes the per-arm projection family onto the [`Self::Store`]
2017 /// specialization axis that the pan-arm accessor's shape blends
2018 /// into a single arm-agnostic view. The trio
2019 /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2020 /// pan-arm accept-set on every payload-carrying arm: exactly one
2021 /// per-arm accessor returns `Some(payload)` and the two peers
2022 /// return `None`, and every payload-less [`Self::Capability`]
2023 /// input returns `None` on all three — the partition the sibling
2024 /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2025 /// pin locks in load-bearing.
2026 #[must_use]
2027 pub const fn store_slot(&self) -> Option<&'a str> {
2028 match *self {
2029 WitTarget::Store { slot } => Some(slot),
2030 WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2031 }
2032 }
2033
2034 /// Render this typed target as a stable human-readable label
2035 /// (`:endpoint "/charge"`, `:subject "events.x"`,
2036 /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2037 /// the WIT world is a pure capability edge).
2038 ///
2039 /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2040 /// gate so the diagnostic names *which* identical edge was
2041 /// declared twice (not just which `(de, para, wit)` triple).
2042 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2043 /// on the payload-carrying arms (`Some((field, payload)) →
2044 /// format!(":{field} {payload:?}")`) and through the lifted
2045 /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2046 /// [`Self::Capability`] arm — so a future variant addition (the
2047 /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2048 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2049 /// `Queue`-shaped peer) becomes a single new match-arm on
2050 /// [`Self::payload_pair`] rather than a rewrite of this template
2051 /// (and every downstream consumer that reaches for the label
2052 /// shape: the per-edge policy resolver in M4, the `feira app
2053 /// graph` view, the operator's mesh-graph audit). Until this
2054 /// lift landed the three payload arms carried three near-identical
2055 /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2056 /// [`Self::Capability`] arm carried the payload-less byte-string
2057 /// twice (once inline here, once in the pin test) — closing the
2058 /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2059 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2060 /// / 4a1e490) peer-const lifts already established for the
2061 /// payload-carrying arms.
2062 #[must_use]
2063 pub fn label(&self) -> String {
2064 match self.payload_pair() {
2065 Some((field, payload)) => format!(":{field} {payload:?}"),
2066 None => Self::CAPABILITY_LABEL.to_string(),
2067 }
2068 }
2069
2070 /// Render this typed target as the `feira app graph` per-`:contratos`
2071 /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2072 /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2073 /// payload-less arm).
2074 ///
2075 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2076 /// on the payload-carrying arms (`Some((field, payload)) →
2077 /// format!("{field}={payload}")`) and through the lifted
2078 /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2079 /// [`Self::Capability`] arm — so a future variant addition
2080 /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2081 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2082 /// `Queue`-shaped peer) becomes one match-arm edit at
2083 /// [`Self::payload_pair`], propagating through this graph-verb
2084 /// projection at zero call-site cost, sibling to the peer
2085 /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2086 /// same 4-arm dispatch.
2087 ///
2088 /// Until this lift landed the [`caixa-feira`]
2089 /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2090 /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2091 /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2092 /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2093 /// `format!("{}={endpoint}", ...)` template and hard-coding
2094 /// `"(capability-only)"` as a fifth payload-less scalar with no link
2095 /// back to the paired [`WitTarget::Capability`] variant declaration.
2096 /// A future variant addition would have had to be threaded through
2097 /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2098 /// verb's inline match in lockstep or the two projections would
2099 /// silently disagree on the arm-set the graph verb prints — the
2100 /// duplicate-`:contratos` diagnostic reading one shape while the
2101 /// graph verb's payload column silently dropped the new arm to
2102 /// `(capability-only)`. Lifting the graph-verb projection onto the
2103 /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2104 /// the axis: both projections migrate as a unit.
2105 ///
2106 /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2107 /// quoting) shape is graph-verb-canonical — distinct from the
2108 /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2109 /// duplicate-`:contratos` diagnostic seeds (see
2110 /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2111 /// on the payload-less axis for the paired distinction).
2112 #[must_use]
2113 pub fn graph_label(&self) -> String {
2114 match self.payload_pair() {
2115 Some((field, payload)) => format!("{field}={payload}"),
2116 None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2117 }
2118 }
2119}
2120
2121/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2122/// pretty-printed byte-string every consumer that formats a typed
2123/// payload target as user-facing text lands on (the
2124/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2125/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2126/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2127/// graph` per-`:contratos`-edge payload column that reaches the graph
2128/// verb through `format!("{target}")`, the future M4 per-edge policy
2129/// resolver's per-edge audit-log line, the operator's mesh-graph
2130/// per-edge inspection view) reaches for the same lifted
2131/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2132/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2133/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2134/// routes through — extending the three-path-convergence
2135/// (`Debug` for structural inspection, `Display` for user-facing text,
2136/// per-arm typed accessor for the canonical byte-string) discipline the
2137/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2138/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2139/// onto the fourth (and only remaining) typed-shape-discriminator axis
2140/// on the caixa surface.
2141///
2142/// Pre-lift the two paths were structurally independent — every consumer
2143/// reaching for a payload byte-string past the [`WitTarget::label`]
2144/// helper had to pick between three paths ([`WitTarget::label`],
2145/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2146/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2147/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2148/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2149/// that reached for `format!("{target}")` — the canonical shape every
2150/// user-facing pretty-print site on the sibling typed-enum axes already
2151/// uses — would silently land on the `Debug` derive's structural output
2152/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2153/// than the `label()` helper's stable byte-string (`:endpoint
2154/// "/charge"` — the author-facing `:contratos` keyword form) the
2155/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2156/// already threads through. The two spellings would diverge silently in
2157/// every downstream diagnostic / graph / audit line reached through
2158/// `format!` rather than through the `label()` helper. Routing
2159/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2160/// path: every `format!("{v}")` call reaches the same
2161/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2162/// and the duplicate-`:contratos` gate already route through, so a
2163/// future variant addition (the M4-and-later per-edge WIT registry may
2164/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2165/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2166/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2167/// match — rather than fanning out through hand-rolled per-arm
2168/// [`std::fmt::Display`] arms.
2169///
2170/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2171/// is the typed view returned by [`WitContract::target`], not a
2172/// closed-set discriminator enum with a gen-platform Discriminant
2173/// registration, so the `Debug` derive's structural output (which every
2174/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2175/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2176/// shape for structural inspection; `Display` (via `label`) reveals the
2177/// stable author-facing payload projection.
2178///
2179/// Pin tests
2180/// [`tests::wit_target_display_routes_through_label_helper`] and
2181/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2182/// assert the two paths agree byte-for-byte on every variant, so a
2183/// future variant addition or `label()` reimplementation that hand-rolls
2184/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2185/// build error visible at caixa-core test time, not a silent
2186/// per-consumer dispatch miss at diagnostic / audit / graph time.
2187impl std::fmt::Display for WitTarget<'_> {
2188 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2189 f.write_str(&self.label())
2190 }
2191}
2192
2193// ── one Aplicacao member ─────────────────────────────────────────────
2194
2195/// A Servico participating in the Aplicacao. Same shape as
2196/// `crate::supervisor::ChildSpec` but without a restart policy —
2197/// supervision is per-Servico (each member has its own
2198/// `:supervisor`), the Aplicacao orchestrates *placement*.
2199#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2200#[serde(rename_all = "camelCase")]
2201pub struct Membro {
2202 /// Member caixa's `:nome`. Resolves through the same dep
2203 /// resolution path as `crate::dep::Dep`.
2204 pub caixa: String,
2205
2206 /// Semver constraint.
2207 pub versao: String,
2208}
2209
2210impl Membro {
2211 /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2212 /// accessor every consumer that reads the member's Servico identity
2213 /// keys off — returns the author-declared `:membros :caixa`
2214 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2215 /// own [`String`] storage.
2216 ///
2217 /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2218 /// participating in the Aplicacao — validated by
2219 /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2220 /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2221 /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2222 /// [`validate_no_self_membership`]) — and every downstream consumer
2223 /// that fans on the member's identity keys off this scalar (the
2224 /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2225 /// lookup, the per-`:membros` duplicate gate's dedup key, the
2226 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2227 /// identity, the self-membership gate, the
2228 /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2229 /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2230 /// CR materializer's per-member resolver).
2231 ///
2232 /// Prior to this lift the `.caixa` byte-string was read inline at
2233 /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2234 /// set collector at
2235 /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2236 /// [`validate_membros`] validation-side member-caixa gate at
2237 /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2238 /// per-member duplicate-gate dedup key at
2239 /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2240 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2241 /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2242 /// [`validate_no_self_membership`] self-loop gate at
2243 /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2244 /// expressed no compile-time link back to the typed slot. Every
2245 /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2246 /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2247 /// `name:` axis, so a future extension of the `:membros :caixa`
2248 /// axis to a richer author surface — a per-cluster alias table the
2249 /// operator pins through a future `:placement`-scoped slot, a
2250 /// namespace-qualified rewrite the M4 CR materializer applies
2251 /// per-CR, a per-member overlay from the future `:membros
2252 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2253 /// acknowledges — would have had to be threaded through every
2254 /// open-coded copy in lockstep or one consumer would silently
2255 /// disagree with the peers on which caixa a given member resolves
2256 /// to. A member-set lookup that treated the name as `"cart"` while
2257 /// the peer adjacency map treated it as `"tenant-a/cart"` would
2258 /// silently split the `:contratos` membership-lookup diagnostic from
2259 /// the cycle-detector's node identity — a two-consumer split at the
2260 /// validator far from the source `caixa.lisp` with no field naming
2261 /// the identity-drift root cause. Lifting the resolution rule to a
2262 /// typed method on the substrate primitive means every downstream
2263 /// consumer of the Aplicacao's per-`:membros` identity surface
2264 /// reaches for exactly one typed dispatch — the resolver's
2265 /// accept-set migrates as a unit on any future axis addition.
2266 ///
2267 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2268 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2269 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2270 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2271 /// destination-Servico scalar accessors — same "one typed dispatch
2272 /// on the substrate primitive, thin projections at each consumer"
2273 /// discipline extended onto the per-`:membros` member-caixa `:nome`
2274 /// byte-string axis. Named `nome()` to match the tatara-lisp
2275 /// author-surface term the field's docstring already reaches for
2276 /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2277 /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2278 /// already carries — the accessor's name maps directly onto the
2279 /// canonical caixa-identity vocabulary rather than shadowing the
2280 /// field's storage-side `caixa` label.
2281 #[must_use]
2282 pub fn nome(&self) -> &str {
2283 self.caixa.as_str()
2284 }
2285
2286 /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2287 /// requirement scalar accessor every consumer that reads the
2288 /// member's version pin keys off — returns the author-declared
2289 /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2290 /// from the typed slot's own [`String`] storage.
2291 ///
2292 /// The `:membros :versao` slot carries the Cargo-shaped semver
2293 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2294 /// pins which release of the member-caixa the Aplicacao composes
2295 /// against — the same requirement grammar the peer `:deps :versao`
2296 /// / `:children :versao` axes carry, resolved through the shared
2297 /// [`crate::render::require_valid_versao_requirement`] cascade and
2298 /// the shared [`crate::version::parse_requirement`] parser. Every
2299 /// downstream consumer that fans on the member's version pin keys
2300 /// off this scalar (the [`validate_membros`] per-member requirement
2301 /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2302 /// …)`, the [`feira app graph`] per-member `println!(" - {} {}",
2303 /// m.nome(), m.versao_requirement())` line, every future per-cluster
2304 /// version-lock overlay the operator pins through a future
2305 /// `:placement`-scoped slot, the future
2306 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2307 /// version resolver, the future `feira app deploy` pipeline's
2308 /// per-member lacre BLAKE3-closure lookup).
2309 ///
2310 /// Prior to this lift the `.versao` byte-string was accessed inline
2311 /// at two `&str`-shaped sites — the [`validate_membros`]
2312 /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2313 /// …)` and the `feira app graph` per-member printer's `println!(
2314 /// " - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2315 /// prior to this lift) — two open-coded field-accesses that expressed
2316 /// no compile-time link back to the typed slot. A future extension of
2317 /// the `:membros :versao` axis to a richer author surface (a
2318 /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2319 /// flow, a lacre-projected concrete-version rewrite the operator
2320 /// materializes at CR-admission time, a future `:membros :versao-lock`
2321 /// per-cluster override slot) would have had to be threaded through
2322 /// every open-coded copy in lockstep or one consumer would silently
2323 /// disagree with the peers on which release constraint a given
2324 /// member resolves to. Lifting the resolution rule to a typed method
2325 /// on the substrate primitive means every downstream requirement-
2326 /// facing consumer reaches for exactly one typed dispatch — the
2327 /// resolver's accept-set migrates as a unit on any future axis
2328 /// addition.
2329 ///
2330 /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2331 /// member-caixa `:nome` scalar accessor — the pair
2332 /// `(nome(), versao_requirement())` jointly projects the
2333 /// `(caixa, versao)` field pair every renderer that fans on
2334 /// per-member identity + version pin keys off, closing the last
2335 /// unlifted per-`:membros` scalar axis so every downstream
2336 /// per-`:membros` reader now routes through a typed dispatch on the
2337 /// substrate primitive. Named `versao_requirement()` rather than
2338 /// `versao()` because the field's storage-side `.versao` label is
2339 /// already the author-surface term (`:versao`); the accessor's name
2340 /// carries the semantic role — the semver *requirement* string the
2341 /// shared [`crate::version::parse_requirement`] entry-point consumes
2342 /// — so a raw field access and a typed dispatch read differently at
2343 /// every consumer site.
2344 ///
2345 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2346 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2347 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2348 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2349 /// destination-Servico scalar accessors — same "one typed dispatch
2350 /// on the substrate primitive, thin projections at each consumer"
2351 /// discipline extended onto the per-`:membros` member-`:versao`
2352 /// semver-requirement byte-string axis.
2353 #[must_use]
2354 pub fn versao_requirement(&self) -> &str {
2355 self.versao.as_str()
2356 }
2357}
2358
2359// ── mesh-level policies ──────────────────────────────────────────────
2360
2361/// Mesh policies that apply to every `:contratos` edge unless
2362/// overridden per-edge in M4. V0 is a single global policy block.
2363#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2364#[serde(rename_all = "camelCase")]
2365pub struct MeshPolicy {
2366 /// Per-call timeout. Authored as a duration string (`"30s"`).
2367 #[serde(
2368 default,
2369 skip_serializing_if = "Option::is_none",
2370 with = "supervisor::duration_codec"
2371 )]
2372 pub timeout: Option<Duration>,
2373
2374 /// Number of retries on transient failure. None = no retries.
2375 #[serde(default, skip_serializing_if = "Option::is_none")]
2376 pub retries: Option<u32>,
2377
2378 /// Circuit breaker config. Trips after N failures within W
2379 /// duration; closes after a cooldown.
2380 #[serde(default, skip_serializing_if = "Option::is_none")]
2381 pub circuit_breaker: Option<CircuitBreaker>,
2382
2383 /// Whether mTLS is required for every contrato. Default: true
2384 /// (sandboxing-by-default; explicit opt-out only).
2385 #[serde(default, skip_serializing_if = "Option::is_none")]
2386 pub mtls_required: Option<bool>,
2387
2388 /// Token-bucket rate limit. Authored as `"100/s"` or
2389 /// `"5000/m"`; stored as `(rate, window)`.
2390 #[serde(
2391 default,
2392 skip_serializing_if = "Option::is_none",
2393 with = "rate_limit_codec"
2394 )]
2395 pub rate_limit: Option<RateLimit>,
2396}
2397
2398impl MeshPolicy {
2399 /// True when no `:politicas` axis carries a value — every field is
2400 /// `None`. The same emptiness contract every other M2/M3 typed
2401 /// surface carries ([`crate::LimitsSpec::is_empty`],
2402 /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2403 /// typed slot onto a cluster artifact key off this predicate to
2404 /// decide "emit the slot" vs "skip the slot entirely", so an
2405 /// authored-but-unset `:politicas (())` round-trips to a rendered
2406 /// artifact that's structurally identical to one that omits the
2407 /// slot. Lifted as a typed predicate (rather than per-renderer
2408 /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2409 /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2410 /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2411 /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2412 /// not a coordinated rewrite of every consumer that's reaching
2413 /// for the emptiness semantic.
2414 #[must_use]
2415 pub const fn is_empty(&self) -> bool {
2416 self.timeout().is_none()
2417 && self.retries().is_none()
2418 && self.circuit_breaker().is_none()
2419 && self.mtls_required().is_none()
2420 && self.rate_limit().is_none()
2421 }
2422
2423 /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2424 /// per-call-deadline scalar accessor every consumer of the
2425 /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2426 /// returns the author-declared `:politicas :timeout` typed
2427 /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2428 /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2429 /// is `Copy`, so the accessor returns by value; no borrow of
2430 /// `&self` past the call). `None` when the slot is absent (the
2431 /// "cluster default applies — typically the gateway class's
2432 /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2433 /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2434 /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2435 /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2436 /// round-trips to a rendered `HTTPRoute` structurally identical to
2437 /// one that omits the slot).
2438 ///
2439 /// The `:politicas :timeout` slot carries the "no infinite blocking"
2440 /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2441 /// the typed slot's `Option<Duration>` accept-set (zero-floor
2442 /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2443 /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2444 /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2445 /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2446 /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2447 /// Every downstream consumer that reads the per-call cap keys off
2448 /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2449 /// renderers key off to decide "emit :politicas overlay" vs "skip
2450 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2451 /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2452 /// fans the deadline into every rule via
2453 /// [`crate::render::single_field_overlay`], the future M4 per-
2454 /// Aplicacao Gateway API reconciler materialization pass, the
2455 /// future per-`:contratos`-edge timeout-override overlay the
2456 /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2457 ///
2458 /// Prior to this lift the `.timeout` field was accessed inline at
2459 /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2460 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2461 /// …)` call — two open-coded field-accesses that expressed no
2462 /// compile-time link back to the typed slot. A future extension of
2463 /// the `:politicas :timeout` axis to a richer author surface — a
2464 /// per-`:contratos`-edge timeout override the operator pins through
2465 /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2466 /// roadmap acknowledges, a per-cluster timeout-default overlay the
2467 /// M4 CR materializer resolves per-CR, a split of the single
2468 /// per-call `Duration` into a richer `{request, backendRequest}`
2469 /// pair once the Gateway API's per-rule `timeouts` block grows the
2470 /// upstream-facing backendRequest arm alongside the client-facing
2471 /// request arm — would have had to be threaded through both open-
2472 /// coded copies in lockstep or the emptiness predicate and the
2473 /// caixa-mesh emit path would silently disagree on which per-call
2474 /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2475 /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2476 /// == false` while the renderer's overlay-emit path silently read
2477 /// a drifted other value, or vice versa: an author's `:timeout
2478 /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2479 /// the emptiness predicate still classified the policy as non-
2480 /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2481 /// | grep -A2 timeouts` audit would land on a route whose author's
2482 /// typed slot value silently vanished at the renderer layer).
2483 /// Lifting the resolution to a typed method on the substrate
2484 /// primitive means every downstream consumer of the Aplicacao's
2485 /// per-`:politicas` deadline surface reaches for exactly one typed
2486 /// dispatch — the resolver's accept-set migrates as a unit on any
2487 /// future axis addition.
2488 ///
2489 /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2490 /// family (sibling of the peer per-`:politicas`
2491 /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2492 /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2493 /// `Option<bool>` accessor — same "one typed dispatch on the
2494 /// substrate primitive, thin projections at each consumer"
2495 /// discipline extended onto the peer per-`:politicas` typed-
2496 /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2497 /// numeric-Copy-T scalar" projection pattern the sibling
2498 /// `Option<u32>` / `Option<bool>` lifts opened, since every
2499 /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2500 /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2501 /// than a scalar). Named `timeout()` to match the storage field's
2502 /// name; the accessor's identity maps onto the canonical MESH-
2503 /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2504 #[must_use]
2505 pub const fn timeout(&self) -> Option<Duration> {
2506 self.timeout
2507 }
2508
2509 /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2510 /// retry-budget scalar accessor every consumer of the Aplicacao's
2511 /// Gateway API v1.x per-rule retry-cap keys off — returns the
2512 /// author-declared `:politicas :retries` typed `u32` verbatim as an
2513 /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2514 /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2515 /// value; no borrow of `&self` past the call). `None` when the slot
2516 /// is absent (the "cluster default applies — typically 'no retries
2517 /// beyond a single dispatch attempt'" arm the caixa-mesh
2518 /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2519 /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2520 /// this predicate too, so an authored-but-unset `:politicas
2521 /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2522 /// identical to one that omits the slot).
2523 ///
2524 /// The `:politicas :retries` slot carries the "transient failure
2525 /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2526 /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2527 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2528 /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2529 /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2530 /// count scalar the caixa-mesh `retry_overlay` builder writes.
2531 /// Every downstream consumer that reads the retry cap keys off this
2532 /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2533 /// renderers key off to decide "emit :politicas overlay" vs "skip
2534 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2535 /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2536 /// the value into every rule via [`crate::render::single_field_overlay`],
2537 /// the future M4 per-Aplicacao Gateway API reconciler
2538 /// materialization pass, the future per-`:contratos`-edge retry-
2539 /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2540 /// acknowledges).
2541 ///
2542 /// Prior to this lift the `.retries` field was accessed inline at
2543 /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2544 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2545 /// …)` call — two open-coded field-accesses that expressed no
2546 /// compile-time link back to the typed slot. A future extension of
2547 /// the `:politicas :retries` axis to a richer author surface — a
2548 /// per-`:contratos`-edge retry override the operator pins through a
2549 /// future `:contratos :retries` slot, a per-cluster retry-default
2550 /// overlay the M4 CR materializer resolves per-CR, a promotion of
2551 /// the plain `u32` attempt-count to a richer `{attempts, codes,
2552 /// backoff}` sub-block once the Gateway API grows the peer
2553 /// `retry.codes` / `retry.backoff` axes — would have had to be
2554 /// threaded through both open-coded copies in lockstep or the
2555 /// emptiness predicate and the caixa-mesh emit path would silently
2556 /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2557 /// (a `:politicas` block whose only axis is a `Some :retries` would
2558 /// satisfy `is_empty() == false` while the renderer's overlay-emit
2559 /// path silently read a drifted other value, or vice versa: an
2560 /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2561 /// block while the emptiness predicate still classified the policy
2562 /// as non-empty). Lifting the resolution to a typed method on the
2563 /// substrate primitive means every downstream consumer of the
2564 /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2565 /// one typed dispatch — the resolver's accept-set migrates as a
2566 /// unit on any future axis addition.
2567 ///
2568 /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2569 /// family (sibling of the peer per-`:politicas`
2570 /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2571 /// same "one typed dispatch on the substrate primitive, thin
2572 /// projections at each consumer" discipline extended onto the
2573 /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2574 /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2575 /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2576 /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2577 /// fold on). Named `retries()` to match the storage field's name;
2578 /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2579 /// §III.2 vocabulary the slot's docstring already carries.
2580 #[must_use]
2581 pub const fn retries(&self) -> Option<u32> {
2582 self.retries
2583 }
2584
2585 /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2586 /// enforcement-toggle scalar accessor every consumer of the
2587 /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2588 /// — returns the author-declared `:politicas :mtls-required` typed
2589 /// bool verbatim as an `Option<bool>`, copied out of the typed
2590 /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2591 /// the accessor returns by value; no borrow of `&self` past the
2592 /// call). `None` when the slot is absent (the "cluster default
2593 /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2594 /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2595 /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2596 /// this predicate too, so an authored-but-unset `:politicas
2597 /// (:mtls-required ())` round-trips to a rendered
2598 /// `CiliumNetworkPolicy` structurally identical to one that omits
2599 /// the slot).
2600 ///
2601 /// The `:politicas :mtls-required` slot carries the "explicit opt-
2602 /// out only, sandboxing-by-default" mTLS-enforcement toggle
2603 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2604 /// `{None, Some(true), Some(false)}` accept-set maps onto the
2605 /// Cilium `authentication.mode` bijection through
2606 /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2607 /// handshake enforced), `Some(false) → "disabled"` (handshake
2608 /// skipped — the debug-edge opt-out), `None` → omit the block
2609 /// (cluster default applies). Every downstream consumer that
2610 /// reads the toggle keys off this scalar (the
2611 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2612 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2613 /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2614 /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2615 /// ingress rule via [`crate::render::single_field_overlay`], the
2616 /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2617 /// materialization pass, the future per-`:contratos`-edge mTLS
2618 /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2619 ///
2620 /// Prior to this lift the `.mtls_required` field was accessed
2621 /// inline at two sites — [`MeshPolicy::is_empty`]'s
2622 /// `self.mtls_required.is_none()` arm and caixa-mesh's
2623 /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2624 /// two open-coded field-accesses that expressed no compile-time
2625 /// link back to the typed slot. A future extension of the
2626 /// `:politicas :mtls-required` axis to a richer author surface —
2627 /// a per-`:contratos`-edge mTLS override the operator pins through
2628 /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2629 /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2630 /// M4 CR materializer resolves per-CR, a three-valued
2631 /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2632 /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2633 /// would have had to be threaded through both open-coded copies in
2634 /// lockstep or the emptiness predicate and the caixa-mesh emit
2635 /// path would silently disagree on which toggle a given
2636 /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2637 /// axis is a `Some`
2638 /// `:mtls-required` would satisfy `is_empty() == false` while the
2639 /// renderer's overlay-emit path silently read a drifted other
2640 /// value, or vice versa). Lifting the resolution to a typed method
2641 /// on the substrate primitive means every downstream consumer of
2642 /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2643 /// for exactly one typed dispatch — the resolver's accept-set
2644 /// migrates as a unit on any future axis addition.
2645 ///
2646 /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2647 /// family (peer of the sibling per-`:placement`
2648 /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2649 /// same "one typed dispatch on the substrate primitive, thin
2650 /// projections at each consumer" discipline extended onto the
2651 /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2652 /// the "optional per-slot Copy-T scalar" projection pattern the
2653 /// sibling per-`:politicas` `:retries` (Option<u32>) /
2654 /// `:timeout` (Option<Duration>) future lifts fold on). Named
2655 /// `mtls_required()` to match the storage field's name; the
2656 /// accessor's identity maps onto the canonical MESH-COMPOSITION
2657 /// §III.2 vocabulary the slot's docstring already carries.
2658 #[must_use]
2659 pub const fn mtls_required(&self) -> Option<bool> {
2660 self.mtls_required
2661 }
2662
2663 /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2664 /// `local_rate_limit`-mesh token-bucket-declaration scalar
2665 /// accessor every consumer of the Aplicacao's per-`:politicas`
2666 /// per-`(rate, window)` rate-limit surface keys off — returns the
2667 /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2668 /// verbatim as an `Option<RateLimit>`, copied out of the typed
2669 /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2670 /// `Copy`, so the accessor returns by value; no borrow of `&self`
2671 /// past the call). `None` when the slot is absent (the "cluster
2672 /// default applies — typically 'no per-Aplicacao rate declaration,
2673 /// gateway-class per-listener default applies'" arm the future
2674 /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2675 /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2676 /// `rate_limit().is_none()` arm reads this predicate too, so an
2677 /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2678 /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2679 /// identical to one that omits the slot).
2680 ///
2681 /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2682 /// token-bucket rate declaration" contract (MESH-COMPOSITION
2683 /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2684 /// (rate lower-bounded by 1 through
2685 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2686 /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2687 /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2688 /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2689 /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2690 /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2691 /// `:politicas` overlay emits. Every downstream consumer that
2692 /// reads the rate declaration keys off this scalar (the
2693 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2694 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2695 /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2696 /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2697 /// `rl.window` against [`is_canonical_rate_limit_window`], the
2698 /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2699 /// the future per-`:contratos`-edge rate-limit override the
2700 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2701 ///
2702 /// Prior to this lift the `.rate_limit` field was accessed inline
2703 /// at two sites — [`MeshPolicy::is_empty`]'s
2704 /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2705 /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2706 /// field-accesses that expressed no compile-time link back to the
2707 /// typed slot. A future extension of the `:politicas :rate-limit`
2708 /// axis to a richer author surface — a per-`:contratos`-edge
2709 /// rate-limit override the operator pins through a future
2710 /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2711 /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2712 /// the M4 CR materializer resolves per-CR, a promotion of the
2713 /// plain `(rate, window)` scalar pair to a richer
2714 /// `{rate, window, burst, key}` sub-block once Envoy's
2715 /// `local_rate_limit` grows the peer `burst_size` /
2716 /// `descriptor_key` axes — would have had to be threaded through
2717 /// both open-coded copies in lockstep or the emptiness predicate
2718 /// and the validate gate would silently disagree on which rate
2719 /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2720 /// block whose only axis is a `Some :rate-limit` would satisfy
2721 /// `is_empty() == false` while the validate path silently read a
2722 /// drifted other value, or vice versa: an author's
2723 /// `:rate-limit "100/s"` would omit the value-shape gate while the
2724 /// emptiness predicate still classified the policy as non-empty).
2725 /// Lifting the resolution to a typed method on the substrate
2726 /// primitive means every downstream consumer of the Aplicacao's
2727 /// per-`:politicas` rate-limit surface reaches for exactly one
2728 /// typed dispatch — the resolver's accept-set migrates as a unit
2729 /// on any future axis addition.
2730 ///
2731 /// First `Option<Copy-composite-T>`-return accessor on the M3
2732 /// mesh-slot family — closes the last un-lifted per-`:politicas`
2733 /// scalar-value axis. Peer of the sibling per-`:politicas`
2734 /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2735 /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2736 /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2737 /// "one typed dispatch on the substrate primitive, thin
2738 /// projections at each consumer" discipline extended onto the
2739 /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2740 /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2741 /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2742 /// sub-accessors rather than a top-level accessor because
2743 /// consumers reach for the axes not the aggregate). Named
2744 /// `rate_limit()` to match the storage field's name; the
2745 /// accessor's identity maps onto the canonical MESH-COMPOSITION
2746 /// §III.2 vocabulary the slot's docstring already carries.
2747 #[must_use]
2748 pub const fn rate_limit(&self) -> Option<RateLimit> {
2749 self.rate_limit
2750 }
2751
2752 /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2753 /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2754 /// declaration scalar accessor every consumer of the Aplicacao's
2755 /// per-`:politicas` breaker declaration keys off — returns the
2756 /// author-declared `:politicas :circuit-breaker` typed
2757 /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2758 /// copied out of the typed slot's own `Option<CircuitBreaker>`
2759 /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2760 /// by value; no borrow of `&self` past the call). `None` when the
2761 /// slot is absent (the "cluster default applies — typically 'no
2762 /// per-Aplicacao breaker declaration, gateway-class per-listener
2763 /// default applies'" arm the future caixa-mesh
2764 /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2765 /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2766 /// arm reads this predicate too, so an authored-but-unset
2767 /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2768 /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2769 /// that omits the slot).
2770 ///
2771 /// The `:politicas :circuit-breaker` slot carries the
2772 /// "per-Aplicacao consecutive-transient-failure trip declaration"
2773 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2774 /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2775 /// zero-floor rejected through
2776 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2777 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2778 /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2779 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2780 /// canonical-form pinned through
2781 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2782 /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2783 /// bijection the future `CiliumClusterwideEnvoyConfig`
2784 /// per-`:politicas` overlay emits. Every downstream consumer that
2785 /// reads the breaker declaration keys off this scalar (the
2786 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2787 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2788 /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2789 /// that brackets `cb.max_failures()` against
2790 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2791 /// [`POLICY_BREAKER_WINDOW_MAX`] via
2792 /// [`crate::render::require_positive_canonical_bounded_duration`],
2793 /// the future M4 per-Aplicacao Envoy reconciler materialization
2794 /// pass, the future per-`:contratos`-edge breaker override the
2795 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2796 ///
2797 /// Prior to this lift the `.circuit_breaker` field was accessed
2798 /// inline at two sites — [`MeshPolicy::is_empty`]'s
2799 /// `self.circuit_breaker.is_none()` arm and the
2800 /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2801 /// bind — two open-coded field-accesses that expressed no
2802 /// compile-time link back to the typed slot. A future extension of
2803 /// the `:politicas :circuit-breaker` axis to a richer author
2804 /// surface — a per-`:contratos`-edge breaker override the operator
2805 /// pins through a future `:contratos :circuit-breaker` slot the
2806 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2807 /// breaker-default overlay the M4 CR materializer resolves per-CR,
2808 /// a promotion of the plain `(max_failures, window)` scalar pair to
2809 /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2810 /// sub-block once Envoy's `outlier_detection` grows the peer
2811 /// ejection-percentage / ejection-time axes — would have had to be
2812 /// threaded through both open-coded copies in lockstep or the
2813 /// emptiness predicate and the validate gate would silently
2814 /// disagree on which breaker declaration a given [`MeshPolicy`]
2815 /// resolves to (a `:politicas` block whose only axis is a
2816 /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2817 /// the validate path silently read a drifted other value, or vice
2818 /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2819 /// "60s"))` would omit the value-shape gate while the emptiness
2820 /// predicate still classified the policy as non-empty). Lifting
2821 /// the resolution to a typed method on the substrate primitive
2822 /// means every downstream consumer of the Aplicacao's
2823 /// per-`:politicas` breaker surface reaches for exactly one typed
2824 /// dispatch — the resolver's accept-set migrates as a unit on any
2825 /// future axis addition.
2826 ///
2827 /// Second `Option<Copy-composite-T>`-return accessor on the M3
2828 /// mesh-slot family (sibling of the peer per-`:politicas`
2829 /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2830 /// on the same composite-Copy shape, and of the sibling per-
2831 /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2832 /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2833 /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2834 /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2835 /// same "one typed dispatch on the substrate primitive, thin
2836 /// projections at each consumer" discipline extended onto the last
2837 /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2838 /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2839 /// match the storage field's name; the accessor's identity maps
2840 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2841 /// docstring already carries. Closes the last unlifted
2842 /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2843 /// reader now routes through a typed dispatch on the substrate
2844 /// primitive.
2845 #[must_use]
2846 pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2847 self.circuit_breaker
2848 }
2849}
2850
2851#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2852#[serde(rename_all = "camelCase")]
2853pub struct CircuitBreaker {
2854 pub max_failures: u32,
2855 #[serde(with = "supervisor::duration_codec_required")]
2856 pub window: Duration,
2857}
2858
2859impl CircuitBreaker {
2860 /// Substrate-canonical per-`:politicas :circuit-breaker`
2861 /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2862 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2863 /// breaker trip-count keys off — returns the author-declared
2864 /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2865 /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2866 /// so the accessor returns by value; no borrow of `&self` past the
2867 /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2868 /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2869 /// axis; a `CircuitBreaker` past pattern-match is definitionally
2870 /// present, and its `:max-failures` field carries the trip count as a
2871 /// required-axis scalar).
2872 ///
2873 /// The `:politicas :circuit-breaker :max-failures` axis carries the
2874 /// "consecutive-transient-failure trip threshold" contract
2875 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2876 /// (zero-floor rejected through
2877 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2878 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2879 /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2880 /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2881 /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2882 /// Every downstream consumer that reads the trip threshold keys off
2883 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2884 /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2885 /// canonical `require_positive_bounded_u32` helper, the future M4
2886 /// per-Aplicacao Envoy config reconciler materialization pass, the
2887 /// future per-`:contratos`-edge breaker-override overlay the
2888 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2889 ///
2890 /// Prior to this lift the `.max_failures` field was accessed inline
2891 /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2892 /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2893 /// open-coded field-access that expressed no compile-time link back
2894 /// to the typed sub-struct axis. A future extension of the
2895 /// `:max-failures` axis to a richer author surface — a
2896 /// per-`:contratos`-edge breaker override the operator pins through a
2897 /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2898 /// #3 roadmap acknowledges, a per-cluster max-failures-default
2899 /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2900 /// plain `u32` trip count to a richer
2901 /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2902 /// tuple once Envoy's `outlier_detection` block's peer axes come into
2903 /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2904 /// count arms — would have had to be threaded through every open-
2905 /// coded copy in lockstep or the validate gate and the future M4
2906 /// emit path would silently disagree on which trip threshold a given
2907 /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2908 /// would satisfy validate while the emit path silently read a drifted
2909 /// other value, or vice versa: a validated typed slot would land at
2910 /// the emit boundary as a no-op breaker whose trip threshold is
2911 /// structurally never reached). Lifting the resolution to a typed
2912 /// method on the substrate primitive means every downstream consumer
2913 /// of the Aplicacao's per-`:politicas :circuit-breaker`
2914 /// trip-threshold surface reaches for exactly one typed dispatch —
2915 /// the resolver's accept-set migrates as a unit on any future axis
2916 /// addition.
2917 ///
2918 /// First sub-struct scalar accessor on the M3 mesh-slot family
2919 /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2920 /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2921 /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2922 /// closes the last unlifted per-`:politicas` scalar-value axis after
2923 /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2924 /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2925 /// Same "one typed dispatch on the substrate primitive, thin
2926 /// projections at each consumer" discipline the peer
2927 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2928 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2929 /// [`Membro::versao_requirement`] (a40b0e3),
2930 /// [`Entrada::destination`] (6db982c) accessors carry on their
2931 /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2932 /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2933 /// match the storage field's name; the accessor's identity maps onto
2934 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2935 /// docstring already carries.
2936 #[must_use]
2937 pub const fn max_failures(&self) -> u32 {
2938 self.max_failures
2939 }
2940
2941 /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2942 /// Envoy-outlier-detection rolling-observation-interval scalar
2943 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2944 /// breaker rolling-window duration keys off — returns the
2945 /// author-declared `:politicas :circuit-breaker :window` typed
2946 /// `Duration` verbatim, copied out of the typed slot's own
2947 /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2948 /// by value; no borrow of `&self` past the call). Non-optional (the
2949 /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2950 /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2951 /// `CircuitBreaker` past pattern-match is definitionally present,
2952 /// and its `:window` field carries the rolling-observation interval
2953 /// as a required-axis scalar).
2954 ///
2955 /// The `:politicas :circuit-breaker :window` axis carries the
2956 /// "consecutive-transient-failure rolling-observation interval"
2957 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2958 /// `Duration` accept-set (zero-floor rejected through
2959 /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2960 /// residue rejected through
2961 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2962 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2963 /// Envoy `outlier_detection.interval` per-cluster
2964 /// ejection-observation-interval scalar (equivalently the future
2965 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2966 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2967 /// consumer that reads the rolling-observation interval keys off
2968 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2969 /// integer-millisecond canonical-form + cap bracket at
2970 /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2971 /// [`crate::render::require_positive_canonical_bounded_duration`]
2972 /// helper, the future M4 per-Aplicacao Envoy config reconciler
2973 /// materialization pass, the future per-`:contratos`-edge
2974 /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2975 /// acknowledges).
2976 ///
2977 /// Prior to this lift the `.window` field was accessed inline at
2978 /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2979 /// `require_positive_canonical_bounded_duration(cb.window, …)`
2980 /// call — one open-coded field-access that expressed no compile-
2981 /// time link back to the typed sub-struct axis. A future extension
2982 /// of the `:window` axis to a richer author surface — a
2983 /// per-`:contratos`-edge window override the operator pins through
2984 /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2985 /// #3 roadmap acknowledges, a per-cluster window-default overlay
2986 /// the M4 CR materializer resolves per-CR, a promotion of the plain
2987 /// `Duration` observation interval to a richer
2988 /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2989 /// once Envoy's `outlier_detection` block's peer axes come into
2990 /// scope, a per-Envoy-cluster minimum-request-volume gate before
2991 /// the window arms — would have had to be threaded through every
2992 /// open-coded copy in lockstep or the validate gate and the future
2993 /// M4 emit path would silently disagree on which observation
2994 /// interval a given [`CircuitBreaker`] resolves to (an author's
2995 /// `:window "60s"` would satisfy validate while the emit path
2996 /// silently read a drifted other value, or vice versa: a validated
2997 /// typed slot would land at the emit boundary as a breaker whose
2998 /// observation window is structurally so wide that no realistic
2999 /// failure-rate shape can trip it). Lifting the resolution to a
3000 /// typed method on the substrate primitive means every downstream
3001 /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3002 /// observation-window surface reaches for exactly one typed
3003 /// dispatch — the resolver's accept-set migrates as a unit on any
3004 /// future axis addition.
3005 ///
3006 /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3007 /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3008 /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3009 /// required-axis, extended onto the per-sub-struct required-`Duration`
3010 /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3011 /// axis. Same "one typed dispatch on the substrate primitive, thin
3012 /// projections at each consumer" discipline the peer
3013 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3014 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3015 /// [`Membro::versao_requirement`] (a40b0e3),
3016 /// [`Entrada::destination`] (6db982c) accessors carry on their
3017 /// respective per-mesh-slot-atom scalar-value axes, extended onto
3018 /// the per-sub-struct required-`Duration` axis. Named `window()` to
3019 /// match the storage field's name; the accessor's identity maps onto
3020 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3021 /// docstring already carries.
3022 #[must_use]
3023 pub const fn window(&self) -> Duration {
3024 self.window
3025 }
3026}
3027
3028#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3029pub struct RateLimit {
3030 /// Requests per window.
3031 pub rate: u32,
3032 /// Window duration.
3033 pub window: Duration,
3034}
3035
3036impl RateLimit {
3037 /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3038 /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3039 /// every consumer of the Aplicacao's per-`:contratos`-edge
3040 /// rate-limit-bucket capacity keys off — returns the author-declared
3041 /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3042 /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3043 /// returns by value; no borrow of `&self` past the call). Non-optional
3044 /// (the surrounding `Option<RateLimit>` is the "slot present?"
3045 /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3046 /// `RateLimit` past pattern-match is definitionally present, and its
3047 /// `:rate` field carries the token-bucket capacity as a required-axis
3048 /// scalar).
3049 ///
3050 /// The `:politicas :rate-limit` `:rate` axis carries the
3051 /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3052 /// the typed slot's `u32` accept-set (zero-floor rejected through
3053 /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3054 /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3055 /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3056 /// token-bucket-capacity scalar (equivalently the future
3057 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3058 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3059 /// consumer that reads the token-bucket capacity keys off this
3060 /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3061 /// cap bracket that gates on the canonical
3062 /// [`crate::render::require_positive_bounded_u32`] helper, the
3063 /// [`rate_limit_codec::render`] `Duration → unit` projection that
3064 /// emits the `<n>/<s|m|h>` author surface, the future M4
3065 /// per-Aplicacao Envoy config reconciler materialization pass, the
3066 /// future per-`:contratos`-edge rate-limit-override overlay the
3067 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3068 ///
3069 /// Prior to this lift the `.rate` field was accessed inline at three
3070 /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3071 /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3072 /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3073 /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3074 /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3075 /// field-accesses that expressed no compile-time link back to the
3076 /// typed sub-struct axis. A future extension of the `:rate` axis
3077 /// to a richer author surface — a per-`:contratos`-edge rate
3078 /// override the operator pins through a future `:contratos :rate`
3079 /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3080 /// per-cluster rate-default overlay the M4 CR materializer resolves
3081 /// per-CR, a promotion of the plain `u32` token capacity to a
3082 /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3083 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3084 /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3085 /// before the token arms — would have had to be threaded through
3086 /// every open-coded copy in lockstep or the validate gate, the
3087 /// codec's render path, and the future M4 emit path would silently
3088 /// disagree on which token capacity a given [`RateLimit`] resolves
3089 /// to (an author's `:rate-limit "100/s"` would satisfy validate
3090 /// while the render / emit paths silently read a drifted other
3091 /// value, or vice versa: a validated typed slot would land at the
3092 /// emit boundary as a no-op limiter whose token capacity is
3093 /// structurally so high that no realistic per-edge traffic shape
3094 /// can drain it). Lifting the resolution to a typed method on the
3095 /// substrate primitive means every downstream consumer of the
3096 /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3097 /// reaches for exactly one typed dispatch — the resolver's
3098 /// accept-set migrates as a unit on any future axis addition.
3099 ///
3100 /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3101 /// in shape to the peer per-`CircuitBreaker`
3102 /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3103 /// on the peer per-sub-struct required-axis, extended onto the
3104 /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3105 /// required-axis scalar" projection pattern the sibling
3106 /// [`RateLimit::window`] future lift folds on. Same "one typed
3107 /// dispatch on the substrate primitive, thin projections at each
3108 /// consumer" discipline the peer [`WitContract::source`] /
3109 /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3110 /// (0804823), [`Membro::nome`] (4a32abf),
3111 /// [`Membro::versao_requirement`] (a40b0e3),
3112 /// [`Entrada::destination`] (6db982c),
3113 /// [`CircuitBreaker::max_failures`] (3a74062),
3114 /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3115 /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3116 /// to match the storage field's name; the accessor's identity maps
3117 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3118 /// docstring already carries.
3119 #[must_use]
3120 pub const fn rate(&self) -> u32 {
3121 self.rate
3122 }
3123
3124 /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3125 /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3126 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3127 /// rate-limit-bucket refill period keys off — returns the
3128 /// author-declared `:politicas :rate-limit` typed `Duration`
3129 /// verbatim, copied out of the typed slot's own `Duration` storage
3130 /// (`Duration` is `Copy`, so the accessor returns by value; no
3131 /// borrow of `&self` past the call). Non-optional (the surrounding
3132 /// `Option<RateLimit>` is the "slot present?" projection at the
3133 /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3134 /// pattern-match is definitionally present, and its `:window`
3135 /// field carries the token-bucket refill period as a required-axis
3136 /// scalar).
3137 ///
3138 /// The `:politicas :rate-limit` `:window` axis carries the
3139 /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3140 /// — the typed slot's `Duration` accept-set (constrained to the
3141 /// three canonical windows `{1s, 60s, 3600s}` the
3142 /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3143 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3144 /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3145 /// per-cluster token-bucket-refill-period scalar (equivalently the
3146 /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3147 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3148 /// consumer that reads the token-bucket refill period keys off
3149 /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3150 /// canonical-window gate that keys off
3151 /// [`is_canonical_rate_limit_window`], the
3152 /// [`rate_limit_codec::render`] `Duration → unit` projection that
3153 /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3154 /// [`rate_limit_window_unit`] and non-canonical fallback via
3155 /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3156 /// reconciler materialization pass, the future per-`:contratos`-
3157 /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3158 /// roadmap acknowledges).
3159 ///
3160 /// Prior to this lift the `.window` field was accessed inline at
3161 /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3162 /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3163 /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3164 /// error-payload construction on refusal, and the two
3165 /// [`rate_limit_codec::render`] arms
3166 /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3167 /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3168 /// open-coded field-accesses that expressed no compile-time link
3169 /// back to the typed sub-struct axis. A future extension of the
3170 /// `:window` axis to a richer author surface — a per-`:contratos`-
3171 /// edge window override the operator pins through a future
3172 /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3173 /// acknowledges, a per-cluster window-default overlay the M4 CR
3174 /// materializer resolves per-CR, a promotion of the plain
3175 /// `Duration` refill period to a richer
3176 /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3177 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3178 /// axis comes into scope, an addition of a `"d"` day suffix once
3179 /// Envoy's `rate_limit_action` grows daily-bucket support — would
3180 /// have had to be threaded through every open-coded copy in
3181 /// lockstep or the validate gate, the codec's render path, and
3182 /// the future M4 emit path would silently disagree on which
3183 /// refill period a given [`RateLimit`] resolves to (an author's
3184 /// `:rate-limit "100/s"` would satisfy validate while the render
3185 /// / emit paths silently read a drifted other value, or vice
3186 /// versa: a validated typed slot would land at the emit boundary
3187 /// as a limiter whose refill period is structurally so long that
3188 /// no realistic per-edge traffic shape stays inside the token
3189 /// budget). Lifting the resolution to a typed method on the
3190 /// substrate primitive means every downstream consumer of the
3191 /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3192 /// reaches for exactly one typed dispatch — the resolver's
3193 /// accept-set migrates as a unit on any future axis addition.
3194 ///
3195 /// Second sub-struct scalar accessor on the `RateLimit` axis —
3196 /// sibling in shape to the just-landed [`RateLimit::rate`]
3197 /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3198 /// required-axis, extended onto the per-sub-struct
3199 /// required-`Duration` axis; closes the last unlifted
3200 /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3201 /// per-sub-struct accessor coverage is now complete across both
3202 /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3203 /// the substrate primitive, thin projections at each consumer"
3204 /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3205 /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3206 /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3207 /// (7f0fd43), [`WitContract::world_ref`] (0804823),
3208 /// [`Membro::nome`] (4a32abf),
3209 /// [`Membro::versao_requirement`] (a40b0e3),
3210 /// [`Entrada::destination`] (6db982c) accessors carry on their
3211 /// respective per-mesh-slot-atom scalar-value axes. Named
3212 /// `window()` to match the storage field's name; the accessor's
3213 /// identity maps onto the canonical MESH-COMPOSITION §III.2
3214 /// vocabulary the slot's docstring already carries.
3215 #[must_use]
3216 pub const fn window(&self) -> Duration {
3217 self.window
3218 }
3219
3220 /// Recognize this rate-limit's `:window` as a canonical
3221 /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
3222 /// exactly matches one of the three closed-set arm-Durations
3223 /// (`1s` / `60s` / `3600s`), `None` when the window carries a
3224 /// non-canonical magnitude the codec's round-trip would break on
3225 /// (sub-second residue, or a second-magnitude outside the set
3226 /// [`RateLimitUnit::ALL`] enumerates).
3227 ///
3228 /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
3229 /// returns `Some` here — the validate gate's
3230 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
3231 /// rejects every window this accessor returns `None` on. Downstream
3232 /// consumers past validate (the codec's [`rate_limit_codec::render`]
3233 /// path, the future M4 per-Aplicacao Envoy config reconciler's
3234 /// materialization pass, the future per-`:contratos`-edge rate-limit-
3235 /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3236 /// acknowledges) that read the typed unit off a validated slot can
3237 /// pattern-match on the returned `Some` without re-checking
3238 /// canonicality at the consumer layer — the typed enum surface is
3239 /// the load-bearing carrier of the canonicality invariant.
3240 ///
3241 /// Preferred over the free [`is_canonical_rate_limit_window`]
3242 /// module-private helper at any call site that has the typed
3243 /// [`RateLimit`] in hand (the codec's `render` arm at
3244 /// [`rate_limit_codec::render`], the validate gate's canonical-form
3245 /// arm in [`AplicacaoSpec::validate_politicas`], any future
3246 /// per-`:contratos` edge-override overlay resolver): those consumers
3247 /// reach for the typed enum without going through the
3248 /// `.window()` scalar-projection layer, and get the enum value
3249 /// directly (which the codec's render arm can then format via
3250 /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
3251 /// "typed sub-struct scalar accessor, one dispatch on the substrate
3252 /// primitive" discipline the sibling [`RateLimit::rate`] and
3253 /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
3254 /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
3255 /// projection axis (the third scalar accessor on the [`RateLimit`]
3256 /// axis, first typed-enum-return projection).
3257 ///
3258 /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
3259 /// the canonical [`RateLimitUnit`] arm now carries the same
3260 /// `const`-eval-surface posture the sibling `pub const fn`
3261 /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
3262 /// this typed sub-struct already carry, composing through the
3263 /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
3264 /// reverse-resolver in `const` context. Any downstream substrate-
3265 /// side `const`-context consumer of the typed unit (a module-scope
3266 /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
3267 /// invariant pin on a typed fixture, a future M4 admission-webhook
3268 /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
3269 /// resolver over a typed [`RateLimit`], any future `const fn`
3270 /// per-`:contratos`-edge rate-limit-override overlay resolver over
3271 /// the substrate primitive) now reaches the same typed dispatch on
3272 /// the substrate primitive at const-eval time as at runtime.
3273 ///
3274 /// Pinned load-bearing at the substrate-primitive level by
3275 /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
3276 /// eval-surface pin via `const fn` wrapper).
3277 #[must_use]
3278 pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
3279 RateLimitUnit::from_window(self.window)
3280 }
3281}
3282
3283/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3284/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3285/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3286///
3287/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3288/// the `:politicas :rate-limit` unit surface reads from
3289/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3290/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3291/// [`is_canonical_rate_limit_window`] predicate the
3292/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3293/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3294/// projection) now lives inside this typed enum's `match self` arms — a
3295/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3296/// `rate_limit_action` grows daily-bucket support) is one new variant
3297/// plus the exhaustiveness arms on the four methods, so every consumer
3298/// picks it up by compile-time construction rather than a runtime
3299/// table-scan miss.
3300///
3301/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3302/// scanned via `find_map` at every projection call — an untyped runtime
3303/// walk that carried no compile-time link between the parse arm's
3304/// accepted suffixes, the render arm's emitted suffixes, and the
3305/// validate gate's accepted windows. A future rate-limit-unit addition
3306/// that landed one row without threading through the other consumers
3307/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3308/// silently split the accepted-set across the three consumers — the
3309/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3310/// for a 24h window that parse can't round-trip, the validate gate
3311/// misses one canonical window. Lifting the pairs onto a typed
3312/// closed-set enum with exhaustive `match` arms makes any such
3313/// half-landed extension a caixa-core build error (the compiler enforces
3314/// arm coverage on every method), not a silent per-consumer drift
3315/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3316/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3317/// [`crate::supervisor::RestartStrategy`],
3318/// [`crate::supervisor::RestartPolicy`],
3319/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3320/// closed-set typed enums carry on their respective closed-set axes —
3321/// extended onto the seventh closed-set typed-enum discriminator axis
3322/// on the caixa typed surface (the `:politicas :rate-limit :window`
3323/// canonical-unit axis).
3324#[derive(
3325 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3326)]
3327pub enum RateLimitUnit {
3328 /// 1-second window — canonical author-surface suffix `"s"`
3329 /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3330 /// with a 1s magnitude.
3331 Second,
3332 /// 1-minute window — canonical author-surface suffix `"m"`
3333 /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3334 /// with a 60s magnitude.
3335 Minute,
3336 /// 1-hour window — canonical author-surface suffix `"h"`
3337 /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3338 /// with a 3600s magnitude.
3339 Hour,
3340}
3341
3342impl RateLimitUnit {
3343 /// Exhaustive iteration surface for every consumer that reads the
3344 /// full canonical-unit set (the byte-parity witness against the
3345 /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3346 /// webhook's accepted-suffix listing in its rejection body, any
3347 /// future round-trip fuzz harness). A future variant addition to
3348 /// [`RateLimitUnit`] extends this slice as a single edit and every
3349 /// consumer picks up the new entry by construction — the compiler-
3350 /// checked exhaustiveness on the sibling method `match` arms is the
3351 /// build-time guarantee that no arm forgets to grow.
3352 pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3353
3354 /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3355 /// string every `<n>/<unit>` rate-limit shape carries after its
3356 /// `/` separator. The single source of truth the codec's parse and
3357 /// render arms both dispatch on: the parse arm matches an incoming
3358 /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3359 /// output; the render arm emits the entry's `as_suffix` verbatim
3360 /// after the rate magnitude.
3361 #[must_use]
3362 pub const fn as_suffix(self) -> &'static str {
3363 match self {
3364 Self::Second => "s",
3365 Self::Minute => "m",
3366 Self::Hour => "h",
3367 }
3368 }
3369
3370 /// Canonical `Duration` for this unit — the token-bucket refill
3371 /// period the [`RateLimit::window`] axis carries when the surrounding
3372 /// slot's `:rate-limit` author surface named this unit.
3373 #[must_use]
3374 pub const fn window(self) -> Duration {
3375 Duration::from_secs(match self {
3376 Self::Second => 1,
3377 Self::Minute => 60,
3378 Self::Hour => 3_600,
3379 })
3380 }
3381
3382 /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3383 /// `None` when `suffix` is outside the closed-set arm-string set
3384 /// [`Self::as_suffix`] emits. The single `str → Self` projection
3385 /// [`rate_limit_codec::parse`] consumes.
3386 #[must_use]
3387 pub fn from_suffix(suffix: &str) -> Option<Self> {
3388 Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3389 }
3390
3391 /// Recognize a canonical rate-limit `Duration` as one of the three
3392 /// arms, or `None` when `window` carries sub-second residue or a
3393 /// second-magnitude outside the closed-set arm-window set
3394 /// [`Self::window`] emits. The single `Duration → Self` projection
3395 /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3396 /// both consume.
3397 ///
3398 /// `pub const fn` — the reverse `Duration → Self` projection now
3399 /// carries the same `const`-eval-surface posture the sibling
3400 /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3401 /// projection accessors on this closed-set typed enum already
3402 /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3403 /// typed-`RateLimit`-projection sibling composes through in `const`
3404 /// context. Routes byte-for-byte through the peer `pub const fn`
3405 /// [`Self::window`] canonical-`Duration` projection so any future
3406 /// arm-magnitude edit on the sibling accessor reaches this reverse
3407 /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3408 /// per-arm probes each dispatch through one `pub const fn` on the
3409 /// substrate primitive rather than a hand-authored per-arm second-
3410 /// magnitude literal that would silently drift on any future
3411 /// [`Self::window`] arm-magnitude edit.
3412 ///
3413 /// Prior to the `const` lift the body dispatched through
3414 /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3415 /// iterator-driven linear scan whose iterator methods
3416 /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3417 /// `PartialEq` dispatch each carry non-`const` bounds on stable
3418 /// Rust 1.94, so any downstream substrate-side `const`-context
3419 /// consumer of the reverse resolver (a module-scope
3420 /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3421 /// invariant pin on a typed fixture, a future M4
3422 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3423 /// webhook `const fn` per-`:politicas` canonical-window floor over a
3424 /// typed [`RateLimit`] scalar, any future `const fn`
3425 /// per-`:contratos`-edge rate-limit-override overlay resolver over
3426 /// the substrate primitive that wants to fan on the canonical unit
3427 /// at compile time) surfaced as a downstream E0015 far from the
3428 /// resolver's own declaration. The `pub const fn` posture closes
3429 /// the drift structurally at caixa-core build time.
3430 ///
3431 /// Pinned load-bearing at the substrate-primitive level by
3432 /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3433 /// eval-surface pin via `const fn` wrapper) and
3434 /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3435 /// (composition-witness pin against the peer `Self::window` scalar
3436 /// dispatch).
3437 #[must_use]
3438 pub const fn from_window(window: Duration) -> Option<Self> {
3439 if window.subsec_nanos() != 0 {
3440 return None;
3441 }
3442 // Route through the peer `pub const fn` [`Self::window`]
3443 // canonical-`Duration` projection so any future arm-magnitude
3444 // edit on the sibling accessor reaches this reverse resolver by
3445 // construction — the per-arm `secs` comparison keys off
3446 // `Duration::as_secs` (`pub const fn`), not a hand-authored
3447 // per-arm second-magnitude literal that would silently drift.
3448 let secs = window.as_secs();
3449 if secs == Self::Second.window().as_secs() {
3450 Some(Self::Second)
3451 } else if secs == Self::Minute.window().as_secs() {
3452 Some(Self::Minute)
3453 } else if secs == Self::Hour.window().as_secs() {
3454 Some(Self::Hour)
3455 } else {
3456 None
3457 }
3458 }
3459
3460 /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3461 /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3462 /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3463 /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3464 /// consumes.
3465 ///
3466 /// The peer `Duration → &'static str` axis folded onto the substrate
3467 /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3468 /// production consumers ([`rate_limit_codec::render`] and
3469 /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3470 /// migrated (61421a6): the free helper's `Duration → &str` projection
3471 /// is now the two-step composition
3472 /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3473 /// reads through the typed accessor. This lift closes the peer
3474 /// `&str → Duration` axis by folding the vestigial module-private
3475 /// `rate_limit_window_from_unit` delegate onto this associated method
3476 /// — the codec's parse arm and every future wire-side consumer of the
3477 /// `&str → Duration` projection (a future admission-webhook that
3478 /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3479 /// before it's promoted to a validated typed slot, a future
3480 /// `feira lint` shape-probe that reads the author-surface bytes
3481 /// verbatim) now reach for exactly one typed dispatch on the
3482 /// substrate primitive.
3483 ///
3484 /// Same "closed-set typed-enum discriminator with canonical
3485 /// projections per axis" discipline the sibling [`Self::as_suffix`]
3486 /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3487 /// methods carry — this associated method closes the fifth (and last
3488 /// unlifted) projection axis on the arm-table, so the closed-set enum
3489 /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3490 /// consumer of the `:politicas :rate-limit :window` axis reaches
3491 /// through. A future rate-limit-unit addition (a `"d"` day suffix
3492 /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3493 /// `"ms"` sub-second window once high-throughput per-edge policies
3494 /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3495 /// variant plus one arm per method — the compiler enforces
3496 /// exhaustiveness on every consumer's `match self` arms and picks
3497 /// the new unit up by construction across all five projections.
3498 #[must_use]
3499 pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3500 Self::from_suffix(suffix).map(Self::window)
3501 }
3502}
3503
3504/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3505/// every consumer that formats a canonical rate-limit unit as user-
3506/// facing text (future M4 admission-webhook rejection bodies naming
3507/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3508/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3509/// codec's parse arm accepts and the render arm emits. Same
3510/// as_str-through-Display convergence discipline the sibling
3511/// [`PlacementStrategy`], [`crate::CaixaKind`],
3512/// [`crate::supervisor::RestartStrategy`], and
3513/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3514impl std::fmt::Display for RateLimitUnit {
3515 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3516 f.write_str(self.as_suffix())
3517 }
3518}
3519
3520/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3521/// validated [`MeshPolicy::timeout`] past
3522/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3523/// (inclusive on both ends, integer-millisecond magnitudes by the
3524/// canonical-form gate immediately preceding).
3525///
3526/// The typed field is `Option<Duration>` (the zero-floor arm
3527/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3528/// `Duration::ZERO`, and the canonical-form arm
3529/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3530/// sub-millisecond residue), so a programmatic struct literal
3531/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3532/// 24h) and the equivalent author-surface form
3533/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3534/// integer-hour magnitude) both round-trip cleanly through serde — a
3535/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3536/// above the documented production-playbook band (Envoy default `15s`,
3537/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3538/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3539/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3540/// at `~3600s`) silently degenerates the mesh-policy contract: the
3541/// per-call deadline is structurally so long that no realistic
3542/// synchronous-`:contratos` traversal can reach it, so the typed slot
3543/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3544/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3545/// blocking" degenerates to a nominal-only contract on the
3546/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3547/// the sibling `:politicas :retries` axis and the
3548/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3549/// `:politicas :circuit-breaker :max-failures` axis — all three close
3550/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3551/// footgun the prior zero-floor-and-canonical-form-only checks left
3552/// open.
3553///
3554/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3555/// shared duration codec emits (`"<n>h"` for any integer-hour
3556/// magnitude) — every value in the canonical authoring form's
3557/// `<integer><unit>` grammar at or below this cap renders to a clean
3558/// canonical string. The cap sits an order of magnitude above every
3559/// documented production-playbook recommendation band (Envoy default
3560/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3561/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3562/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3563/// below the clearly-pathological "effectively no timeout" floor
3564/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3565/// want for a long-running synchronous workflow, but a hard wall above
3566/// which the mesh-level deadline is structurally a non-deadline.
3567/// Lifted as a typed `pub const` so the bound has exactly one source
3568/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3569/// materializer's admission webhook and the caixa-mesh-side
3570/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3571/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3572/// other typed upper bound in this crate carries
3573/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3574/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3575/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3576/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3577pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3578
3579/// Upper-bound ceiling on the `:politicas :retries` axis — every
3580/// validated [`MeshPolicy::retries`] past
3581/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3582///
3583/// The typed slot is `Option<u32>` (`None` = no retries on transient
3584/// failure; `Some(0)` already rejected by the
3585/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3586/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3587/// .. }`) and the equivalent author-surface form
3588/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3589/// serde / the codec — a structurally unbounded `u32` ceiling. The
3590/// runtime substrate that consumes the value (Envoy's
3591/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3592/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3593/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3594/// admission cap is 10) translates a four-billion-retry policy into a
3595/// thundering-herd amplification vector on transient failure — the
3596/// caller's one request fans out to `retries` server-side calls per
3597/// edge per traversal, multiplying load by `(retries+1)^depth` across
3598/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3599/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3600/// invariant on the retry axis; both belong at the typed-slot layer.
3601///
3602/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3603/// upstream mesh-policy schema that documents one) and sits above the
3604/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3605/// every documented production playbook): a value the author can
3606/// plausibly want, but a hard wall above which the policy is
3607/// structurally a footgun. Lifted as a typed `pub const` so the bound
3608/// has exactly one source of truth — a future axis reaching for the
3609/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3610/// materializer's admission webhook, the caixa-mesh-side
3611/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3612/// one place. Same shape every other typed upper bound in this crate
3613/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3614/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3615/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3616/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3617pub const POLICY_RETRIES_MAX: u32 = 10;
3618
3619/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3620/// axis — every validated [`CircuitBreaker::max_failures`] past
3621/// [`AplicacaoSpec::validate_politicas`] lies in
3622/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3623///
3624/// The typed field is `u32` (the zero-floor arm
3625/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3626/// `0` — a breaker that trips on the first call), so a programmatic
3627/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3628/// and the equivalent author-surface form
3629/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3630/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3631/// `max_failures` value far above the documented production-playbook
3632/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3633/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3634/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3635/// typical 5–50) silently disables the breaker's protection role:
3636/// the threshold is structurally so high that no realistic
3637/// failures-per-`:window` traffic shape can reach it, so the breaker
3638/// never trips and the typed slot becomes a no-op carried on every
3639/// emitted Envoy / Cilium L7 overlay. Pairs with the
3640/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3641/// axis — both close the "structurally unbounded `u32` ceiling on a
3642/// typed policy axis" footgun the prior zero-floor-only checks left
3643/// open.
3644///
3645/// The `1000` ceiling sits an order of magnitude above every
3646/// documented upstream production-playbook recommendation band (the
3647/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3648/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3649/// the clearly-pathological "effectively no protection"
3650/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3651/// plausibly want at hyperscale, but a hard wall above which the
3652/// policy is structurally a no-op. Lifted as a typed `pub const` so
3653/// the bound has exactly one source of truth — the future M4
3654/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3655/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3656/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3657/// one place. Same shape every other typed upper bound in this crate
3658/// carries ([`POLICY_RETRIES_MAX`],
3659/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3660/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3661/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3662pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3663
3664/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3665/// every validated [`CircuitBreaker::window`] past
3666/// [`AplicacaoSpec::validate_politicas`] lies in
3667/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3668/// integer-millisecond magnitudes by the canonical-form gate
3669/// immediately preceding).
3670///
3671/// The typed field is `Duration` (the zero-floor arm
3672/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3673/// `Duration::ZERO`, and the canonical-form arm
3674/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3675/// sub-millisecond residue), so a programmatic struct literal
3676/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3677/// and the equivalent author-surface form
3678/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3679/// integer-hour magnitude) both round-trip cleanly through serde — a
3680/// structurally unbounded `Duration` ceiling. A `:window` value far
3681/// above the documented production-playbook band (Hystrix
3682/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3683/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3684/// Istio `outlierDetection.interval` default `10s`, Envoy
3685/// `outlier_detection.interval` default `10s`, AWS App Mesh
3686/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3687/// breaker's role: a rolling-window failure counter whose window is
3688/// hours long is operationally a lifetime counter, the breaker's
3689/// "recent failures" memory is structurally so long that transient
3690/// failures are never forgotten, and the typed slot becomes a no-op
3691/// trigger that trips once and stays tripped for the lifetime of the
3692/// component carried on every emitted Envoy / Cilium L7 overlay.
3693///
3694/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3695/// shared duration codec emits (`"<n>h"` for any integer-hour
3696/// magnitude) — every value in the canonical authoring form's
3697/// `<integer><unit>` grammar at or below this cap renders to a clean
3698/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3699/// cap on the first typed-`Duration` `:politicas` axis: the two
3700/// duration-typed `:politicas` axes now share a single uniform top
3701/// edge so the next typed-slot wiring (the future caixa-mesh
3702/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3703/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3704/// admission webhook) reaches for either field knowing the value is
3705/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3706/// sits two orders of magnitude above every documented upstream
3707/// production-playbook recommendation band (Hystrix / resilience4j /
3708/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3709/// and below the clearly-pathological "rolling window degenerates to
3710/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3711/// author can plausibly want for a very-low-traffic long-tail
3712/// failure-detection window, but a hard wall above which the breaker's
3713/// rolling-window contract is structurally a lifetime-counter contract.
3714/// Lifted as a typed `pub const` so the bound has exactly one source
3715/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3716/// materializer's admission webhook and the caixa-mesh-side
3717/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3718/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3719/// other typed upper bound in this crate carries
3720/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3721/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3722/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3723/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3724/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3725pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3726
3727/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3728/// every validated [`RateLimit::rate`] past
3729/// [`AplicacaoSpec::validate_politicas`] lies in
3730/// `1..=POLICY_RATE_LIMIT_MAX`.
3731///
3732/// The typed field is `u32` (the zero-floor arm
3733/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3734/// zero-rate limit denies every request, the canonical "I forgot
3735/// that 0 means deny-everything" footgun), so a programmatic struct
3736/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3737/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3738/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3739/// round-trip cleanly through serde — a structurally unbounded `u32`
3740/// ceiling. The runtime substrate consuming the value (Envoy's
3741/// `local_rate_limit.token_bucket.max_tokens`, the future
3742/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3743/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3744/// rate-limit into a no-op rate-limiter: the bucket capacity is
3745/// structurally so high no realistic per-edge traffic shape can
3746/// drain it, the limiter never trips, and the typed slot becomes a
3747/// "rate-limit declared, no enforcement" footgun — the canonical
3748/// declared-but-inert shape every other `:politicas` cap arm
3749/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3750/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3751///
3752/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3753/// above every documented upstream production-playbook recommendation
3754/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3755/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3756/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3757/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3758/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3759/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3760/// `u32::MAX`): a value the author can plausibly want at hyperscale
3761/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3762/// /h-window arm), but a hard wall above which the policy is
3763/// structurally a no-op carried verbatim on every emitted Envoy /
3764/// Cilium L7 overlay. The cap brackets all three canonical windows
3765/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3766/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3767/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3768/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3769/// has exactly one source of truth — the future M4
3770/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3771/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3772/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3773/// one place. Same shape every other typed upper bound in this crate
3774/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3775/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3776/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3777/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3778/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3779/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3780pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3781
3782// `:entrada :host` total-length and per-label cap axes route through
3783// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3784// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3785// pair of aplicacao-private aliases the previous `validate_entrada_host`
3786// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3787// = 63`) were structurally the same K8s Gateway API v1 Hostname
3788// admission-schema bounds — the total-length cap on the OpenAPI
3789// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3790// same regex — that the peer axes at the caixa-core::render level pin,
3791// so hoisting both readers onto the shared lifted constants closes the
3792// third-occurrence duplication threshold structurally: the M4
3793// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3794// label validator, the future per-`Certificate` SAN emitter, and every
3795// other per-Gateway-API-Hostname landing site reach the same one place
3796// as the `:entrada :host` gate does — no per-axis alias drift surface
3797// between them, by construction.
3798
3799/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3800/// extractor expression — the upper bound `validate_placement_shard_key`
3801/// enforces on every well-shaped shard-key past validate. The realistic
3802/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3803/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3804/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3805/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3806/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3807/// in `:shard-key`" footgun at validate time rather than at the future
3808/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3809const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3810
3811/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3812/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3813/// that maps the shared parser-shaped reason into the
3814/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3815/// is self-locating (the offending `caixa:` is named verbatim) and
3816/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3817/// fix it in one edit. Same diagnostic shape as
3818/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3819/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3820fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3821 // Empty is already gated by `MembroCaixaEmpty` at the call site;
3822 // re-checking here keeps the predicate usable from any future
3823 // call site (the M4 CR materializer) without an empty-check
3824 // footgun. The shared
3825 // [`crate::render::require_valid_dns_1123_label`] helper brackets
3826 // the empty-first + shape cascade every peer name axis
3827 // (`:placement :clusters`, `:placement :affinity`, `:contratos
3828 // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3829 // `:upgrade-from :module`) routes through, so drift between the
3830 // eight axes' accepted DNS-1123-label sets is structurally
3831 // impossible.
3832 crate::render::require_valid_dns_1123_label(
3833 caixa,
3834 || AplicacaoError::MembroCaixaEmpty,
3835 |reason| AplicacaoError::MembroCaixaInvalid {
3836 caixa: caixa.to_string(),
3837 reason,
3838 },
3839 )
3840}
3841
3842/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3843/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3844/// that maps the shared parser-shaped reason into the
3845/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3846///
3847/// Cluster names land in DNS-1123-label territory across every consumer:
3848/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3849/// the `lareira-fleet-programs` aggregator applies to scope programs to
3850/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3851/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3852/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3853/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3854/// side schema enforces the DNS-1123 label rule on admission; a
3855/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3856/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3857/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3858/// only gate and the failure surfaces as a no-match at filter time —
3859/// the workload doesn't land in the named cluster, with no diagnostic
3860/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3861/// build time mirrors the `:membros :caixa` value-shape trajectory
3862/// (3f9d7a0) on the peer name axis.
3863///
3864/// The diagnostic carries the offending `cluster:` verbatim plus a
3865/// parser-shaped `reason:` naming the specific violation, so the
3866/// author can grep their caixa.lisp for `:clusters` and fix it in
3867/// one edit. Same diagnostic shape as
3868/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3869fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3870 // Empty is already gated by `PlacementClusterEmpty` at the call
3871 // site; re-checking here keeps the predicate usable from any
3872 // future call site (the M4 CR materializer's per-cluster validator)
3873 // without an empty-check footgun. Routes through the shared
3874 // [`crate::render::require_valid_dns_1123_label`] gate the peer
3875 // name axes each land on.
3876 crate::render::require_valid_dns_1123_label(
3877 cluster,
3878 || AplicacaoError::PlacementClusterEmpty,
3879 |reason| AplicacaoError::PlacementClusterInvalid {
3880 cluster: cluster.to_string(),
3881 reason,
3882 },
3883 )
3884}
3885
3886/// Reject `:placement :affinity` hints whose shape can never legitimately
3887/// land in any downstream selector or label-keyed routing axis. Thin
3888/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3889/// shared parser-shaped reason into the
3890/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3891/// diagnostic is self-locating (the offending `:affinity` is named
3892/// verbatim) and the author can grep their caixa.lisp for
3893/// `:affinity "<hint>"` and fix it in one edit.
3894///
3895/// The `:affinity` slot carries a placement-engine hint — canonical
3896/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3897/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3898/// compression overlay and the future M4 placement-engine's per-hint
3899/// routing axis. Each downstream consumer (caixa-mesh's
3900/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3901/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3902/// `spec.placement.affinity` admission rule, the future M4 per-hint
3903/// node-affinity / pod-affinity rule generator keying off the same
3904/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3905/// selector) requires the value to be a DNS-1123 label — K8s label
3906/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3907/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3908/// admission rule the apiserver enforces.
3909///
3910/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3911/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3912/// Python-module-name leak), `:affinity "data.locality"` (the
3913/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3914/// `:affinity "data-locality-"` (boundary-hyphen violation),
3915/// `:affinity "data locality"` (paste-from-doc whitespace),
3916/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3917/// 64-byte over-cap slug silently passed the empty-only check and the
3918/// failure surfaced as a no-match at the M3 Adaptive compression
3919/// overlay's filter time (`placement.affinity` carried a malformed
3920/// value, no node matched, the workload landed on the default
3921/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3922/// the empty-:affinity / empty-shard-key / zero-:politicas /
3923/// empty-:contratos-target gates already close on every other
3924/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3925/// gate closes the fifth typed slot on the Aplicacao surface to land
3926/// on the canonical DNS-1123 label floor (after the four Servico-name
3927/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3928/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3929/// b0e8748).
3930///
3931/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3932/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3933/// validated values are guaranteed-accepted by the apiserver without
3934/// re-validation at any downstream renderer or admission layer.
3935fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3936 // Empty is gated separately at the call site for a self-locating
3937 // diagnostic; re-checking here keeps the predicate usable from any
3938 // future call site (the M4 CR materializer's per-affinity
3939 // validator) without an empty-check footgun. Routes through the
3940 // shared [`crate::render::require_valid_dns_1123_label`] gate the
3941 // peer name axes each land on.
3942 crate::render::require_valid_dns_1123_label(
3943 affinity,
3944 || AplicacaoError::PlacementAffinityEmpty,
3945 |reason| AplicacaoError::PlacementAffinityInvalid {
3946 affinity: affinity.to_string(),
3947 reason,
3948 },
3949 )
3950}
3951
3952/// Reject `:placement :shard-key` extractor expressions whose shape can
3953/// never legitimately drive the future M4 Akka-style cluster-sharding
3954/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3955/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3956/// diagnostic is self-locating (the offending `:shard-key` value is
3957/// named verbatim alongside the parser-shaped reason) and the author can
3958/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3959/// edit.
3960///
3961/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3962/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3963/// expression naming the message property to hash on. The realistic
3964/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3965/// property name; `$tenantId` — Akka entity-id placeholder;
3966/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3967/// `${tenant}` — interpolation-style template) all sit in the printable
3968/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3969/// multi-line blob landing in `:shard-key`, an embedded space from a
3970/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3971/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3972/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3973/// check and the failure surfaces at the future M4 reconciler's hash
3974/// pass as a runtime extractor-evaluation error far from the source
3975/// `caixa.lisp`, with no field naming which member's `:shard-key`
3976/// carried the offending value.
3977///
3978/// The contract — the printable ASCII single-token intersection-floor
3979/// every Akka-style entity-id extractor implementation admits:
3980///
3981/// - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3982/// peer DNS-1123-label-shaped `:placement :affinity` /
3983/// `:placement :clusters` identifier axes; realistic shard-keys sit
3984/// well under 32 bytes, the cap surfaces paste-from-doc multi-line
3985/// blob footguns at validate time;
3986/// - every byte in the printable ASCII range `0x21..=0x7E` —
3987/// rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3988/// `"$tenantId\n"` from paste-from-aligned-doc /
3989/// paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3990/// `\x7F` — the canonical "embedded null from a copy-paste-binary
3991/// footgun"), and non-ASCII bytes (`"$tenàntId"` —
3992/// un-Punycode-encoded IDN that round-trips inconsistently across
3993/// NFC/NFD normalization).
3994///
3995/// The accepted set is broader than the DNS-1123 label floor the peer
3996/// `:placement :clusters` / `:placement :affinity` axes use because the
3997/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3998/// landing site; it's an extractor expression the future Akka-style
3999/// reconciler reads as a property reference. The realistic forms
4000/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4001/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4002/// but every Akka-style entity-id extractor parses. The
4003/// printable-ASCII-token floor accepts every shape any such extractor
4004/// would accept while rejecting the cross-implementation footguns
4005/// (whitespace breaks token boundaries; non-ASCII round-trips
4006/// inconsistently across YAML emitters and NFC/NFD normalization;
4007/// control characters silently corrupt the next read).
4008///
4009/// Until this gate landed `validate_placement` only refused the
4010/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4011/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4012/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4013/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4014/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4015/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4016/// control character from paste-from-binary, the 64-byte over-cap
4017/// paste-from-doc multi-line slug) silently passed validate. The future
4018/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4019/// would then surface the malformed value either as a runtime
4020/// extractor-evaluation error (whitespace breaks the extractor's token
4021/// boundary, no match) or as a silently-different shard assignment
4022/// across YAML emitters (non-ASCII normalizes differently between the
4023/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4024/// parser, the same entity ID maps to two distinct shards on a
4025/// re-render). Lifting the shape gate to caixa-build time makes the
4026/// extractor-floor invariant a structural property of every validated
4027/// `Placement`: every `Sharded` placement past `validate_placement` has
4028/// a `:shard-key` the future M4 reconciler can hash without
4029/// re-validating at the runtime layer.
4030///
4031/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4032/// [`AplicacaoError::ContratoSubjectInvalid`] /
4033/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4034/// on the peer `:contratos` payload axes — each lifts the
4035/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4036/// closing the canonical "this passed validate but the runtime parser
4037/// rejected it" surprise.
4038fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4039 // Empty is gated separately at the call site via the more
4040 // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4041 // re-checking here keeps the predicate usable from any future call
4042 // site (the M4 CR materializer's per-shard-key validator) without
4043 // an empty-check footgun.
4044 if key.is_empty() {
4045 return Err(AplicacaoError::ShardedKeyEmpty);
4046 }
4047 if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4048 return Err(AplicacaoError::ShardKeyInvalid {
4049 shard_key: key.to_string(),
4050 reason: format!(
4051 "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4052 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4053 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4054 well under 32 bytes, this length suggests a paste-from-doc \
4055 multi-line blob landed in `:shard-key` instead of a single-token \
4056 extractor expression)",
4057 key.len()
4058 ),
4059 });
4060 }
4061 for &b in key.as_bytes() {
4062 if (0x21..=0x7E).contains(&b) {
4063 continue;
4064 }
4065 let reason = if b == b' ' {
4066 "contains a space (Akka-style entity-id extractor expressions are \
4067 single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4068 whitespace breaks the extractor's token boundary at the runtime layer, \
4069 and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4070 a multi-token blob in one `:shard-key` slot)"
4071 .to_string()
4072 } else if b == b'\t' {
4073 "contains a tab character (paste-from-aligned-doc footgun; the \
4074 Akka-style entity-id extractor reads `:shard-key` as a single-token \
4075 reference, embedded whitespace breaks the token boundary at the \
4076 runtime hash-extractor pass)"
4077 .to_string()
4078 } else if b == b'\n' || b == b'\r' {
4079 format!(
4080 "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4081 paste-from-multiline-doc footgun; the Akka-style entity-id \
4082 extractor reads `:shard-key` as a single-token reference, embedded \
4083 newlines either truncate the value at the YAML emitter layer or \
4084 break the token boundary at the runtime hash-extractor pass)"
4085 )
4086 } else if b < 0x20 || b == 0x7F {
4087 format!(
4088 "contains control character 0x{b:02x} (the canonical \
4089 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4090 control characters silently corrupt round-trip serialization \
4091 across YAML emitters and break the runtime hash-extractor's \
4092 single-token parser)"
4093 )
4094 } else {
4095 format!(
4096 "contains non-ASCII byte 0x{b:02x} (the canonical \
4097 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4098 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4099 across YAML emitter implementations — the same entity ID can \
4100 silently map to two distinct shards on a re-render. Use a \
4101 printable-ASCII extractor expression like `tenantId`, \
4102 `$tenantId`, or `metadata.tenantId`)"
4103 )
4104 };
4105 return Err(AplicacaoError::ShardKeyInvalid {
4106 shard_key: key.to_string(),
4107 reason,
4108 });
4109 }
4110 Ok(())
4111}
4112
4113/// Reject `:contratos :de` / `:contratos :para` values whose shape
4114/// can never legitimately match a validated `:membros :caixa`. Thin
4115/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4116/// shared parser-shaped reason into the
4117/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4118/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4119/// the offending value verbatim) and the author can grep their
4120/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4121/// one edit.
4122///
4123/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4124/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4125/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4126/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4127/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4128/// un-Punycode-encoded IDN) silently passed the per-axis check and
4129/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4130/// membership lookup — diagnostic-framed as "this caixa is not in
4131/// `:membros`" when the root cause is "this `:de` value is not a
4132/// well-shaped Servico-name identifier and could never legitimately
4133/// match any validated member". Because every `:membros :caixa` is
4134/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4135/// `names` HashSet structurally never contains an empty / malformed
4136/// string, so the membership lookup arm misframes every empty /
4137/// malformed input. Lifting the shape arm ahead of the lookup
4138/// preserves the legitimate `ContratoMemberMissing` arm (a
4139/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4140/// reference) while routing every structurally-impossible-to-match
4141/// input through the narrower self-locating shape diagnostic.
4142///
4143/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4144/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4145/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4146/// to land on the canonical [`crate::render::is_dns_1123_label`]
4147/// floor. The `slot: &'static str` field carries the kebab-case
4148/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4149/// per-callback-slot diagnostic shape and the
4150/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4151/// (85f102c) cross-list-tag pattern.
4152fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4153 // Routes through the shared
4154 // [`crate::render::require_valid_dns_1123_label`] gate the peer
4155 // name axes each land on. The `slot: &'static str` field flows
4156 // through both error variants so the diagnostic names which
4157 // per-edge axis (`:de` vs `:para`) the offending value came from.
4158 crate::render::require_valid_dns_1123_label(
4159 caixa,
4160 || AplicacaoError::ContratoCaixaEmpty { slot },
4161 |reason| AplicacaoError::ContratoCaixaInvalid {
4162 slot,
4163 caixa: caixa.to_string(),
4164 reason,
4165 },
4166 )
4167}
4168
4169/// Reject `:entrada :para` values whose shape can never legitimately
4170/// match a validated `:membros :caixa`. Thin wrapper around
4171/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4172/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4173/// variant, so the diagnostic is self-locating (the offending
4174/// `:entrada :para` value is named verbatim) and the author can grep
4175/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4176///
4177/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4178/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4179/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4180/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4181/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4182/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4183/// silently passed the per-axis check and surfaced as
4184/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4185/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4186/// root cause is "this `:entrada :para` value is not a well-shaped
4187/// Servico-name identifier and could never legitimately match any
4188/// validated member". Because every `:membros :caixa` is shape-
4189/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4190/// `HashSet` structurally never contains an empty / malformed string,
4191/// so the membership lookup arm misframes every empty / malformed
4192/// input. Lifting the shape arm ahead of the lookup preserves the
4193/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4194/// simply isn't in `:membros` — a phantom reference) while routing
4195/// every structurally-impossible-to-match input through the narrower
4196/// self-locating shape diagnostic.
4197///
4198/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4199/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4200/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4201/// fourth and last Aplicacao-level Servico-name reference axis to
4202/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4203/// No `slot: &'static str` field because there is only one axis
4204/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4205/// the simpler shape mirrors [`validate_membro_caixa`] and
4206/// [`validate_placement_cluster`].
4207fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4208 // Empty is gated separately at the call site for a self-locating
4209 // diagnostic; re-checking here keeps the predicate usable from any
4210 // future call site (the M4 CR materializer's per-`:entrada`
4211 // validator) without an empty-check footgun. Routes through the
4212 // shared [`crate::render::require_valid_dns_1123_label`] gate the
4213 // peer name axes each land on.
4214 crate::render::require_valid_dns_1123_label(
4215 para,
4216 || AplicacaoError::EntradaParaEmpty,
4217 |reason| AplicacaoError::EntradaParaInvalid {
4218 para: para.to_string(),
4219 reason,
4220 },
4221 )
4222}
4223
4224/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4225/// would refuse at admission time. The contract — exactly the regex
4226/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4227/// and `HTTPRoute.spec.hostnames[]`,
4228/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4229/// (max length 253; per-label max length 63):
4230///
4231/// - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
4232/// uppercase, no underscore, no Unicode/IDN — IDN must be
4233/// pre-encoded as Punycode `xn--…` by the author);
4234/// - exactly one optional leading wildcard label (`*.`); a wildcard
4235/// in any non-leading label position is rejected;
4236/// - each `.`-separated label is 1..=63 bytes, with non-hyphen
4237/// alphanumeric at both boundaries (no `-foo`, no `foo-`);
4238/// - total length 1..=253 bytes;
4239/// - no IPv4 literal (Gateway API forbids IP literals);
4240/// - no scheme (`https://`, `http://`), no port (`:8080`), no
4241/// whitespace, no path (`/`).
4242///
4243/// Lifted as a typed gate (rather than an inline cascade in
4244/// `validate()`) so the contract lives in one place — every future
4245/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4246/// materializer's host validator, the future per-`:entrada` SAN
4247/// emission for cert-manager Certificates, the multi-`:entrada`
4248/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
4249/// for the same predicate, not its own. Same compounding shape as
4250/// `is_canonical_rate_limit_window` (808017c) and
4251/// [`WitTarget::label`] (previously the free `contrato_target_label`
4252/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
4253/// per-variant label match is compiler-checked-exhaustive).
4254///
4255/// The diagnostic carries the offending `host:` verbatim plus a
4256/// parser-shaped `reason:` naming the specific violation, so the
4257/// author can grep their caixa.lisp for `:host "<host>"` and fix it
4258/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
4259/// (9888b13).
4260fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
4261 // Empty is already gated by `EmptyEntradaHost` at the call site;
4262 // re-checking here keeps the predicate usable from any future
4263 // call site (M4 CR materializer) without an empty-check footgun.
4264 if host.is_empty() {
4265 return Err(AplicacaoError::EmptyEntradaHost);
4266 }
4267 if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
4268 return Err(AplicacaoError::EntradaHostInvalid {
4269 host: host.to_string(),
4270 reason: format!(
4271 "exceeds Gateway API v1 Hostname max length of {cap} bytes \
4272 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
4273 host.len(),
4274 cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
4275 ),
4276 });
4277 }
4278 if host.contains("://") {
4279 return Err(AplicacaoError::EntradaHostInvalid {
4280 host: host.to_string(),
4281 reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
4282 Gateway API takes the bare hostname)"
4283 .to_string(),
4284 });
4285 }
4286 if host.contains('/') {
4287 return Err(AplicacaoError::EntradaHostInvalid {
4288 host: host.to_string(),
4289 reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4290 matching is in `:entrada :paths`)"
4291 .to_string(),
4292 });
4293 }
4294 // After the `://` scheme-prefix and `/` path arms have ruled out the
4295 // two `:`-bearing shapes the Gateway API actively rejects with
4296 // location-shaped diagnostics, any remaining `:` in the host body is
4297 // either the canonical "I put the port in the `:host` slot"
4298 // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4299 // slot lives one axis away on the same `:entrada` block) or an
4300 // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4301 // Hostname forbids identically to the IPv4-literal arm below. Both
4302 // shapes silently fell through the `://` and `/` arms before this
4303 // lift and surfaced as a deep `label "<rest>:<port>" contains
4304 // invalid character ':'` diagnostic from the per-byte loop near the
4305 // bottom of this predicate, which named the offending byte but not
4306 // the canonical authoring fix — for the port case the author has to
4307 // know the `:entrada` block carries a separate `:port u16` slot
4308 // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4309 // move the value over; for the IPv6 case the author has to know
4310 // Gateway API v1 forbids IP literals across the board. The contract
4311 // doc-comment above already promises "no port (`:8080`)" verbatim
4312 // in the rejected-shape enumeration but the predicate's
4313 // implementation refused the `:` only as a side-effect of the
4314 // per-label `[a-z0-9-]` character-class loop; this arm brings the
4315 // implementation in line with the documented contract by surfacing
4316 // the canonical fix at the top-level shape gate, peer with how the
4317 // `://` arm names the scheme prefix and the `/` arm names the
4318 // `:entrada :paths` axis. Same compounding trajectory the recent
4319 // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4320 // — the typed slot's rejected set matches the apiserver's rejected
4321 // set, structurally, with a self-locating diagnostic at the
4322 // offending axis instead of a deep parser-shape leak.
4323 if host.contains(':') {
4324 return Err(AplicacaoError::EntradaHostInvalid {
4325 host: host.to_string(),
4326 reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4327 slot — a separate `u16` axis on the same `:entrada` block, \
4328 defaulting to 8080 — not in the host body; drop the `:<port>` \
4329 suffix and author the bare hostname. If you intended an IPv6 \
4330 literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4331 Hostname forbids IP literals identically to the IPv4-literal \
4332 arm — use a DNS name)"
4333 .to_string(),
4334 });
4335 }
4336 // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4337 // predicate — the same single source of truth every peer
4338 // ASCII-whitespace scan in caixa-core flows through: the four
4339 // typed-magnitude codec sites (`limits::parse_byte_size` backing
4340 // `:limits :memory`, `limits::parse_duration` backing `:limits
4341 // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4342 // `aplicacao::rate_limit_codec::parse` backing `:politicas
4343 // :rate-limit`) and the shared duration codec
4344 // (`supervisor::duration_codec::parse`) backing `:supervisor
4345 // :restart-window` / `:politicas :timeout` / `:politicas
4346 // :circuit-breaker :window`. This landing closes the last string-typed
4347 // slot in caixa-core still calling `.bytes().any(|b|
4348 // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4349 // across every typed slot now shares one predicate, so a future
4350 // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4351 // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4352 // deliberately excluded from the peer non-ASCII predicate) can
4353 // extend at this shared site in one edit rather than seven
4354 // independent scans diverging over time. Naming the offending byte
4355 // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4356 // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4357 // the offending byte verbatim" discipline every peer codec site
4358 // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4359 // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4360 if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4361 return Err(AplicacaoError::EntradaHostInvalid {
4362 host: host.to_string(),
4363 reason: format!(
4364 "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4365 Hostname is a single-token DNS name — leading, trailing, \
4366 or embedded whitespace breaks the K8s apiserver's Hostname \
4367 regex at admission time; the paste-from-aligned-doc / \
4368 paste-from-shell-history / paste-from-CSV footgun silently \
4369 lands a multi-token blob in `:entrada :host`. Strip every \
4370 whitespace byte and author the bare hostname — space \
4371 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4372 refuse identically)"
4373 ),
4374 });
4375 }
4376 // Peer of the ASCII-whitespace scan above: route the non-ASCII
4377 // subset of Unicode `White_Space` through the shared
4378 // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4379 // single source of truth every peer non-ASCII-whitespace scan in
4380 // caixa-core flows through: `limits::parse_byte_size` (`:limits
4381 // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4382 // `limits::parse_millicores` (`:limits :cpu`),
4383 // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4384 // and `supervisor::duration_codec::parse` (`:supervisor
4385 // :restart-window` / `:politicas :timeout` / `:politicas
4386 // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4387 // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4388 // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4389 // paste-from-web-doc), or an EM-SPACE-split host
4390 // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4391 // survived this predicate's ASCII byte-scan (none of the UTF-8
4392 // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4393 // `u8::is_ascii_whitespace`), then landed on the per-label
4394 // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4395 // predicate with the generic `label "…" must start and end with an
4396 // alphanumeric` diagnostic — a "far from source at build-time"
4397 // leak that names the label-shape violation but not the
4398 // paste-from-typography origin the author actually needs to fix.
4399 // Peer with the four codec sites the 1b75b38 landing pinned: the
4400 // typed slot's diagnostic axis names the offending codepoint
4401 // (`U+XXXX`) verbatim rather than laundering the value through a
4402 // downstream label-shape arm, so the author can grep their
4403 // caixa.lisp for the invisible codepoint at the surfaced position
4404 // rather than eyeball a multi-byte host for embedded NBSP / LINE
4405 // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4406 // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4407 // drift between any two typed-slot sites' non-ASCII-whitespace
4408 // rejection set becomes a single-edit fix at the shared predicate
4409 // rather than N independent inline scans diverging over time, and
4410 // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4411 // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4412 // `char::is_whitespace`" class the peer non-ASCII predicate's
4413 // doc-comment names as the follow-up trajectory) extends at the
4414 // shared predicate in one edit rather than seven.
4415 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4416 return Err(AplicacaoError::EntradaHostInvalid {
4417 host: host.to_string(),
4418 reason: format!(
4419 "contains non-ASCII Unicode whitespace character {ch:?} \
4420 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4421 single-token DNS name limited to `[a-z0-9-]` labels; \
4422 the paste-from-typography footgun silently lands an \
4423 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4424 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4425 `U+3000`, and every other member of the Unicode \
4426 `White_Space` property outside the ASCII byte range) \
4427 in `:entrada :host`, which the K8s apiserver's \
4428 Hostname regex refuses at admission time far from the \
4429 caixa.lisp source line. Strip every non-ASCII \
4430 whitespace character and author the bare hostname \
4431 with only ASCII bytes (write \"checkout.quero.cloud\" \
4432 verbatim)",
4433 codepoint = ch as u32,
4434 ),
4435 });
4436 }
4437
4438 // Strip the optional single leading wildcard label *before* the
4439 // trailing-dot check so the bare `"*."` form surfaces the more
4440 // self-locating "wildcard without domain" diagnostic instead of
4441 // the generic "trailing dot" one.
4442 let (had_wildcard, rest) = match host.strip_prefix("*.") {
4443 Some(r) => (true, r),
4444 None => (false, host),
4445 };
4446 if had_wildcard && rest.is_empty() {
4447 return Err(AplicacaoError::EntradaHostInvalid {
4448 host: host.to_string(),
4449 reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4450 });
4451 }
4452 if rest.contains('*') {
4453 return Err(AplicacaoError::EntradaHostInvalid {
4454 host: host.to_string(),
4455 reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4456 no inner or trailing `*` labels"
4457 .to_string(),
4458 });
4459 }
4460 if rest.ends_with('.') {
4461 return Err(AplicacaoError::EntradaHostInvalid {
4462 host: host.to_string(),
4463 reason: "must not have a trailing `.` (Gateway API hostnames are not \
4464 fully-qualified with a root dot; the apiserver regex rejects \
4465 trailing dots)"
4466 .to_string(),
4467 });
4468 }
4469
4470 // Reject pure IPv4 literals: four dot-separated labels, every
4471 // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4472 // literals as Hostnames.
4473 let labels: Vec<&str> = rest.split('.').collect();
4474 if labels.len() == 4
4475 && labels
4476 .iter()
4477 .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4478 {
4479 return Err(AplicacaoError::EntradaHostInvalid {
4480 host: host.to_string(),
4481 reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4482 literals; use a DNS name)"
4483 .to_string(),
4484 });
4485 }
4486
4487 // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4488 // hyphen, with non-hyphen at both boundaries.
4489 for label in &labels {
4490 if label.is_empty() {
4491 return Err(AplicacaoError::EntradaHostInvalid {
4492 host: host.to_string(),
4493 reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4494 });
4495 }
4496 if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4497 return Err(AplicacaoError::EntradaHostInvalid {
4498 host: host.to_string(),
4499 reason: format!(
4500 "label {label:?} exceeds DNS-1123 label max length of \
4501 {cap} bytes (got {} bytes)",
4502 label.len(),
4503 cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4504 ),
4505 });
4506 }
4507 let bytes = label.as_bytes();
4508 if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4509 return Err(AplicacaoError::EntradaHostInvalid {
4510 host: host.to_string(),
4511 reason: format!(
4512 "label {label:?} must start and end with an alphanumeric \
4513 (no leading or trailing `-`)"
4514 ),
4515 });
4516 }
4517 for &b in bytes {
4518 let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4519 if !valid {
4520 let msg = if b.is_ascii_uppercase() {
4521 format!(
4522 "label {label:?} contains uppercase character {ch:?} \
4523 (Gateway API hostnames are lowercase-only; use {lower:?})",
4524 ch = b as char,
4525 lower = label.to_ascii_lowercase()
4526 )
4527 } else if b == b'_' {
4528 format!(
4529 "label {label:?} contains `_` (Gateway API hostnames \
4530 allow only `[a-z0-9-]`; use `-` instead)"
4531 )
4532 } else {
4533 format!(
4534 "label {label:?} contains invalid character {ch:?} \
4535 (Gateway API hostnames allow only `[a-z0-9-]`)",
4536 ch = b as char
4537 )
4538 };
4539 return Err(AplicacaoError::EntradaHostInvalid {
4540 host: host.to_string(),
4541 reason: msg,
4542 });
4543 }
4544 }
4545 }
4546 Ok(())
4547}
4548
4549/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4550/// would refuse at admission time. Thin wrapper around
4551/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4552/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4553/// variant, preserving the more self-locating
4554/// [`AplicacaoError::EntradaPathEmpty`] /
4555/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4556/// path fails those narrower invariants first.
4557///
4558/// The contract is the canonical HTTP-path grammar — `1..=
4559/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4560/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4561/// whitespace/control/non-ASCII bytes — shared with the
4562/// `:contratos :endpoint` axis through the lifted predicate so drift
4563/// between either landing site and the K8s apiserver-side
4564/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4565/// the predicate, not a per-renderer "this passed validate but failed
4566/// admission" surprise. The diagnostic carries the offending `path:`
4567/// verbatim plus a parser-shaped `reason:` naming the specific
4568/// violation, so the author can grep their caixa.lisp for `:paths`
4569/// and fix it in one edit. Same diagnostic shape as
4570/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4571/// axis.
4572fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4573 // Empty and missing-leading-`/` are already gated at the call
4574 // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4575 // checking here keeps the per-axis narrower diagnostics in force
4576 // when the predicate is reached directly (and `is_gateway_api_http_path`
4577 // itself defends against `bytes[0]`-style indexing on empty
4578 // input).
4579 if path.is_empty() {
4580 return Err(AplicacaoError::EntradaPathEmpty);
4581 }
4582 if !path.starts_with('/') {
4583 return Err(AplicacaoError::EntradaPathNotAbsolute {
4584 path: path.to_string(),
4585 });
4586 }
4587 crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4588 AplicacaoError::EntradaPathInvalid {
4589 path: path.to_string(),
4590 reason,
4591 }
4592 })
4593}
4594
4595mod rate_limit_codec {
4596 // `Duration` is no longer named here — the codec routes through
4597 // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4598 // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4599 // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4600 // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4601 // closed-set enum's arm-table rather than through vestigial free-helper
4602 // delegates.
4603 use super::{RateLimit, RateLimitUnit};
4604 use serde::{Deserialize, Deserializer, Serializer};
4605
4606 pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4607 match v {
4608 Some(rl) => s.serialize_str(&render(*rl)),
4609 None => s.serialize_none(),
4610 }
4611 }
4612
4613 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4614 let opt: Option<String> = Option::deserialize(d)?;
4615 match opt {
4616 None => Ok(None),
4617 Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4618 }
4619 }
4620
4621 fn parse(s: &str) -> Result<RateLimit, String> {
4622 // Whitespace-rejection arm — peer with the leading-`+`
4623 // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4624 // same canonical-form render-determinism axis. Until this gate
4625 // landed the parser silently tolerated leading / trailing /
4626 // internal whitespace via the top-level `s.trim()` and the
4627 // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4628 // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4629 // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4630 // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4631 // serde silently round-tripped to `"100/s"` on the next emit
4632 // (a *different* canonical string) — breaking the THEORY.md
4633 // Part V render-determinism contract on the same
4634 // canonical-form-drift axis the leading-`+` arm below (the
4635 // 4eeae98 predecessor) and the leading-zero arm below (the
4636 // 4f46830 predecessor) already close.
4637 //
4638 // The canonical author shape is `<integer>/<s|m|h>` with no
4639 // whitespace bytes anywhere — every string [`render`] emits
4640 // carries none, so the parser's accepted set must match for
4641 // serialize / deserialize to round-trip losslessly. This gate
4642 // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4643 // `unit.trim()` calls below strict no-ops on the accepted set
4644 // (every byte-position match they would perform is now already
4645 // trimmed away by the accepted set itself), while the arm
4646 // surfaces every rejected whitespace-carrying shape with a
4647 // self-locating diagnostic naming the offending byte and the
4648 // canonical form the author intended, peer with every prior
4649 // canonical-form-drift arm on this codec.
4650 //
4651 // Routed through the lifted
4652 // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4653 // same source of truth the four peer typed-magnitude codec
4654 // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4655 // `limits::parse_millicores`, `supervisor::duration_codec`)
4656 // share. `u8::is_ascii_whitespace()` at the predicate covers
4657 // the five WhatWG-conformant ASCII whitespace bytes (space,
4658 // tab, LF, FF, CR); the "single lifted predicate" discipline
4659 // the peer non-ASCII arm below carries on the strictly-
4660 // complementary Unicode `White_Space` class extends here to
4661 // the ASCII byte set as well.
4662 if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4663 return Err(format!(
4664 "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4665 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4666 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4667 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4668 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4669 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4670 on first serialize — breaking the THEORY.md Part V render-determinism \
4671 contract every typed slot carries. Strip every whitespace byte (write \
4672 `\"100/s\"` verbatim)"
4673 ));
4674 }
4675 // Non-ASCII Unicode `White_Space` arm — the strictly-
4676 // complementary class the ASCII arm above cannot see.
4677 // `str::trim` at the top of every peer codec uses
4678 // `char::is_whitespace` (Unicode `White_Space`, strictly
4679 // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4680 // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4681 // survives the byte-scan (its UTF-8 bytes are not in
4682 // `is_ascii_whitespace`), gets silently stripped by the
4683 // top-level `s.trim()` below, and the value round-trips
4684 // through `render` to a *different* canonical form
4685 // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4686 // render-determinism contract every typed slot carries.
4687 // Closed here (`:politicas :rate-limit`) and at the three
4688 // peer codec sites (`limits::parse_byte_size`,
4689 // `limits::parse_duration`, `supervisor::duration_codec`)
4690 // through the shared
4691 // [`crate::render::find_non_ascii_whitespace_char`] predicate
4692 // — the "single lifted predicate across all four codec sites
4693 // in one follow-up run" the 24a8ad4 commit body's `Forward
4694 // compounding` bullet named as the next compounding step.
4695 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4696 return Err(format!(
4697 "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4698 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4699 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4700 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4701 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4702 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4703 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4704 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4705 silently strips it at parse entry, and the value round-trips through \
4706 `render` to a *different* canonical form (`\"100/s\"`) on first \
4707 serialize — breaking the THEORY.md Part V render-determinism contract \
4708 every typed slot carries. Strip every non-ASCII whitespace character \
4709 (write `\"100/s\"` verbatim with only ASCII bytes)",
4710 cp = ch as u32
4711 ));
4712 }
4713 let s = s.trim();
4714 let (rate_str, unit) = s
4715 .split_once('/')
4716 .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4717 let rate_trim = rate_str.trim();
4718 // The canonical authoring form for `:politicas :rate-limit` is
4719 // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4720 // non-negative integer with no decimal point and no leading
4721 // sign, so the parser's accepted set must match for
4722 // serialize/deserialize to round-trip without canonical-form
4723 // drift. Until this gate landed the parser accepted any
4724 // `u32::from_str`-shaped magnitude — and current Rust
4725 // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4726 // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4727 // serde silently round-tripped to `"100/s"` on the next emit
4728 // (a *different* canonical string) — breaking the THEORY.md
4729 // Part V render-determinism contract on the fifth typed-codec
4730 // surface in caixa-core (peer with the four duration codecs the
4731 // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4732 // already covered: `supervisor::duration_codec` backing three
4733 // typed-duration slots, `limits::parse_duration` backing
4734 // `:limits :wall-clock`, `limits::parse_byte_size` backing
4735 // `:limits :memory`). The fractional / decimal-shaped sibling
4736 // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4737 // existing rejection arm, but the diagnostic is value-laundered
4738 // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4739 // doesn't name the canonical-form remediation or the round-trip
4740 // drift the next emit would produce); this gate lifts the
4741 // fractional arm onto the same canonical-form diagnostic the
4742 // peer codecs carry.
4743 //
4744 // Strict canonical form: every byte of the magnitude is an
4745 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4746 // inputs the gate distinguishes "non-canonical-but-numeric"
4747 // (parses as f64 or i64 — surfaced with a self-locating
4748 // diagnostic naming the canonical authoring form and the
4749 // round-trip drift the rejected shape would produce on first
4750 // serialize) from "garbage" (parses as neither — surfaced with
4751 // the existing narrower `"not a u32"` wording so its
4752 // diagnostic shape remains stable for the parser-shape footgun
4753 // case).
4754 //
4755 // Routed through the lifted
4756 // [`crate::render::is_digit_only_magnitude`] predicate — the
4757 // same source of truth the four peer typed-magnitude codec
4758 // sites share.
4759 let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4760 if !digit_only {
4761 let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4762 if numeric {
4763 return Err(format!(
4764 "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4765 canonical authoring form for `:politicas :rate-limit` is \
4766 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4767 with no decimal point and no leading `+` / `-` sign. A fractional / \
4768 signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4769 through `render` to a *different* canonical form (`\"1/s\"`, \
4770 `\"100/s\"`, parser-reject) on first serialize — breaking the \
4771 THEORY.md Part V render-determinism contract every typed slot \
4772 carries. Pick an integer rate that fits the desired window \
4773 (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4774 ));
4775 }
4776 return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4777 }
4778 // Leading-zero arm — peer with the prior `"+100/s"` arm above
4779 // (4eeae98's predecessor) on the same canonical-form
4780 // render-determinism axis. The digit-only gate accepts
4781 // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4782 // them losslessly (= 100, 0, 7), but `render` emits the
4783 // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4784 // a *different* canonical string on the next emit, breaking
4785 // the THEORY.md Part V render-determinism contract the same
4786 // way `"+100/s"` did before the leading-`+` arm landed. The
4787 // single-byte magnitude `"0"` itself round-trips losslessly
4788 // through `render` (`render(0)` emits `"0/s"`) — the
4789 // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4790 // what refuses rate-zero authoring, so `"0/s"` stays in the
4791 // accepted set at this codec layer and the diagnostic
4792 // partitioning between canonical-form drift (this arm) and
4793 // semantic-zero (the downstream gate) remains stable.
4794 // Peer with the future leading-zero arms on the three peer
4795 // typed-magnitude codecs the trajectory acknowledges:
4796 // `supervisor::duration_codec`, `limits::parse_duration`,
4797 // `limits::parse_byte_size` — each carries the same
4798 // canonical-form-drift class today; this gate lands the
4799 // discipline on the fourth typed-magnitude codec in
4800 // caixa-core first because the peer `"+100/s"` arm above is
4801 // the closest predecessor on the trajectory.
4802 //
4803 // Routed through the lifted
4804 // [`crate::render::is_leading_zero_padded_magnitude`]
4805 // predicate — the same source of truth the four peer
4806 // typed-magnitude codec sites share.
4807 if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4808 return Err(format!(
4809 "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4810 canonical authoring form for `:politicas :rate-limit` is \
4811 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4812 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4813 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4814 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4815 first serialize — breaking the THEORY.md Part V render-determinism \
4816 contract every typed slot carries. Strip the leading zeros (write \
4817 `\"100/s\"` instead of `\"0100/s\"`)"
4818 ));
4819 }
4820 // The digit-only gate guarantees every byte is `[0-9]`, and
4821 // the leading-zero arm above guarantees the magnitude is
4822 // either the single byte `"0"` or starts with `[1-9]`, so
4823 // the only way `u32::from_str` can fail here is overflow
4824 // (the magnitude exceeds `u32::MAX`). Surface that with an
4825 // overflow-shaped wording so the diagnostic names the
4826 // offending magnitude verbatim rather than collapsing onto
4827 // the non-canonical arm. Same shape
4828 // `supervisor::duration_codec` (1c55a2a) carries on the peer
4829 // duration-codec axis.
4830 let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4831 format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4832 })?;
4833 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4834 // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4835 // arm reads the `&str → Duration` projection through the
4836 // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4837 // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4838 // with [`super::RateLimitUnit::window`]) rather than the vestigial
4839 // module-private `rate_limit_window_from_unit` free helper the
4840 // predecessor 61421a6 left as the last unlifted delegate on this
4841 // axis. One typed dispatch on the substrate primitive instead of
4842 // one runtime call through the free-helper delegate; the sole
4843 // production consumer of the `&str → Duration` axis (this parse
4844 // arm) now reaches for exactly one typed method on the closed-set
4845 // enum, sibling to the codec's render arm's
4846 // [`super::RateLimit::canonical_unit`] dispatch on the paired
4847 // `Duration → RateLimitUnit` axis and to the validate gate's
4848 // [`super::RateLimit::canonical_unit`] shape-probe on the
4849 // canonical-window axis. A future rate-limit-unit addition (a
4850 // `"d"` day suffix once Envoy's `rate_limit_action` grows
4851 // daily-bucket support, a `"ms"` sub-second window once
4852 // high-throughput per-edge policies come into scope per
4853 // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4854 // on the closed-set enum, and the compiler enforces exhaustiveness
4855 // on every consumer's `match self` arms — this parse arm's
4856 // accepted-suffix set, the render arm's emitted-suffix set, the
4857 // validate gate's canonical-window set, and every future
4858 // per-`:contratos`-edge rate-limit-override overlay all pick it up
4859 // by construction.
4860 let unit = unit.trim();
4861 let window = RateLimitUnit::window_from_suffix(unit)
4862 .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4863 Ok(RateLimit { rate, window })
4864 }
4865
4866 fn render(rl: RateLimit) -> String {
4867 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4868 // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4869 // this render arm reads the `Duration → RateLimitUnit` projection
4870 // through the substrate primitive [`super::RateLimit::canonical_unit`]
4871 // (returns `None` on every non-canonical window — the sub-second /
4872 // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4873 // formats the returned typed enum through its
4874 // [`std::fmt::Display`] impl (which routes through
4875 // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4876 // the substrate primitive instead of one runtime `find_map`
4877 // walk through the free-helper delegate chain
4878 // [`super::rate_limit_window_unit`] (the vestigial free helper's
4879 // sole production consumer was this arm; every other consumer of
4880 // the `Duration → unit` axis — the validate gate below and the
4881 // future M4 per-Aplicacao Envoy config reconciler — now reads
4882 // the same typed method).
4883 //
4884 // A future rate-limit-unit addition (a `"d"` day suffix once
4885 // Envoy's `rate_limit_action` grows daily-bucket support) is
4886 // one variant + one arm per method on the closed-set enum, and
4887 // the compiler enforces exhaustiveness on every consumer's
4888 // `match self` arms — the codec's `parse` accepted-suffix set,
4889 // this render arm's emitted-suffix set, the validate gate's
4890 // canonical-window set, and every future per-`:contratos`-edge
4891 // rate-limit-override overlay all pick it up by construction.
4892 if let Some(unit) = rl.canonical_unit() {
4893 format!("{}/{unit}", rl.rate())
4894 } else {
4895 // Defensive fallback for non-canonical windows. Note:
4896 // [`AplicacaoSpec::validate_politicas`] rejects any
4897 // non-canonical `:rate-limit :window` via
4898 // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4899 // a validated `RateLimit` never reaches this branch. The
4900 // emitted `<n>/<k>s` form is *not* round-trippable through
4901 // [`parse`] (which accepts only the closed-set
4902 // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4903 // explicit count) — the validate gate is what makes the
4904 // round-trip a structural property; this branch exists only
4905 // so a programmatic non-validated serialize doesn't panic.
4906 format!("{}/{}s", rl.rate(), rl.window().as_secs())
4907 }
4908 }
4909}
4910
4911// ── placement strategy ───────────────────────────────────────────────
4912
4913/// How the Aplicacao distributes across clusters. Three options:
4914///
4915/// - `SingleNode` — one cluster runs the app at a time; takeover on
4916/// death (Erlang/OTP distributed-app semantics).
4917/// - `Replicated` — every named cluster runs an instance (active-active).
4918/// - `Sharded` — entities distribute by hash key across clusters
4919/// (Akka cluster sharding).
4920#[derive(
4921 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4922)]
4923pub enum PlacementStrategy {
4924 SingleNode,
4925 Replicated,
4926 Sharded,
4927}
4928
4929/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
4930/// distribution-strategy default for the `:placement :estrategia` axis —
4931/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
4932/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
4933/// so every substrate-side consumer that resolves "what
4934/// [`PlacementStrategy`] variant does an author-omitted `:placement
4935/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
4936/// primitive [`PlacementStrategy`].
4937///
4938/// The `:placement :estrategia` default axis has three production
4939/// consumers on the substrate side today: the [`Default for
4940/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
4941/// impl's struct-literal `estrategia` field, and the serde-side
4942/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
4943/// author-omitted `:placement :estrategia` scalar through the [`Default
4944/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
4945/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
4946/// impl and implicit `PlacementStrategy::default()` routes at the sibling
4947/// consumers, with no compile-time link back to the paired
4948/// [`crate::manifest::Caixa::aplicacao_view`] fold's
4949/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
4950/// production consumer that resolves an author-omitted `:placement` slot
4951/// (entirely omitted, not just the `:estrategia` scalar within a declared
4952/// `:placement` block) through [`Placement::default`] which then routes
4953/// through this same discriminator. A future coherent rebrand of the
4954/// `:placement :estrategia` default (a widening to `Sharded` once the
4955/// substrate discovers hash-keyed distribution as the more common
4956/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
4957/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
4958/// names, a per-cluster overlay the operator pins through a future
4959/// `:placement-overrides` slot) would have had to migrate a lifted
4960/// discriminator on one path and open-coded discriminators on the peers
4961/// in lockstep or the four consumers would silently drift out of
4962/// pairing. Lifting the resolution rule to a typed `pub const` on the
4963/// substrate primitive means the M3-mesh-canonical `:placement
4964/// :estrategia` default migrates as one unit on any future axis change.
4965///
4966/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
4967/// §II.2's active-active-across-every-named-cluster arm — the closest
4968/// canonical M3 production reference the substrate carries, matching the
4969/// caixa-mesh default axis every M3 renderer already keys off (a
4970/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
4971/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
4972/// under the substrate's fleet-programs aggregator without an explicit
4973/// `:placement :estrategia` override). The two alternatives the closed
4974/// [`PlacementStrategy::ALL`] accept-set carries
4975/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
4976/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
4977/// Akka-style hash-keyed distribution across clusters,
4978/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
4979/// postures an author declares explicitly, never a posture an omitted
4980/// slot should silently assume.
4981///
4982/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
4983/// exactly one source of truth on the `:placement :estrategia` axis, on
4984/// the same substrate-primitive lift discipline the sibling M2
4985/// per-supervisor default set carries
4986/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
4987/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
4988/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
4989/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
4990/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
4991/// ([`crate::render::DEFAULT_NAMESPACE`],
4992/// [`crate::render::DEFAULT_LIBRARY_NAME`],
4993/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
4994/// the M3 mesh-primitive-defining slot family to converge onto the
4995/// substrate-primitive-lift discipline the M2 supervisor-slot family
4996/// already carries end-to-end.
4997pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
4998
4999impl Default for PlacementStrategy {
5000 fn default() -> Self {
5001 // Route the [`Default for PlacementStrategy`] impl through the
5002 // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5003 // `pub const` rather than a raw `Self::Replicated` arm — one
5004 // source of truth for the M3-mesh-canonical active-active-
5005 // across-every-named-cluster `:placement :estrategia` default
5006 // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5007 // lift discipline the sibling M2 per-supervisor default set
5008 // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5009 // paired halves) carries end-to-end. Pinned by
5010 // `placement_strategy_default_routes_through_lifted_default`.
5011 PLACEMENT_ESTRATEGIA_DEFAULT
5012 }
5013}
5014
5015impl PlacementStrategy {
5016 /// Exhaustive iteration surface for every consumer that reads the
5017 /// full closed-set (the future M4 admission-webhook's accepted-
5018 /// strategy listing in its rejection body, a future `feira app
5019 /// placement --list` CLI-side surfacing of the accepted arm-set,
5020 /// any future round-trip fuzz harness). A future variant addition
5021 /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5022 /// names as a trajectory item) extends this slice as a single edit
5023 /// and every consumer picks up the new entry by construction — the
5024 /// compiler-checked exhaustiveness on the sibling method `match`
5025 /// arms is the build-time guarantee that no arm forgets to grow.
5026 /// Same shape as the sibling closed-set typed enums'
5027 /// [`RateLimitUnit::ALL`] (6bce03d) and
5028 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5029 /// surfaces — the third closed-set typed enum on the caixa surface
5030 /// to converge onto the same discipline.
5031 pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5032
5033 /// Canonical camelCase-schema discriminator scalar this variant
5034 /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5035 /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5036 /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5037 /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5038 /// every substrate consumer that dispatches on the strategy (the
5039 /// `lareira-fleet-programs` aggregator, the future `app-operator`
5040 /// reconciler, the M3 Adaptive compression pass) reads the same
5041 /// byte-string the `Serialize` derive emits — the pin test in
5042 /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5043 /// asserts the two paths agree.
5044 #[must_use]
5045 pub const fn as_str(self) -> &'static str {
5046 match self {
5047 Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5048 Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5049 Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5050 }
5051 }
5052
5053 /// Substrate-canonical reverse projection on the `:placement
5054 /// :estrategia` closed-set axis — parses the camelCase-schema
5055 /// discriminator scalar back to the typed variant, or `None` when
5056 /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5057 /// emits. Dispatches on the same lifted
5058 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5059 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5060 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5061 /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5062 /// the round-trip migrate through one caixa-core edit on any future
5063 /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5064 /// §II.5 hint names as a trajectory item lands one variant + one
5065 /// arm per method and the compiler enforces exhaustiveness on every
5066 /// consumer's `match self` arms).
5067 ///
5068 /// Prior to this lift the substrate carried only the forward
5069 /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5070 /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5071 /// derive that emits the same byte-string under
5072 /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5073 /// consumer that wanted to parse a wire-form strategy scalar had to
5074 /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5075 /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5076 /// compile-time link back to the typed variant's canonical lifted
5077 /// constant. A future variant rename or a per-arm serde-attribute
5078 /// drift would silently split the wire byte-string one non-serde
5079 /// consumer parsed from the one the emitter wrote, with the
5080 /// failure surfacing at parse time far from the rebrand commit.
5081 ///
5082 /// Same closed-set-reverse-projection discipline the sibling
5083 /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5084 /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5085 /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5086 /// defining `:placement :estrategia` closed-set axis, the third
5087 /// substrate-side closed-set typed enum to converge on the two-way
5088 /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5089 /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5090 /// and side-step the [`std::str::FromStr`]-collision clippy
5091 /// (`clippy::should_implement_trait`) the plain `from_str` name
5092 /// carries; a future explicit [`std::str::FromStr`] impl can layer
5093 /// on top by delegating to this canonical arm-dispatch method.
5094 ///
5095 /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5096 /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5097 /// picks the diagnostic form appropriate for its use site — a
5098 /// future `feira app placement --set` CLI-side arg-parse that wants
5099 /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5100 /// Sharded)"` diagnostic builds one on top by iterating
5101 /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5102 /// path folds `None` onto its per-CR structured refusal body.
5103 #[must_use]
5104 pub fn from_wire(s: &str) -> Option<Self> {
5105 match s {
5106 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5107 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5108 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5109 _ => None,
5110 }
5111 }
5112
5113 /// Substrate-canonical per-arm predicate naming the cross-slot
5114 /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5115 /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5116 /// consumes the paired [`Placement::shard_key`] axis (and therefore
5117 /// requires — and is the only strategy that permits — a non-empty
5118 /// `:shard-key` on the paired slot). Today the accept-set is the
5119 /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5120 /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5121 /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5122 /// distributed-app takeover — §II.1) and `Replicated` (active-active
5123 /// across every named cluster) have no hash-keyed routing axis to
5124 /// consume the slot and refuse a declared-but-inert `:shard-key`
5125 /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5126 ///
5127 /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5128 /// satisfies `placement.shard_key().is_some() ==
5129 /// placement.estrategia().requires_shard_key()` by construction — the
5130 /// cross-slot partition the pin
5131 /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5132 /// locks load-bearing, so every downstream consumer that reaches for
5133 /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5134 /// CR materializer's per-CR shard-key resolver, the future
5135 /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5136 /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5137 /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5138 /// shard-key requirement probe, a future author-facing tatara-lisp
5139 /// linter that flags `(:placement (:estrategia Replicated :shard-key
5140 /// "tenantId"))` shapes before `feira lint` reaches
5141 /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5142 /// the substrate primitive — the predicate names *the cross-slot
5143 /// invariant*, not the arm identity.
5144 ///
5145 /// Prior to this lift the "does this strategy consume `:shard-key`"
5146 /// classification lived under the `gen_platform::IsVariant`-derived
5147 /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5148 /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5149 /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5150 /// } else { None }` cascade, the
5151 /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5152 /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5153 /// "tenantId".to_string())` cascade, and the
5154 /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5155 /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5156 /// cascade). Each site conflated two semantically distinct questions:
5157 /// "is the variant `Sharded`?" (arm-identity, what
5158 /// [`Self::is_sharded`] answers) and "does the variant consume
5159 /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5160 /// The two questions land on the same three-way answer under today's
5161 /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5162 /// future arm addition that consumed `:shard-key` under a different
5163 /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5164 /// §II.5 roadmap-hint names that hash-partitions across the cluster
5165 /// pool by client-IP hash rather than an author-declared extractor
5166 /// expression, a hypothetical `WeightedShard` variant that carries a
5167 /// shard-key + per-cluster weight table under a promoted M5
5168 /// adaptive-placement engine) or an addition that did *not* consume
5169 /// `:shard-key` on a semantically Sharded-shaped arm would silently
5170 /// split the two questions. Any consumer that read
5171 /// `.is_sharded().then(…)` for the shard-key requirement gate would
5172 /// silently misclassify the new arm as non-consuming — a fixture
5173 /// builder would omit `:shard-key` where the new arm required one and
5174 /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5175 /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5176 /// commit, a future M4 CR materializer would fall through the
5177 /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5178 /// silently emit an empty extractor at the Akka reconciler layer.
5179 ///
5180 /// Lifting the classification as a substrate-primitive method on the
5181 /// closed-set typed enum names the cross-slot invariant on the
5182 /// primitive that owns the partition: every future arm addition
5183 /// declares its `:shard-key` consumption in one place (this predicate's
5184 /// `match self` arm-set), and every downstream consumer that reaches
5185 /// for the paired shape reads through one typed dispatch. Same
5186 /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5187 /// per-arm predicate on the pre-projection WIT-shape axis and the
5188 /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5189 /// paired predicate on the post-projection typed-view axis — a
5190 /// per-arm semantic-classification predicate paired with the
5191 /// arm-identity predicate the derive already emits, closing the drift
5192 /// footgun on the cross-slot invariant axis.
5193 ///
5194 /// Method-named `requires_shard_key` (not `has_shard_key`, not
5195 /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5196 /// invariant reads as "this strategy *requires* the paired
5197 /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5198 /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5199 /// merely omit it. The `has_*` framing would read as an accessor
5200 /// (returning the presence of an already-carried value) rather than a
5201 /// requirement (naming the invariant the paired slot must satisfy).
5202 /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5203 /// shape as the sibling [`WitContract::is_capability`] /
5204 /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5205 /// arm-family, so every consumer reaches for `.requires_shard_key()`
5206 /// as a drop-in replacement for the `.is_sharded()` conflated read
5207 /// without a return-shape migration.
5208 #[must_use]
5209 pub const fn requires_shard_key(self) -> bool {
5210 match self {
5211 Self::Sharded => true,
5212 Self::SingleNode | Self::Replicated => false,
5213 }
5214 }
5215}
5216
5217// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5218// cross-slot-invariant per-arm predicate: the module-scope const-eval
5219// assertions below trip at caixa-core build time (not test time) if a
5220// future edit rewires the predicate's arm-set away from the singleton
5221// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5222// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5223// runtime pin covers the same truth-table with a more descriptive
5224// diagnostic on failure; these const-eval items add a build-time failure
5225// surface strictly stronger than the runtime pin (a downstream renderer's
5226// `const`-context reader that composed against a rebound predicate would
5227// still surface here before the test suite even ran) and side-step the
5228// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5229// would otherwise accumulate on the caixa-core module baseline.
5230const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5231const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5232const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5233
5234/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5235/// the pretty-printed byte-string every consumer that formats the strategy
5236/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5237/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5238/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5239/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5240/// admission-webhook rejection body) reaches for the same lifted
5241/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5242/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5243/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5244/// `Serialize` derive already emits under
5245/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5246/// [`PlacementStrategy::as_str`] helper already returns.
5247///
5248/// Until this lift landed the sibling OTP-shape typed enums —
5249/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5250/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5251/// so [`std::fmt::Display`] routes through the same discriminant string
5252/// the wire format emits) — carried a stable [`std::fmt::Display`]
5253/// surface but [`PlacementStrategy`] did not; every consumer reaching
5254/// for a strategy byte-string past the wire format had to pick between
5255/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5256/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5257/// derive), any two of which a future variant rename or
5258/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5259/// desynchronize — with the failure surfacing as a downstream renderer /
5260/// operator's per-strategy dispatch reading one spelling while the wire
5261/// format emitted another, far from the source rebrand commit and with
5262/// no field naming the drift. Routing `Display` through
5263/// [`PlacementStrategy::as_str`] makes the three paths
5264/// (`Debug` for structural inspection, `Display` for user-facing text,
5265/// `Serialize` for the wire format) converge on the same lifted
5266/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5267/// the diagnostic byte-string, and the pretty-printed byte-string move
5268/// as a single unit through one canonical declaration each, by
5269/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5270/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5271/// closes the third path.
5272///
5273/// Pin tests
5274/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5275/// and
5276/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5277/// assert the three paths agree byte-for-byte on every variant, so a
5278/// future variant rename or per-arm serde attribute drift is a build
5279/// error visible at caixa-core test time, not a silent per-consumer
5280/// dispatch miss at apply / reconcile time.
5281impl std::fmt::Display for PlacementStrategy {
5282 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5283 f.write_str(self.as_str())
5284 }
5285}
5286
5287/// Where the Aplicacao runs.
5288#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5289#[serde(rename_all = "camelCase")]
5290pub struct Placement {
5291 /// Distribution strategy.
5292 #[serde(default)]
5293 pub estrategia: PlacementStrategy,
5294
5295 /// Named clusters that host this Aplicacao. Required for
5296 /// `Replicated` and `SingleNode`; for `Sharded` declares the
5297 /// shard pool.
5298 #[serde(default)]
5299 pub clusters: Vec<String>,
5300
5301 /// Optional hint to the placement engine: `"data-locality"`,
5302 /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5303 #[serde(default, skip_serializing_if = "Option::is_none")]
5304 pub affinity: Option<String>,
5305
5306 /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5307 #[serde(default, skip_serializing_if = "Option::is_none")]
5308 pub shard_key: Option<String>,
5309}
5310
5311impl Placement {
5312 /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5313 /// `:shard-key` extractor-expression scalar accessor every consumer
5314 /// of the Aplicacao's hash-keyed distribution routing keys off —
5315 /// returns the author-declared `:placement :shard-key` byte-string
5316 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5317 /// own `Option<String>` storage; `None` when the slot is absent
5318 /// (the canonical shape under `:estrategia Replicated` /
5319 /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5320 /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5321 /// partition — `validate` refuses any `Placement` past this call
5322 /// that lands `Some` on a non-`Sharded` strategy or `None` on
5323 /// `Sharded`).
5324 ///
5325 /// The `:placement :shard-key` slot carries the Akka-style
5326 /// cluster-sharding entity-id extractor expression
5327 /// (MESH-COMPOSITION §II.4) — validated by
5328 /// [`validate_placement_shard_key`] to be a non-empty printable-
5329 /// ASCII single-token reference (`tenantId`, `$tenantId`,
5330 /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5331 /// future M4 Akka-style cluster-sharding reconciler hashes without
5332 /// re-validating at the runtime layer), and every downstream
5333 /// consumer that reads the key keys off this scalar (the
5334 /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5335 /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5336 /// declared-but-inert refusal diagnostic, the caixa-mesh
5337 /// per-Aplicacao `placement.shardKey` emit path the substrate
5338 /// operator's per-entity hash-routing reader consumes, the future
5339 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5340 /// per-shard-key resolver).
5341 ///
5342 /// Prior to this lift the `.shard_key` field was accessed inline at
5343 /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5344 /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5345 /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5346 /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5347 /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5348 /// — two open-coded field-accesses that expressed no compile-time
5349 /// link back to the typed slot. A future extension of the
5350 /// `:placement :shard-key` axis to a richer author surface — a
5351 /// per-cluster override the operator pins through a future
5352 /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5353 /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5354 /// alias table the M4 CR materializer resolves per-CR, a
5355 /// per-Aplicacao dynamic `:shard-key` derivation the future
5356 /// adaptive placement engine computes from `:affinity` weights —
5357 /// would have had to be threaded through both open-coded copies in
5358 /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5359 /// arm refusal would silently disagree on which extractor
5360 /// expression a given Placement resolves to. Lifting the resolution
5361 /// rule to a typed method on the substrate primitive means every
5362 /// downstream consumer of the Aplicacao's per-`:placement`
5363 /// hash-key surface reaches for exactly one typed dispatch — the
5364 /// resolver's accept-set migrates as a unit on any future axis
5365 /// addition.
5366 ///
5367 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5368 /// [`WitContract::destination`] / [`WitContract::world_ref`]
5369 /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5370 /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5371 /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5372 /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5373 /// typed dispatch on the substrate primitive, thin projections at
5374 /// each consumer" discipline extended onto the per-`:placement`
5375 /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5376 /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5377 /// — opens the "optional per-slot scalar" projection pattern the
5378 /// sibling per-`:placement` `:affinity`, per-`:politicas`
5379 /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5380 /// match the storage field's name; the accessor's identity name
5381 /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5382 /// slot's docstring already carries.
5383 #[must_use]
5384 pub fn shard_key(&self) -> Option<&str> {
5385 self.shard_key.as_deref()
5386 }
5387
5388 /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5389 /// compression-hint scalar accessor every weighting-consumer of the
5390 /// Aplicacao's per-hint routing surface keys off — returns the
5391 /// author-declared `:placement :affinity` byte-string verbatim as
5392 /// an `Option<&str>`, borrowed from the typed slot's own
5393 /// `Option<String>` storage; `None` when the slot is absent (the
5394 /// canonical shape of an Aplicacao that leaves the compression
5395 /// weighting up to the placement engine's cluster-default arm — no
5396 /// author-authored `data-locality` / `low-latency` / etc. hint
5397 /// biases the routing).
5398 ///
5399 /// The `:placement :affinity` slot carries the M3 Adaptive-
5400 /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5401 /// by [`validate_placement_affinity`] to be a DNS-1123 label
5402 /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5403 /// K8s-conformant label-selector shape every apiserver-side pod-
5404 /// affinity / node-affinity materializer already gates on
5405 /// admission), and every downstream consumer that reads the hint
5406 /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5407 /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5408 /// `placement.affinity` overlay emit path the substrate operator's
5409 /// per-hint weighting-consumer reads, the future M4
5410 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5411 /// pod-affinity / node-affinity selector resolver).
5412 ///
5413 /// Prior to this lift the `.affinity` field was accessed inline at
5414 /// the sole caixa-core site — the
5415 /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5416 /// `if let Some(a) = &self.placement.affinity { …
5417 /// validate_placement_affinity(a)? … }` cascade — one open-coded
5418 /// field-access that expressed no compile-time link back to the
5419 /// typed slot. A future extension of the `:placement :affinity`
5420 /// axis to a richer author surface — a per-cluster override the
5421 /// operator pins through a future `:placement :affinity-overrides`
5422 /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5423 /// tenant hint alias table the M4 CR materializer resolves per-CR,
5424 /// a per-Aplicacao dynamic `:affinity` derivation the future
5425 /// adaptive placement engine computes from `:clusters` topology —
5426 /// would have had to be threaded through the open-coded copy in
5427 /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5428 /// materializer reader that landed on the axis, or the per-hint
5429 /// value-shape gate and its downstream weighting consumers would
5430 /// silently disagree on which hint a given Placement resolves to.
5431 /// Lifting the resolution rule to a typed method on the substrate
5432 /// primitive means every downstream consumer of the Aplicacao's
5433 /// per-`:placement` compression-hint surface reaches for exactly
5434 /// one typed dispatch — the resolver's accept-set migrates as a
5435 /// unit on any future axis addition.
5436 ///
5437 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5438 /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5439 /// optional-scalar axis — same "one typed dispatch on the substrate
5440 /// primitive, thin projections at each consumer" discipline extended
5441 /// onto the per-`:placement` M3-Adaptive-compression-hint
5442 /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5443 /// return accessor on the M3 mesh-slot family; closes the last
5444 /// un-lifted per-`:placement` `Option<String>` axis. Named
5445 /// `affinity()` to match the storage field's name; the accessor's
5446 /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5447 /// vocabulary the slot's docstring already carries.
5448 #[must_use]
5449 pub fn affinity(&self) -> Option<&str> {
5450 self.affinity.as_deref()
5451 }
5452
5453 /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5454 /// strategy scalar accessor every consumer that dispatches on the
5455 /// Aplicacao's per-cluster distribution shape keys off — returns the
5456 /// author-declared `:placement :estrategia` variant verbatim as a
5457 /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5458 /// `PlacementStrategy` storage.
5459 ///
5460 /// The `:placement :estrategia` slot carries the closed-set
5461 /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5462 /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5463 /// `Replicated` — active-active across every named cluster; `Sharded`
5464 /// — Akka-style hash-keyed entity distribution across the cluster pool
5465 /// per §II.4) that every downstream consumer of the Aplicacao's
5466 /// per-cluster fan-out shape keys off. Validated by
5467 /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5468 /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5469 /// matches!(estrategia, Sharded)` — the cross-slot partition the
5470 /// [`Placement::shard_key`] accessor's docstring pins), and every
5471 /// downstream consumer that reads the strategy keys off this scalar
5472 /// (the [`AplicacaoSpec::validate_placement`]
5473 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5474 /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5475 /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5476 /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5477 /// declared-but-inert refusal's
5478 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5479 /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5480 /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5481 /// emit path the substrate operator's per-strategy fan-out reader
5482 /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5483 /// materializer's per-strategy admission-webhook resolver).
5484 ///
5485 /// Prior to this lift the `.estrategia` field was accessed inline at
5486 /// four sites — the [`AplicacaoSpec::validate_placement`]
5487 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5488 /// `estrategia: self.placement.estrategia`, the same method's
5489 /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5490 /// partition dispatch, the non-`Sharded`-arm
5491 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5492 /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5493 /// per-Aplicacao strategy print line at
5494 /// `println!("… {} …", spec.placement.estrategia, …)`
5495 /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5496 /// expressed no compile-time link back to the typed slot. A future
5497 /// extension of the `:placement :estrategia` axis to a richer author
5498 /// surface (a per-cluster override the operator pins through a future
5499 /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5500 /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5501 /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5502 /// derivation the future adaptive placement engine computes from
5503 /// `:affinity` + `:clusters` topology) would have had to be threaded
5504 /// through every open-coded copy in lockstep — one consumer reading
5505 /// the raw variant while a peer read the operator-resolved variant
5506 /// would silently split the `PlacementWithoutClusters` /
5507 /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5508 /// partition-dispatch input, a two-consumer split at the validator
5509 /// far from the source `caixa.lisp` with no field naming the
5510 /// strategy-drift root cause. Lifting the resolution rule to a typed
5511 /// method on the substrate primitive means every downstream consumer
5512 /// of the Aplicacao's per-`:placement` distribution-strategy surface
5513 /// reaches for exactly one typed dispatch — the resolver's accept-set
5514 /// migrates as a unit on any future axis addition.
5515 ///
5516 /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5517 /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5518 /// same "one typed dispatch on the substrate primitive, thin
5519 /// projections at each consumer" discipline extended onto the
5520 /// per-`:placement` distribution-strategy `Copy`-composite-enum
5521 /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5522 /// family; first `Copy`-return accessor on the M3 mesh-slot
5523 /// `Placement` type — companion to the sibling per-`:placement`
5524 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5525 /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5526 /// optional-scalar axes, closing the last unlifted per-`:placement`
5527 /// scalar-value axis (the closed-set `PlacementStrategy`
5528 /// distribution-strategy discriminator) so every downstream
5529 /// per-`:placement` reader now routes through a typed dispatch on
5530 /// the substrate primitive. Named `estrategia()` to match the storage
5531 /// field's name; the accessor's identity name maps onto the
5532 /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5533 /// already carries. Declared `pub const fn` (matching the peer M3
5534 /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5535 /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5536 /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5537 /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5538 /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5539 /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5540 /// [`RateLimit`] — every one a `pub const fn`) so every future
5541 /// substrate-side `const`-context consumer of the resolved
5542 /// distribution-strategy variant (a `const _: () = assert!(…)`
5543 /// module-scope invariant pin on a per-fixture typed [`Placement`],
5544 /// a future M4 admission-webhook `const fn` resolver over a typed
5545 /// [`Placement`], any `const fn` composer that fans on the strategy
5546 /// at compile time) reaches through the same typed dispatch on the
5547 /// substrate primitive at const-eval time as at runtime. Pinned by
5548 /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5549 /// const-eval posture at module scope via `const _:() = …` items so
5550 /// any future accidental downgrade to non-`const` trips at caixa-core
5551 /// build time.
5552 #[must_use]
5553 pub const fn estrategia(&self) -> PlacementStrategy {
5554 self.estrategia
5555 }
5556
5557 /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5558 /// per-cluster distribution-target slice accessor every consumer that
5559 /// walks the Aplicacao's declared cluster-pool keys off — returns the
5560 /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5561 /// `&[String]` slice-view, borrowed from the typed slot's own
5562 /// `Vec<String>` storage (a zero-copy slice-view over the same
5563 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5564 /// through). Non-optional: the empty slice is the load-bearing
5565 /// pre-validation sentinel every downstream consumer of the paired
5566 /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5567 /// off — every strategy in the closed
5568 /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5569 /// requires a non-empty list (`SingleNode` / `Replicated` use the
5570 /// list as hosting / takeover candidates per Erlang/OTP distributed-
5571 /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5572 /// shard pool per Akka cluster-sharding convention, §II.4), so the
5573 /// `.is_empty()` probe is the shared pre-condition every
5574 /// [`AplicacaoSpec::validate_placement`] arm heads on.
5575 ///
5576 /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5577 /// 1123-label per-cluster distribution-target list — the same
5578 /// set-not-multiset shape the sibling `:membros :caixa` /
5579 /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5580 /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5581 /// pins the shape). Every downstream consumer that fans on the list
5582 /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5583 /// pre-flight `.is_empty()` probe that trips
5584 /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5585 /// per-cluster value-shape + duplicate-detection fan-out loop, the
5586 /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5587 /// that materializes the list verbatim onto every
5588 /// programs.yaml entry the substrate operator's per-cluster
5589 /// `placement.clusters | contains .Values.cluster` filter reads,
5590 /// the `feira app graph` per-Aplicacao cluster print line, the
5591 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5592 /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5593 /// placement engine's cluster-topology reader).
5594 ///
5595 /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5596 /// inline at three production sites — the
5597 /// [`AplicacaoSpec::validate_placement`] pre-flight
5598 /// `self.placement.clusters.is_empty()` refusal probe, the same
5599 /// method's per-cluster validate loop's
5600 /// `for c in &self.placement.clusters` traversal head, and the
5601 /// `feira app graph` per-Aplicacao print line's
5602 /// `spec.placement.clusters` `{:?}` formatter argument
5603 /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5604 /// that expressed no compile-time link back to the typed slot. A
5605 /// future extension of the `:placement :clusters` axis to a richer
5606 /// author surface (a per-tenant cluster-pool overlay the operator
5607 /// pins through a future `:placement :clusters-overrides` slot the
5608 /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5609 /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5610 /// the future M5 adaptive-placement engine computes from
5611 /// `:affinity` weights + live cluster-topology probes, a promotion
5612 /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5613 /// partition once the substrate operator's cluster-membership
5614 /// reconciler comes into typed scope) would have had to be threaded
5615 /// through all three open-coded copies in lockstep or one consumer
5616 /// would silently disagree with the peers on which cluster-pool a
5617 /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5618 /// reading the raw slot while the peer per-cluster validate loop
5619 /// read an operator-resolved slot would silently split the paired
5620 /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5621 /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5622 /// input from the pre-flight input, a three-consumer split at the
5623 /// validator and formatter far from the source `caixa.lisp` with
5624 /// no field naming the cluster-pool-drift root cause. Lifting the
5625 /// resolution rule to a typed method on the substrate primitive
5626 /// means every downstream consumer of the Aplicacao's
5627 /// per-`:placement` cluster-pool surface reaches for exactly one
5628 /// typed dispatch — the resolver's accept-set migrates as a unit
5629 /// on any future axis addition.
5630 ///
5631 /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5632 /// slot — sibling to the seed M2
5633 /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5634 /// slice-return accessor on the peer per-`:supervisor` static-
5635 /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5636 /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5637 /// primitive, thin projections at each consumer" discipline. The
5638 /// three peer `Vec`-carry axes still unlifted at the time of this
5639 /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5640 /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5641 /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5642 /// [`crate::UpgradeFromEntry::instructions`]
5643 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5644 /// — inherit this accessor's discipline as future compounding runs
5645 /// migrate their consumers onto the shared slice-return shape.
5646 /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5647 /// type, sibling to the two `Option<&str>`-return
5648 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5649 /// (74ec2d3) accessors and the `Copy`-return
5650 /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5651 /// unlifted per-`:placement` field axis (the `Vec<String>`
5652 /// distribution-target-list carrier) so every downstream
5653 /// per-`:placement` reader now routes through a typed dispatch on
5654 /// the substrate primitive. Named `clusters()` to match the storage
5655 /// field's name verbatim and the tatara-lisp author-surface term
5656 /// (`:clusters`) the field's own docstring already carries; the
5657 /// accessor's identity maps onto the canonical MESH-COMPOSITION
5658 /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5659 /// for. Returns `&[String]` (not `&Vec<String>`) because every
5660 /// downstream consumer of the cluster list treats it as a read-only
5661 /// sequence — the slice-view is the narrowest borrow that supports
5662 /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5663 /// `.len()`) without leaking the backing `Vec`'s
5664 /// grow/push/reserve surface that no consumer of the typed view
5665 /// reaches for (the storage-side `Vec` remains reachable through
5666 /// the `pub clusters` field for the mutation-carrying serde
5667 /// round-trip and per-test fixture-mutation paths).
5668 #[must_use]
5669 pub fn clusters(&self) -> &[String] {
5670 self.clusters.as_slice()
5671 }
5672}
5673
5674impl Default for Placement {
5675 fn default() -> Self {
5676 Self {
5677 // Route the struct-literal `estrategia` default arm through
5678 // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5679 // typed `pub const` rather than the transitively-derived
5680 // [`PlacementStrategy::default`] route — one source of truth
5681 // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5682 // active-active-across-every-named-cluster arm
5683 // (MESH-COMPOSITION §II.2) that both this struct-literal
5684 // altitude and the sibling [`Default for PlacementStrategy`]
5685 // impl already key off through the same substrate primitive.
5686 // Pinned by
5687 // `placement_default_estrategia_routes_through_lifted_default`.
5688 estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5689 clusters: Vec::new(),
5690 affinity: None,
5691 shard_key: None,
5692 }
5693 }
5694}
5695
5696// ── external entry point ─────────────────────────────────────────────
5697
5698/// External entry point — what an outside caller sees. Renders to a
5699/// Gateway / Ingress + a route to the named member Servico.
5700#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5701#[serde(rename_all = "camelCase")]
5702pub struct Entrada {
5703 /// Public hostname (e.g. `"checkout.quero.cloud"`).
5704 pub host: String,
5705
5706 /// Member Servico the gateway routes to. Must be in `:membros`.
5707 pub para: String,
5708
5709 /// Optional path filter — if set, only matching paths route to
5710 /// this Aplicacao (the rest fall through to other route rules).
5711 #[serde(default)]
5712 pub paths: Vec<String>,
5713
5714 /// Default port on the destination Servico (the trigger.service.port).
5715 #[serde(default = "default_port")]
5716 pub port: u16,
5717}
5718
5719impl Entrada {
5720 /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5721 /// every HTTPRoute-aware renderer keys off — returns the author-
5722 /// declared `:entrada :paths` list verbatim when non-empty, and the
5723 /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5724 /// all fallback otherwise (so an Aplicacao author who declares an
5725 /// external `:entrada` block but no per-path rule surface still
5726 /// gets a route whose sole `HTTPPathMatch` matches every incoming
5727 /// request under the paired
5728 /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5729 ///
5730 /// Prior to this lift the "if `:entrada :paths` is empty use the
5731 /// substrate catch-all; else return each declared path verbatim"
5732 /// cascade lived inline at
5733 /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5734 /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5735 /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5736 /// substrate ships today, with no typed method on the substrate
5737 /// primitive that named the rule. A future path-resolution axis
5738 /// addition — a per-cluster `:entrada :default-path` override the
5739 /// operator pins through a future `:placement`-scoped slot, an
5740 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5741 /// admission-webhook floor that materializes the catch-all before
5742 /// the CR lands, a future per-`:entrada :paths` overlay from a
5743 /// per-cluster policy the future `feira app deploy` pipeline
5744 /// consumes — would have to be threaded through every renderer's
5745 /// inline copy of the cascade in lockstep or one consumer would
5746 /// silently disagree with the peers on which path list a given
5747 /// `:entrada` block resolves to. Lifting the rule to a typed
5748 /// method on the substrate primitive means every downstream
5749 /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5750 /// per-cluster overlay resolver, every future per-Aplicacao
5751 /// snapshot renderer) reaches for exactly one typed dispatch —
5752 /// the resolver's accept-set moves as a unit on any future axis
5753 /// addition.
5754 ///
5755 /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5756 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5757 /// per-`:entrada` scalar-value axes — extends the "one typed
5758 /// dispatch on the substrate primitive, thin projections at each
5759 /// consumer" discipline onto the per-`:entrada` path-list
5760 /// resolution axis every HTTPRoute-aware renderer consumes. Same
5761 /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5762 /// sibling `:politicas` primitive — one typed method on the
5763 /// substrate primitive that names the cascade every renderer
5764 /// otherwise re-inlines.
5765 #[must_use]
5766 pub fn resolved_paths(&self) -> Vec<&str> {
5767 // Route the internal cascade-head + per-entry projection reads
5768 // through the lifted [`Self::paths`] slice accessor rather than
5769 // the raw `self.paths` field access — the substrate-primitive
5770 // per-`:entrada` path-list resolver's two internal reads now
5771 // key off the canonical raw-slot surface every downstream
5772 // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5773 // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5774 // entrada summary line's `{:?}` Debug print) routes through, so
5775 // any future rebrand on the typed slot's raw-slot reader lands
5776 // at exactly one place. Same two-consumer coherence discipline
5777 // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5778 // the peer M3 mesh-slot `Vec<String>`-carry axis.
5779 if self.paths().is_empty() {
5780 vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5781 } else {
5782 self.paths().iter().map(String::as_str).collect()
5783 }
5784 }
5785
5786 /// Substrate-canonical per-`:entrada` DNS-hostname singular
5787 /// accessor every Gateway-API `Listener.hostname` reader keys off
5788 /// — returns the author-declared `:entrada :host` byte-string
5789 /// verbatim as a `&str`, borrowed from the typed slot's own
5790 /// [`String`] storage.
5791 ///
5792 /// Named the "singular" half of the DNS-hostname resolver pair on
5793 /// the substrate primitive: the parent-Gateway per-listener
5794 /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5795 /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5796 /// hostname per listener), and this accessor is the typed dispatch
5797 /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5798 /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5799 /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5800 /// per-Aplicacao ingress-hostname surface projects onto.
5801 ///
5802 /// Prior to this lift the `entrada.host.clone()` byte-string was
5803 /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5804 /// per-listener singular `hostname:` axis
5805 /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5806 /// per-HTTPRoute plural `spec.hostnames[]` axis
5807 /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5808 /// consumers read the same `entrada.host` field but the two-site
5809 /// duplication expressed no compile-time contract that the singular
5810 /// Gateway-listener filter and the plural `HTTPRoute` filter list
5811 /// stay in lockstep on future extensions of the `:entrada` slot to
5812 /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5813 /// overlay, a per-cluster SNI fan-out the operator pins through a
5814 /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5815 /// Aplicacao` CR materializer's per-listener virtual-host filter
5816 /// admission-webhook overlay). Any such extension would have to be
5817 /// threaded through every renderer's inline copy of the resolution
5818 /// in lockstep or the Gateway listener's `hostname:` filter would
5819 /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5820 /// — a Gateway-API-conformance divergence whose apply-time symptom
5821 /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5822 /// `NoMatchingParent` — the API server rejects the route because
5823 /// its `hostnames[]` filter doesn't intersect the parent listener's
5824 /// `hostname` filter) is far from the source `caixa.lisp` and never
5825 /// surfaces in the emitted YAML. Lifting the singular and plural
5826 /// resolvers to typed methods on the substrate primitive means
5827 /// every consumer of the Aplicacao's ingress-hostname surface
5828 /// reaches for exactly one typed dispatch, and the pair-invariant
5829 /// `hostnames() == vec![hostname()]` pinned by the sibling
5830 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5831 /// keeps the two axes in lockstep by construction.
5832 ///
5833 /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5834 /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5835 /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5836 /// the substrate primitive, thin projections at each consumer"
5837 /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5838 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5839 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5840 /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5841 /// `:entrada` scalar-value + list-value axes.
5842 #[must_use]
5843 pub fn hostname(&self) -> &str {
5844 self.host.as_str()
5845 }
5846
5847 /// Substrate-canonical per-`:entrada` DNS-hostname plural
5848 /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5849 /// keys off — returns the singleton `[hostname()]` list under
5850 /// today's single-hostname-per-Aplicacao author surface, and the
5851 /// authoritative multi-hostname list under a future
5852 /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5853 ///
5854 /// Plural half of the DNS-hostname resolver pair — see the
5855 /// companion [`Entrada::hostname`] docstring for the two-consumer
5856 /// lift + pair-invariant discipline (`hostnames() ==
5857 /// vec![hostname()]`, pinned load-bearing by the sibling
5858 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5859 /// test).
5860 ///
5861 /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5862 /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5863 /// per-rule path-list axis — same `Vec<&str>` shape, same
5864 /// substrate-primitive-owns-the-resolver discipline extended to
5865 /// the per-HTTPRoute virtual-host filter-list axis.
5866 #[must_use]
5867 pub fn hostnames(&self) -> Vec<&str> {
5868 vec![self.hostname()]
5869 }
5870
5871 /// Substrate-canonical per-`:entrada` destination-Servico scalar
5872 /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5873 /// the author-declared `:entrada :para` byte-string verbatim as a
5874 /// `&str`, borrowed from the typed slot's own [`String`] storage.
5875 ///
5876 /// The `:entrada :para` slot names the single member Servico the
5877 /// external Gateway routes to (validated by
5878 /// [`AplicacaoSpec::validate`] to be a
5879 /// [`Membro::caixa`] the Aplicacao declares — a stray
5880 /// `:para` that doesn't name a member is
5881 /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5882 /// backend-attachment miss at cluster-apply time). Under today's
5883 /// single-destination author surface `:entrada :para` is the ingress
5884 /// apex Servico's canonical identity; under a hypothetical
5885 /// future multi-backend author surface (a `:entrada
5886 /// :split :backends` weighted-fan-out overlay for canary /
5887 /// blue-green traffic-split rollouts, per-path override for
5888 /// path-based per-Servico routing beyond the single-apex model,
5889 /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5890 /// per-CR admission-webhook that promotes the scalar to a
5891 /// weighted list) this accessor is the substrate primitive's typed
5892 /// dispatch every downstream `HTTPRoute`-aware consumer routes
5893 /// through, so the resolution shape migrates as a unit on one
5894 /// caixa-core edit rather than a coordinated rewrite across every
5895 /// renderer's inline field-access.
5896 ///
5897 /// Prior to this lift the `entrada.para` byte-string was accessed
5898 /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
5899 /// `metadata.name` composer's per-destination discriminator arg
5900 /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
5901 /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
5902 /// per-HTTPRoute per-rule `backendRefs[0].name` axis
5903 /// (`entrada.para.clone()`,
5904 /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
5905 /// consumers read the same `entrada.para` field but the two-site
5906 /// duplication expressed no compile-time contract that the HTTPRoute
5907 /// name-discriminator and the per-rule backend name stay in
5908 /// lockstep on future extensions of the `:entrada` slot to a
5909 /// multi-destination author surface. Any such extension would have
5910 /// to be threaded through every renderer's inline copy of the
5911 /// destination projection in lockstep or the HTTPRoute
5912 /// `metadata.name` would silently reference a different destination
5913 /// than its own `backendRefs[]` — an operator-side
5914 /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
5915 /// grep-by-name lookup would land on a route whose `backendRefs[]`
5916 /// silently point at a peer Servico, dropping every external
5917 /// `:entrada` flow at the gateway with the destination-drift root
5918 /// cause invisible in the emitted YAML.
5919 ///
5920 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
5921 /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
5922 /// the per-listener singular / per-HTTPRoute plural filter axes and
5923 /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
5924 /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
5925 /// typed dispatch on the substrate primitive, thin projections at
5926 /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5927 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5928 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5929 /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
5930 /// sibling per-`:entrada` scalar-value + list-value axes — this
5931 /// accessor closes the last unlifted per-`:entrada` scalar axis
5932 /// (the destination-Servico byte-string) so every downstream
5933 /// per-`:entrada` reader now routes through a typed dispatch on
5934 /// the substrate primitive.
5935 #[must_use]
5936 pub fn destination(&self) -> &str {
5937 self.para.as_str()
5938 }
5939
5940 /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
5941 /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
5942 /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
5943 /// reader keys off — returns the author-declared `:entrada :port`
5944 /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
5945 /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
5946 /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
5947 /// [`AplicacaoError::EntradaPortZero`], not a silent
5948 /// admission-webhook rejection at cluster-apply time).
5949 ///
5950 /// The `:entrada :port` slot carries the destination Servico's
5951 /// canonical in-cluster L4 listener port (`trigger.service.port` on
5952 /// the `pleme-computeunit` library chart), and every downstream
5953 /// consumer that reads the port keys off this scalar (the
5954 /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
5955 /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
5956 /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
5957 /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5958 /// CR materializer's per-Aplicacao gateway port resolver).
5959 ///
5960 /// Prior to this lift the `.port` field was accessed inline at two
5961 /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
5962 /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
5963 /// the [`AplicacaoSpec::port_for_destination`] resolver's
5964 /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
5965 /// open-coded field-accesses that expressed no compile-time link
5966 /// back to the typed slot. A future extension of the `:entrada :port`
5967 /// axis to a richer author surface — a per-cluster override the
5968 /// operator pins through a future `:placement :default-port` slot the
5969 /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
5970 /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
5971 /// heterogeneous listener ports, an M4
5972 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5973 /// admission-webhook floor that promotes the scalar to a
5974 /// per-destination map — would have had to be threaded through both
5975 /// open-coded copies in lockstep or the structural-floor validator
5976 /// and the [`AplicacaoSpec::port_for_destination`] resolver would
5977 /// silently disagree on which port a given [`Entrada`] resolves to.
5978 /// Lifting the resolution rule to a typed method on the substrate
5979 /// primitive means every downstream consumer of the Aplicacao's
5980 /// per-`:entrada` L4-port surface reaches for exactly one typed
5981 /// dispatch — the resolver's accept-set migrates as a unit on any
5982 /// future axis addition.
5983 ///
5984 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
5985 /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
5986 /// accessors on the per-`:entrada` scalar-value axis — same "one
5987 /// typed dispatch on the substrate primitive, thin projections at
5988 /// each consumer" discipline extended onto the per-`:entrada`
5989 /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
5990 /// the M3 mesh-slot `Entrada` type — closes the last unlifted
5991 /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
5992 /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
5993 /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
5994 /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
5995 /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
5996 /// storage field's name; the accessor's identity name maps onto the
5997 /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
5998 /// already carries. Declared `pub const fn` (matching the peer M3
5999 /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6000 /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6001 /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6002 /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6003 /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6004 /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6005 /// [`RateLimit`], and the sibling per-`:placement`
6006 /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6007 /// enum scalar axis — every one a `pub const fn`) so every future
6008 /// substrate-side `const`-context consumer of the resolved
6009 /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6010 /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6011 /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6012 /// admission-webhook `const fn` per-CR gateway-port floor over a
6013 /// typed [`Entrada`], any `const fn` composer that fans on the port
6014 /// at compile time) reaches through the same typed dispatch on the
6015 /// substrate primitive at const-eval time as at runtime. Pinned by
6016 /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6017 /// const-eval posture at module scope via `const _:() = …` items so
6018 /// any future accidental downgrade to non-`const` trips at caixa-core
6019 /// build time.
6020 #[must_use]
6021 pub const fn port(&self) -> u16 {
6022 self.port
6023 }
6024
6025 /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6026 /// slice accessor every HTTPRoute-aware renderer keys off when it
6027 /// wants the raw author-declared path-list (not the fallback-
6028 /// applied projection [`Self::resolved_paths`] returns) — returns
6029 /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6030 /// borrowed from the typed slot's own [`Vec<String>`] storage.
6031 ///
6032 /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6033 /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6034 /// (1449891) closes the fallback-applying arm every per-Aplicacao
6035 /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6036 /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6037 /// catch-all; non-empty slot → per-entry verbatim projection); this
6038 /// accessor closes the raw-slot arm every consumer that must see the
6039 /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6040 /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6041 /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6042 /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6043 /// external-gateway summary line's `{:?}` Debug print — which must
6044 /// name the author's declaration, not the substrate's fallback, so
6045 /// an author reading their graph output can grep their caixa.lisp
6046 /// for the exact list they authored) routes through.
6047 ///
6048 /// Prior to this lift the `.paths` field was accessed inline at four
6049 /// production sites: the two internal reads in [`Self::resolved_paths`]
6050 /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6051 /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6052 /// value-shape gate's `for p in &e.paths` traversal head, and the
6053 /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6054 /// Debug print — four open-coded field-accesses that expressed no
6055 /// compile-time link back to the typed slot. A future extension of
6056 /// the `:entrada :paths` axis to a richer author surface — a
6057 /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6058 /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6059 /// spec supports through `matches[].method`), a per-path per-header
6060 /// filter overlay (`matches[].headers[]`), a per-cluster override
6061 /// the operator pins through a future `:placement :path-overlay`
6062 /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6063 /// per-CR admission-webhook that normalized the list at admission
6064 /// time — would have had to be threaded through every open-coded
6065 /// copy in lockstep or the validator's per-entry gate would silently
6066 /// disagree with the renderer's per-entry emit on which list a given
6067 /// `:entrada` block resolves to. Lifting the resolution to a typed
6068 /// method on the substrate primitive means every downstream consumer
6069 /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6070 /// exactly one typed dispatch — the resolver's accept-set migrates
6071 /// as a unit on any future axis addition.
6072 ///
6073 /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6074 /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6075 /// carry axis — same "one typed dispatch on the substrate primitive,
6076 /// thin projections at each consumer" discipline extended onto the
6077 /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6078 /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6079 /// carrier) so every downstream per-`:entrada` reader now routes
6080 /// through a typed dispatch on the substrate primitive. Returns
6081 /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6082 /// treats the list as a read-only sequence — the slice-view is the
6083 /// narrowest borrow that supports every present + roadmapped consumer
6084 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6085 /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6086 /// view reaches for (the storage-side `Vec` remains reachable through
6087 /// the `pub paths` field for the mutation-carrying serde round-trip
6088 /// and per-test fixture-mutation paths).
6089 #[must_use]
6090 pub fn paths(&self) -> &[String] {
6091 self.paths.as_slice()
6092 }
6093}
6094
6095/// Canonical default L4 port every typed Servico exposes on its
6096/// in-cluster K8s Service (the `trigger.service.port` axis the
6097/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6098/// surface defaults to when the author omits the slot, and the
6099/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6100/// `:entrada` block matches the per-`:contratos` destination Servico).
6101/// The single source of truth all three typed-port consumers reach for:
6102///
6103/// - [`Entrada::port`]'s serde default (via the
6104/// [`default_port`] helper this constant feeds); the author surface
6105/// `(:entrada (:host … :para …))` without an explicit `:port` slot
6106/// reads back as a typed [`Entrada`] carrying this exact value;
6107/// - the
6108/// [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6109/// emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6110/// fallback, fired when the typed `:entrada` block doesn't name
6111/// the per-`:contratos` destination Servico — the typed
6112/// `:contratos` graph carries no per-destination port axis (the
6113/// destination port is the destination Servico's
6114/// `lareira-<nome>` chart's `trigger.service.port`, which the
6115/// Aplicacao-level renderer has no visibility into without a
6116/// resolver round-trip), so the renderer falls back to the
6117/// substrate's canonical Servico-port assumption — by
6118/// construction the same value the destination's own
6119/// `pleme-computeunit` chart emits, the same value the
6120/// destination's own typed `:entrada :port` slot defaults to;
6121/// - every future per-Servico renderer the absorption-roadmap
6122/// acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6123/// CR materializer's per-edge port resolver, the future
6124/// per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6125/// emitter's per-route bucket key, the future caixa-otel
6126/// collector-pipeline emitter's per-Servico scrape port).
6127///
6128/// Until this lift landed the value `8080` lived at two production-code
6129/// call-sites: the [`default_port`] helper at
6130/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6131/// and the `.unwrap_or(8080)` literal at
6132/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6133/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6134/// resolver). A future Servico-port rebrand — the substrate moving the
6135/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6136/// gateway grows direct `:80` listeners, to `8443` once the substrate
6137/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6138/// override the operator pins through a future
6139/// `:placement :default-port` slot — without a coordinated edit on
6140/// both sides would silently emit Servicos listening on one port and
6141/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6142/// The CNP's apply-time symptom (the policy is admitted but every L4
6143/// flow on the destination Servico's actual port silently drops because
6144/// it doesn't match the whitelisted port) is far from the rebrand
6145/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6146/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6147/// a shared constant closes the drift footgun structurally — both
6148/// consumers read from the same `u16`, so any rebrand reaches both
6149/// sites by construction.
6150///
6151/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6152/// per-renderer canonical-K8s-axis constant — the namespace string
6153/// and the canonical Servico port both lived as duplicated literals
6154/// across caixa-core / caixa-mesh / caixa-flux before their respective
6155/// lifts. Same "the typed constant lives in one place" discipline the
6156/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6157/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6158/// shared-string axes.
6159///
6160/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6161pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6162
6163/// Structural floor for the typed `:entrada :port` axis — every
6164/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6165/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6166///
6167/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6168/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6169/// interprets as "let the kernel pick a free port at bind time", not a
6170/// well-defined destination the substrate's per-`:entrada` Gateway API
6171/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6172/// carrying `port: 0` degenerates to a nominal-only routing target: the
6173/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6174/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6175/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6176/// at build time rather than at `kubectl apply` time), and the
6177/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6178/// (caixa-mesh/src/lib.rs:2657 through
6179/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6180/// [`Entrada::port`] typed value — silently emits a policy whose
6181/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6182/// actual listener, dropping every L4 flow at the eBPF data plane far
6183/// from the source caixa.lisp with no field naming the port-zero-drift
6184/// root cause.
6185///
6186/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6187/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6188/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6189/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6190/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6191/// well below `u32::MAX` and therefore need explicit typed caps).
6192///
6193/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6194/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6195/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6196/// `:port` inherits through the serde default hook; this constant names
6197/// the accept-set floor every declared port must satisfy. The pair is
6198/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6199/// substrate's default must satisfy its own accept-set floor by
6200/// construction) — a future rebrand that accidentally moved
6201/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6202/// negative-cast typo, a per-cluster override the operator pins through
6203/// a future `:placement :default-port` slot that lands out-of-range)
6204/// would silently invalidate the serde-default emission at every
6205/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6206/// invariant pin
6207/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6208/// closes the drift footgun at caixa-core build time.
6209///
6210/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6211/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6212/// has exactly one source of truth — the future M4
6213/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6214/// gateway resolver, the future per-Servico
6215/// `computeunit.trigger.service.port` renderer's per-CR port-value
6216/// validator, and every downstream test-fixture navigator asserting
6217/// the accept-set floor all read from one place. Same shape every
6218/// other typed bracket-floor / bracket-ceiling in this crate carries
6219/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6220/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6221/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6222/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6223/// [`POLICY_RATE_LIMIT_MAX`]).
6224pub const SERVICO_PORT_MIN: u16 = 1;
6225
6226const fn default_port() -> u16 {
6227 DEFAULT_SERVICO_PORT
6228}
6229
6230// ── the typed view ───────────────────────────────────────────────────
6231
6232/// Typed composition view of the flat Aplicacao slots on
6233/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6234/// validation + downstream renderer consumption.
6235#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6236#[serde(rename_all = "camelCase")]
6237pub struct AplicacaoSpec {
6238 pub membros: Vec<Membro>,
6239 pub contratos: Vec<WitContract>,
6240 pub politicas: MeshPolicy,
6241 pub placement: Placement,
6242 pub entrada: Option<Entrada>,
6243}
6244
6245impl AplicacaoSpec {
6246 /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6247 /// per-Aplicacao member-list slice-return accessor every
6248 /// per-Aplicacao member-list reader keys off — returns the author-
6249 /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6250 /// over the same backing buffer the raw `self.membros.as_slice()`
6251 /// field access borrows from.
6252 ///
6253 /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6254 /// member list — the load-bearing identity of the application graph
6255 /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6256 /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6257 /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6258 /// accessor) with a `:versao` semver-requirement string (through
6259 /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6260 /// and every downstream consumer that fans on the member-set keys
6261 /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6262 /// membership-lookup `HashSet<&str>` seed's collect input, the
6263 /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6264 /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6265 /// per-member DNS-1123 / semver-requirement / duplicate-detection
6266 /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6267 /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6268 /// programs.yaml per-`:membros` fan-out emitter's per-entry
6269 /// mapping-composition loop, the `feira app graph` per-Aplicacao
6270 /// member-count print line and per-member tree traversal,
6271 /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6272 /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6273 /// placement engine's per-member weight-topology reader).
6274 ///
6275 /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6276 /// inline at six production sites — the [`AplicacaoSpec::validate`]
6277 /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
6278 /// [`AplicacaoSpec::validate_membros`]'s pre-flight
6279 /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
6280 /// probe, the same method's per-member `for m in &self.membros`
6281 /// validate-loop traversal head, the
6282 /// [`AplicacaoSpec::detect_sync_cycles`]'s
6283 /// `for m in &self.membros` adjacency-list seed, the
6284 /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6285 /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6286 /// paired with the peer `for m in &spec.membros` per-entry fan-out
6287 /// loop, and the `feira app graph` per-Aplicacao print line's
6288 /// `spec.membros.len()` count formatter argument paired with the
6289 /// peer `for m in &spec.membros` per-member tree traversal — six
6290 /// open-coded field-accesses that expressed no compile-time link
6291 /// back to the typed slot. A future extension of the `:membros`
6292 /// axis to a richer author surface (a per-cluster member-set
6293 /// overlay the operator pins through a future
6294 /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6295 /// roadmap acknowledges, a per-tenant member-alias table the M4
6296 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6297 /// CR at admission time, a per-Aplicacao dynamic member-set
6298 /// derivation the future adaptive-placement engine computes from
6299 /// weighted membership topology, a promotion of the plain
6300 /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6301 /// Orleans-style virtual-actor dynamic-membership comes into typed
6302 /// scope) would have had to be threaded through all six open-coded
6303 /// copies in lockstep or one consumer would silently disagree with
6304 /// the peers on which member-set a given Aplicacao resolves to —
6305 /// the `HashSet<&str>` name-set seed reading the raw slot while
6306 /// the peer `.is_empty()` refusal probe read an operator-resolved
6307 /// slot would silently split the `:contratos` membership-lookup
6308 /// input from the pre-flight-refusal input, a six-consumer split
6309 /// at the validator + programs.yaml emitter + graph printer far
6310 /// from the source `caixa.lisp` with no field naming the member-
6311 /// set-drift root cause. Lifting the resolution rule to a typed
6312 /// method on the substrate primitive means every downstream
6313 /// consumer of the Aplicacao's per-`:membros` member-list surface
6314 /// reaches for exactly one typed dispatch — the resolver's accept-
6315 /// set migrates as a unit on any future axis addition.
6316 ///
6317 /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6318 /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6319 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6320 /// static-child-list `Vec`-carry axis, and to the M3
6321 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6322 /// on the peer per-`:placement` distribution-target-list `Vec`-
6323 /// carry axis. Same "one typed dispatch on the substrate primitive,
6324 /// thin projections at each consumer" discipline. The two peer
6325 /// `Vec`-carry axes still unlifted at the time of this lift —
6326 /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6327 /// WIT-typed edge list) and
6328 /// [`crate::UpgradeFromEntry::instructions`]
6329 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6330 /// — inherit this accessor's discipline as future compounding runs
6331 /// migrate their consumers onto the shared slice-return shape.
6332 /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6333 /// `AplicacaoSpec` type itself, extending the discipline beyond
6334 /// the inner per-slot types ([`crate::Placement`],
6335 /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6336 /// view every renderer consumes. Named `membros()` to match the
6337 /// storage field's name verbatim and the tatara-lisp author-
6338 /// surface term (`:membros`) the field's own docstring already
6339 /// carries; the accessor's identity maps onto the canonical
6340 /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6341 /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6342 /// every downstream consumer of the member list treats it as a
6343 /// read-only sequence — the slice-view is the narrowest borrow
6344 /// that supports every present + roadmapped consumer
6345 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6346 /// backing `Vec`'s grow/push/reserve surface that no consumer of
6347 /// the typed view reaches for (the storage-side `Vec` remains
6348 /// reachable through the `pub membros` field for the mutation-
6349 /// carrying serde round-trip and per-test fixture-mutation paths).
6350 #[must_use]
6351 pub fn membros(&self) -> &[Membro] {
6352 self.membros.as_slice()
6353 }
6354
6355 /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6356 /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6357 /// accessor every per-Aplicacao contract-list reader keys off —
6358 /// returns the author-declared `:contratos` list verbatim as a
6359 /// `&[WitContract]` slice-view over the same backing buffer the raw
6360 /// `self.contratos.as_slice()` field access borrows from.
6361 ///
6362 /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6363 /// WIT-typed edge list — the load-bearing set of directed edges
6364 /// on the application graph whose nodes are the `:membros` entries
6365 /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6366 /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6367 /// six-tuple is the edge identity every downstream duplicate gate
6368 /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6369 /// Servico caller name + a `:para` destination-Servico callee name
6370 /// (through the lifted [`WitContract::source`] +
6371 /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6372 /// caller/callee-Servico axis) with a `:wit` world-reference
6373 /// (through the lifted [`WitContract::world_ref`] (0804823)
6374 /// accessor) and the target-shape-appropriate payload-carrier
6375 /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6376 /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6377 /// (ed22b66) accessor on the per-target-shape payload-carrier
6378 /// axis). Every downstream consumer that fans on the edge-set
6379 /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6380 /// name-set / self-edge / target-shape / dedup fan-out loop, the
6381 /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6382 /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6383 /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6384 /// grouping loop, the `feira app graph` per-Aplicacao contract-
6385 /// count print line and per-contract tree traversal, every future
6386 /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6387 /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6388 /// mesh-policy overlay resolver's per-contract typed-edge weight
6389 /// reader).
6390 ///
6391 /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6392 /// accessed inline at four production sites — the
6393 /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6394 /// per-edge validate-loop traversal head (which drives every
6395 /// per-edge name-set membership lookup, self-edge check,
6396 /// target-shape dispatch, and dedup `HashSet` insert), the
6397 /// [`AplicacaoSpec::detect_sync_cycles`]'s
6398 /// `for c in &self.contratos` adjacency-list seed head (which
6399 /// drives every per-edge sync-vs-pub-sub partition and per-edge
6400 /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6401 /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6402 /// `BTreeMap` grouping loop head (which drives every per-CNP
6403 /// fan-out emit), and the `feira app graph` per-Aplicacao print
6404 /// line's `spec.contratos.len()` count formatter argument paired
6405 /// with the peer `for c in &spec.contratos` per-contract tree
6406 /// traversal — four open-coded field-accesses that expressed no
6407 /// compile-time link back to the typed slot. A future extension
6408 /// of the `:contratos` axis to a richer author surface (a
6409 /// per-cluster contract overlay the operator pins through a
6410 /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6411 /// federation roadmap acknowledges, a per-tenant edge-policy
6412 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6413 /// materializer resolves per-CR at admission time, a per-edge
6414 /// weight scalar the future adaptive-placement engine reads to
6415 /// bias sync-subgraph routing, a promotion of the plain
6416 /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6417 /// once virtual-actor-style dynamic-edge composition comes into
6418 /// typed scope) would have had to be threaded through all four
6419 /// open-coded copies in lockstep or one consumer would silently
6420 /// disagree with the peers on which edge-set a given Aplicacao
6421 /// resolves to — the validator's per-edge dedup `HashSet` seed
6422 /// reading the raw slot while the peer sync-cycle adjacency-list
6423 /// seed read an operator-resolved slot would silently split the
6424 /// build-time edge-set gate from the runtime deadlock-detection
6425 /// gate, a four-consumer split at the validator, the cycle
6426 /// detector, the CNP emitter, and the graph printer far from
6427 /// the source `caixa.lisp` with no field naming the edge-set-
6428 /// drift root cause. Lifting the resolution rule to a typed method on the
6429 /// substrate primitive means every downstream consumer of the
6430 /// Aplicacao's per-`:contratos` edge-list surface reaches for
6431 /// exactly one typed dispatch — the resolver's accept-set
6432 /// migrates as a unit on any future axis addition.
6433 ///
6434 /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6435 /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6436 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6437 /// static-child-list `Vec`-carry axis, to the M3
6438 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6439 /// on the peer per-`:placement` distribution-target-list `Vec`-
6440 /// carry axis, and to the immediately-adjacent sibling M3
6441 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6442 /// the peer per-`:membros` node-list `Vec`-carry axis — the
6443 /// per-`:contratos` edge-list accessor is the natural pair of
6444 /// the per-`:membros` node-list accessor (graph edges over graph
6445 /// nodes; every graph-shaped consumer reads both). Same "one
6446 /// typed dispatch on the substrate primitive, thin projections
6447 /// at each consumer" discipline. The last remaining `Vec`-carry
6448 /// axis still unlifted at the time of this lift —
6449 /// [`crate::UpgradeFromEntry::instructions`]
6450 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6451 /// list) — inherits this accessor's discipline as future
6452 /// compounding runs migrate its consumers onto the shared slice-
6453 /// return shape. Second `&[T]`-return accessor on the top-level
6454 /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6455 /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6456 /// `:contratos` are the two `Vec` fields on the outer typed
6457 /// composition view — `:politicas`, `:placement`, `:entrada` are
6458 /// scalar/option-shaped and already route through their per-slot
6459 /// accessor families). Named `contratos()` to match the storage
6460 /// field's name verbatim and the tatara-lisp author-surface term
6461 /// (`:contratos`) the field's own docstring already carries; the
6462 /// accessor's identity maps onto the canonical MESH-COMPOSITION
6463 /// §III.1 vocabulary the slot's docstring already reaches for.
6464 /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6465 /// every downstream consumer of the contract list treats it as a
6466 /// read-only sequence — the slice-view is the narrowest borrow
6467 /// that supports every present + roadmapped consumer
6468 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6469 /// backing `Vec`'s grow/push/reserve surface that no consumer of
6470 /// the typed view reaches for (the storage-side `Vec` remains
6471 /// reachable through the `pub contratos` field for the mutation-
6472 /// carrying serde round-trip and per-test fixture-mutation paths).
6473 #[must_use]
6474 pub fn contratos(&self) -> &[WitContract] {
6475 self.contratos.as_slice()
6476 }
6477
6478 /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6479 /// per-Aplicacao mesh-policy composite-reference accessor every
6480 /// per-Aplicacao policy-block reader keys off — returns the author-
6481 /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6482 /// reference over the same backing storage the raw `&self.politicas`
6483 /// field access borrows from.
6484 ///
6485 /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6486 /// mesh-policy composite — the load-bearing container of every
6487 /// mesh-level operational-policy axis every downstream mesh-artifact
6488 /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6489 /// mesh-policy overlay is the single typed surface a
6490 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6491 /// from). Every per-`:politicas` axis threads through a lifted
6492 /// per-slot accessor on the [`MeshPolicy`] type: the
6493 /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6494 /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6495 /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6496 /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6497 /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6498 /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6499 /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6500 /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6501 /// accessor. Every downstream consumer that reaches for a policy
6502 /// axis first passes through this outer accessor onto the composite
6503 /// and then dispatches onto the per-axis accessor — the two-level
6504 /// dispatch means every per-`:politicas` reader now routes through
6505 /// a typed dispatch on the substrate primitive at both altitudes.
6506 ///
6507 /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6508 /// accessed inline at four production sites — the
6509 /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6510 /// &self.politicas;` traversal seed (which drives every per-axis
6511 /// zero-floor + upper-cap + canonical-form bracket dispatch through
6512 /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6513 /// `p.rate_limit()` on the axis-level lifted accessors), the
6514 /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6515 /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6516 /// chain (which drives every per-`(:de, :para)` CNP
6517 /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6518 /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6519 /// timeout + retry overlay emitter's paired
6520 /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6521 /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6522 /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6523 /// open-coded outer-field accesses that expressed no compile-time
6524 /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6525 /// future extension of the `:politicas` outer axis to a richer
6526 /// author surface (a per-cluster policy overlay the operator pins
6527 /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6528 /// §V federation roadmap acknowledges, a per-tenant policy-alias
6529 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6530 /// resolves per-CR at admission time, a per-Aplicacao dynamic
6531 /// policy-composite derivation the future adaptive-placement engine
6532 /// computes from a per-cluster load-topology reader, a promotion of
6533 /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6534 /// partition once virtual-actor-style dynamic-mesh-policy
6535 /// composition comes into typed scope) would have had to be threaded
6536 /// through all four open-coded copies in lockstep or one consumer
6537 /// would silently disagree with the peers on which mesh-policy
6538 /// composite a given Aplicacao resolves to — the validator's
6539 /// per-axis bracket-dispatch seed reading the raw slot while the
6540 /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6541 /// would silently split the build-time policy-shape gate from the
6542 /// runtime CNP-emission gate, a four-consumer split at the
6543 /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6544 /// the source `caixa.lisp` with no field naming the policy-drift
6545 /// root cause. Lifting the resolution rule to a typed method on the
6546 /// substrate primitive means every downstream consumer of the
6547 /// Aplicacao's per-`:politicas` mesh-policy composite surface
6548 /// reaches for exactly one typed dispatch — the resolver's accept-
6549 /// set migrates as a unit on any future axis addition.
6550 ///
6551 /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6552 /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6553 /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6554 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6555 /// close the two `Vec`-carry axes on the outer typed composition
6556 /// view; the outer `:politicas` composite-reference axis is the
6557 /// natural pair to the paired outer `Vec`-carry accessors on the
6558 /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6559 /// emitter reads all four axes as one unit (graph nodes + graph
6560 /// edges + mesh policy + placement pool). Peer to the same
6561 /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6562 /// slot: every M2 `SupervisorSpec`-scoped composite reader
6563 /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6564 /// `restart_window`, `children`) already routes through the M2
6565 /// `SupervisorSpec` accessor family — this lift extends the same
6566 /// "one typed dispatch on the substrate primitive at the outer
6567 /// composition altitude" discipline to the M3 mesh-slot
6568 /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6569 /// remaining peer outer-composite axes still unlifted at the time
6570 /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6571 /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6572 /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6573 /// inherit this accessor's discipline as future compounding runs
6574 /// migrate their consumers onto the shared reference-return shape.
6575 /// Named `politicas()` to match the storage field's name verbatim
6576 /// and the tatara-lisp author-surface term (`:politicas`) the
6577 /// field's own docstring already carries; the accessor's identity
6578 /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6579 /// slot's docstring already reaches for. Returns `&MeshPolicy`
6580 /// (not the owning composite by copy or clone) because every
6581 /// downstream consumer of the mesh-policy composite treats it as a
6582 /// read-only per-axis dispatch source — the reference-view is the
6583 /// narrowest borrow that supports every present + roadmapped
6584 /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6585 /// emptiness probe) without cloning the composite through every
6586 /// consumer's fast path.
6587 #[must_use]
6588 pub fn politicas(&self) -> &MeshPolicy {
6589 &self.politicas
6590 }
6591
6592 /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6593 /// per-Aplicacao distribution-composite composite-reference accessor
6594 /// every per-Aplicacao placement-block reader keys off — returns the
6595 /// author-declared `:placement` composite verbatim as a `&Placement`
6596 /// reference over the same backing storage the raw `&self.placement`
6597 /// field access borrows from.
6598 ///
6599 /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6600 /// distribution composite — the load-bearing container of every
6601 /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6602 /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6603 /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6604 /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6605 /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6606 /// `:affinity` hint). Every per-`:placement` axis threads through a
6607 /// lifted per-slot accessor on the [`Placement`] type: the
6608 /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6609 /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6610 /// per-cluster distribution-target slice-return accessor, the
6611 /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6612 /// optional-scalar accessor, and the [`Placement::shard_key`]
6613 /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6614 /// downstream consumer that reaches for a placement axis first passes
6615 /// through this outer accessor onto the composite and then dispatches
6616 /// onto the per-axis accessor — the two-level dispatch means every
6617 /// per-`:placement` reader now routes through a typed dispatch on the
6618 /// substrate primitive at both altitudes.
6619 ///
6620 /// Prior to this lift the `.placement` `Placement` composite was
6621 /// accessed inline at three production sites — the
6622 /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6623 /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6624 /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6625 /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6626 /// cluster `.clusters()` validate-loop traversal head, the per-
6627 /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6628 /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6629 /// paired with the shape-gate cascade's `.shard_key()` /
6630 /// `.estrategia()` diagnostic-carry pair), the
6631 /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6632 /// per-entry placement-block emitter's outer
6633 /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6634 /// seed (which fans onto every per-cluster `programs[]` entry as a
6635 /// self-describing distribution overlay the aggregator filters by),
6636 /// and the `feira app graph` per-Aplicacao print line's paired
6637 /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6638 /// then-inner-accessor chains (which drive the human-readable
6639 /// distribution summary of the typed Aplicacao view) — three open-
6640 /// coded outer-field accesses that expressed no compile-time link
6641 /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6642 /// extension of the `:placement` outer axis to a richer author surface
6643 /// (a per-cluster placement overlay the operator pins through a
6644 /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6645 /// federation roadmap acknowledges, a per-tenant placement-alias
6646 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6647 /// resolves per-CR at admission time, a per-Aplicacao dynamic
6648 /// placement-composite derivation the future M5 adaptive-placement
6649 /// engine computes from a per-cluster load-topology reader, a
6650 /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6651 /// partition once Orleans-style virtual-actor dynamic-placement comes
6652 /// into typed scope) would have had to be threaded through all three
6653 /// open-coded copies in lockstep or one consumer would silently
6654 /// disagree with the peers on which placement composite a given
6655 /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6656 /// seed reading the raw slot while the peer
6657 /// `programs_for_aplicacao` emitter read an operator-resolved slot
6658 /// would silently split the build-time distribution-shape gate from
6659 /// the runtime programs.yaml distribution-annotation gate, a three-
6660 /// consumer split at the validator, the programs.yaml emitter, and
6661 /// the `feira app graph` printer far from the source `caixa.lisp`
6662 /// with no field naming the placement-drift root cause. Lifting the
6663 /// resolution rule to a typed method on the substrate primitive
6664 /// means every downstream consumer of the Aplicacao's per-
6665 /// `:placement` distribution composite surface reaches for exactly
6666 /// one typed dispatch — the resolver's accept-set migrates as a unit
6667 /// on any future axis addition.
6668 ///
6669 /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6670 /// `AplicacaoSpec` type itself — sibling to the seed
6671 /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6672 /// composite-reference accessor on the peer per-`:politicas` outer-
6673 /// composite axis, and to the paired slice-return accessors
6674 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6675 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6676 /// the two `Vec`-carry axes on the outer typed composition view; the
6677 /// outer `:placement` composite-reference axis is the natural pair
6678 /// to the peer `:politicas` composite-reference axis on the two
6679 /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6680 /// how-to-run policy overlay, `:placement` carries the where-to-run
6681 /// distribution composite — every whole-Aplicacao mesh-artifact
6682 /// emitter reads both as one unit). Same "one typed dispatch on the
6683 /// substrate primitive, thin projections at each consumer"
6684 /// discipline the peer per-`:politicas` composite-reference axis
6685 /// already routes through. The one remaining outer-composite axis
6686 /// still unlifted at the time of this lift —
6687 /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6688 /// external-gateway composite) — inherits this accessor's discipline
6689 /// as the next compounding run migrates its consumers onto the shared
6690 /// reference-return shape, closing the outer-composite altitude on
6691 /// every M3 mesh-slot axis. Named `placement()` to match the storage
6692 /// field's name verbatim and the tatara-lisp author-surface term
6693 /// (`:placement`) the field's own docstring already carries; the
6694 /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6695 /// vocabulary the slot's docstring already reaches for. Returns
6696 /// `&Placement` (not the owning composite by copy or clone) because
6697 /// every downstream consumer of the placement composite treats it as
6698 /// a read-only per-axis dispatch source — the reference-view is the
6699 /// narrowest borrow that supports every present + roadmapped consumer
6700 /// (per-axis accessor dispatch, serde composite-serialization) without
6701 /// cloning the composite through every consumer's fast path.
6702 #[must_use]
6703 pub fn placement(&self) -> &Placement {
6704 &self.placement
6705 }
6706
6707 /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6708 /// per-Aplicacao external-gateway composite optional-composite-
6709 /// reference accessor every per-Aplicacao gateway-block reader
6710 /// keys off — returns the author-declared `:entrada` composite
6711 /// verbatim as an `Option<&Entrada>` reference over the same
6712 /// backing storage the raw `self.entrada.as_ref()` field access
6713 /// borrows from, with `None` naming the internal-only mesh shape
6714 /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6715 /// gateway_routes emitter treats as "emit nothing" and the peer
6716 /// `feira app graph` printer treats as "internal-only mesh").
6717 ///
6718 /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6719 /// external-gateway composite — the load-bearing container of
6720 /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6721 /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6722 /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6723 /// hostname axis, §III.4 for the `:para` destination-Servico
6724 /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6725 /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6726 /// axis threads through a lifted per-slot accessor on the
6727 /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6728 /// Gateway-API `Listener.hostname` scalar accessor, the paired
6729 /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6730 /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6731 /// backendRefs destination-Servico scalar accessor, the
6732 /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6733 /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6734 /// scalar accessor. Every downstream consumer that reaches for
6735 /// an entrada axis first passes through this outer accessor onto
6736 /// the composite and then dispatches onto the per-axis accessor
6737 /// — the two-level dispatch means every per-`:entrada` reader
6738 /// now routes through a typed dispatch on the substrate primitive
6739 /// at both altitudes.
6740 ///
6741 /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6742 /// was accessed inline at four production sites — the
6743 /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6744 /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6745 /// (which drives every per-axis refusal on the composite: the
6746 /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6747 /// `EntradaMemberMissing` membership lookup against the
6748 /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6749 /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6750 /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6751 /// per-path shape gate on each entry of `e.paths`), the
6752 /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6753 /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6754 /// composite-projection seed (which drives the destination-
6755 /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6756 /// backendRefs port emitter fans on), the
6757 /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6758 /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6759 /// early-return seed (which drives the "no `:entrada` ⇒ no
6760 /// external artifacts" partition on the whole-Aplicacao Gateway-
6761 /// API emitter's fan-out), and the `feira app graph` per-
6762 /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6763 /// external-gateway summary emitter (which drives the human-
6764 /// readable `entrada: host → para (paths=…, port=…)` /
6765 /// `entrada: (internal-only mesh)` partition on the typed
6766 /// Aplicacao view) — four open-coded outer-field accesses that
6767 /// expressed no compile-time link back to the typed slot at the
6768 /// [`AplicacaoSpec`] altitude. A future extension of the
6769 /// `:entrada` outer axis to a richer author surface (a
6770 /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6771 /// at admission time so an Aplicacao can expose a public-web +
6772 /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6773 /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6774 /// operator can pin a per-cluster hostname override without
6775 /// re-authoring the `caixa.lisp`, a promotion of the plain
6776 /// `Option<Entrada>` to a richer `{single, multi}` partition once
6777 /// the multi-`:entrada` roadmap lands) would have had to be
6778 /// threaded through all four open-coded copies in lockstep or one
6779 /// consumer would silently disagree with the peers on which
6780 /// entrada composite a given Aplicacao resolves to — the
6781 /// validator's per-axis bracket-dispatch seed reading the raw
6782 /// slot while the peer `gateway_routes` emitter read an
6783 /// operator-resolved slot would silently split the build-time
6784 /// gateway-shape gate from the runtime Gateway + HTTPRoute
6785 /// emission gate, a four-consumer split at the validator, the
6786 /// `port_for_destination` L4-port resolver, the `gateway_routes`
6787 /// emitter, and the `feira app graph` printer far from the
6788 /// source `caixa.lisp` with no field naming the entrada-drift
6789 /// root cause. Lifting the resolution rule to a typed method on
6790 /// the substrate primitive means every downstream consumer of
6791 /// the Aplicacao's per-`:entrada` external-gateway composite
6792 /// surface reaches for exactly one typed dispatch — the
6793 /// resolver's accept-set migrates as a unit on any future axis
6794 /// addition.
6795 ///
6796 /// Third and final `&Composite`-return accessor on the top-level
6797 /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6798 /// unlifted outer-composite axis on the outer typed composition
6799 /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6800 /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6801 /// accessor on the per-`:politicas` outer-composite axis and to
6802 /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6803 /// distribution-composite composite-reference accessor on the
6804 /// per-`:placement` outer-composite axis; extends the outer-
6805 /// composite reference-return discipline the two peers already
6806 /// route through onto the last unlifted per-`AplicacaoSpec`
6807 /// outer-composite axis. The `:entrada` outer-composite axis is
6808 /// the natural pair to the two peer outer-composite axes on the
6809 /// three operationally-symmetric M3 mesh-slot outer composites
6810 /// (`:politicas` carries the how-to-run policy overlay,
6811 /// `:placement` carries the where-to-run distribution composite,
6812 /// `:entrada` carries the who-can-reach-it external-gateway
6813 /// composite — every whole-Aplicacao mesh-artifact emitter reads
6814 /// all three as one unit). Same "one typed dispatch on the
6815 /// substrate primitive, thin projections at each consumer"
6816 /// discipline the peer outer-composite axes already route through.
6817 /// Named `entrada()` to match the storage field's name verbatim
6818 /// and the tatara-lisp author-surface term (`:entrada`) the
6819 /// field's own docstring already carries; the accessor's
6820 /// identity maps onto the canonical MESH-COMPOSITION §III.4
6821 /// vocabulary the slot's docstring already reaches for. Returns
6822 /// `Option<&Entrada>` (not the owning composite by copy or
6823 /// clone) because every downstream consumer of the entrada
6824 /// composite treats it as a read-only per-axis dispatch source
6825 /// — the reference-view is the narrowest borrow that supports
6826 /// every present + roadmapped consumer (per-axis accessor
6827 /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
6828 /// port-fallback projection, early-return partition on the
6829 /// `None` arm) without cloning the composite through every
6830 /// consumer's fast path. The `Option` half of the return-type
6831 /// preserves the load-bearing "author-omitted `:entrada` ⇒
6832 /// internal-only mesh" partition (not a default composite the
6833 /// downstream must reject on emptiness) — the accessor projects
6834 /// the raw `Option<Entrada>` slot's presence bit through the
6835 /// reference-return unchanged.
6836 #[must_use]
6837 pub fn entrada(&self) -> Option<&Entrada> {
6838 self.entrada.as_ref()
6839 }
6840
6841 /// Validate the typed shape:
6842 /// - `:membros` is non-empty; every entry has a non-empty `:caixa`
6843 /// and a non-empty `:versao`; no two entries share the same
6844 /// `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6845 /// not a multiset)
6846 /// - every `:contratos` :de + :para must be in `:membros`
6847 /// - no `:contratos` edge is a self-edge (`:de == :para`) — a
6848 /// contract is an inter-Servico edge, so a Servico contracting
6849 /// with itself is a build error under every WIT shape
6850 /// (MESH-COMPOSITION §III.1)
6851 /// - no two `:contratos` entries agree on
6852 /// `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6853 /// edges are a set, not a multiset (peer of the `:membros` /
6854 /// `:placement :clusters` / `:entrada :paths` duplicate gates)
6855 /// - `:entrada :para` must be in `:membros`
6856 /// - `:placement Sharded` must declare `:shard-key` (non-empty);
6857 /// `:placement Replicated`/`SingleNode` must NOT declare
6858 /// `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6859 /// consumes it (MESH-COMPOSITION §II.4), and the typed partition
6860 /// between strategy and shard-key is symmetric: every validated
6861 /// `Placement` has `shard_key.is_some()` iff `estrategia ==
6862 /// Sharded`
6863 /// - every `:placement` strategy must declare ≥1 `:clusters` entry —
6864 /// `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6865 /// the shard pool (MESH-COMPOSITION §III.1)
6866 /// - every `:clusters` entry is non-empty and unique
6867 /// - `:placement :affinity`, when set, is non-empty
6868 /// - the synchronous-`:contratos` subgraph is acyclic
6869 /// (MESH-COMPOSITION §III.3)
6870 /// - every declared `:politicas` value is operationally meaningful
6871 /// (zero timeout, zero retries, zero breaker thresholds, zero rate
6872 /// limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6873 /// omit the field instead to express "no policy on this axis")
6874 pub fn validate(&self) -> Result<(), AplicacaoError> {
6875 self.validate_membros()?;
6876 let names: std::collections::HashSet<&str> =
6877 self.membros().iter().map(Membro::nome).collect();
6878
6879 // Identity key for the typed-edge duplicate gate below: every
6880 // field that distinguishes one contract from another. Two
6881 // entries that agree on all six are *the same edge declared
6882 // twice*, the typed-graph analogue of duplicate `:membros` /
6883 // `:placement :clusters` / `:entrada :paths` entries (which
6884 // are already build errors at this layer). Rejecting it at the
6885 // validate gate closes a renderer-side footgun: caixa-mesh's
6886 // `cilium_network_policies` keys each emitted policy by
6887 // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6888 // (de, para) and identical payload would land as two K8s
6889 // objects with colliding `metadata.name`, rejected at apply
6890 // time far from the source caixa.lisp.
6891 let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
6892 std::collections::HashSet::new();
6893 for c in self.contratos() {
6894 // Per-axis value-shape gate on every `:contratos` name
6895 // reference, before any graph-membership lookup. Empty +
6896 // DNS-1123-malformed `:de`/`:para` values silently fell
6897 // through to `ContratoMemberMissing` at the lookup arm
6898 // because every `:membros :caixa` is shape-validated
6899 // (3f9d7a0), so the `names` set structurally cannot contain
6900 // an empty / malformed string and the membership-lookup
6901 // diagnostic always misframed the root cause as
6902 // "this caixa is not in `:membros`". The shape gate runs
6903 // ahead of the lookup so structurally-impossible-to-match
6904 // inputs route through the narrower self-locating
6905 // diagnostic, preserving the legitimate "well-shaped
6906 // phantom reference" arm. `:de` runs before `:para` per
6907 // the canonical edge-direction order the existing
6908 // membership lookup, self-edge check, target dispatch,
6909 // and diagnostic strings already use.
6910 // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
6911 // + the paired [`AplicacaoError::ContratoMemberMissing`]
6912 // diagnostic's `caixa:` carrier through the lifted
6913 // [`WitContract::source`] / [`WitContract::destination`]
6914 // scalar accessors rather than the raw `&c.de` / `&c.para`
6915 // `&String`-borrow arg site + the raw `c.de.clone()` /
6916 // `c.para.clone()` field-access `String`-carry sites — the
6917 // last unlifted per-`:contratos` raw-field-access sites in
6918 // the M3 mesh-slot validator's per-edge per-arm shape-gate
6919 // arg + phantom-name diagnostic wrap-envelope emit surface.
6920 // `c.source()` is byte-identical to `&c.de` (pinned by the
6921 // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
6922 // + `wit_contract_source_borrows_from_de_storage` accessor
6923 // tests) and `c.destination()` is byte-identical to `&c.para`
6924 // (pinned by the sibling
6925 // `wit_contract_destination_returns_para_byte_equal_across_permutations`
6926 // + `wit_contract_destination_borrows_from_para_storage`
6927 // accessor tests) — so a future rebrand of either underlying
6928 // storage flows through the accessor's one body without a
6929 // coordinated per-consumer rewrite across the M3 mesh
6930 // validator's per-edge shape-gate + phantom-name refusal
6931 // arms. Peer of the sibling per-`:contratos` self-loop
6932 // arm's `.source().to_string()` / `.world_ref().to_string()`
6933 // `String`-carry sites the earlier convergence lifted onto
6934 // the same accessor pair.
6935 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
6936 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
6937 if !names.contains(c.source()) {
6938 return Err(AplicacaoError::ContratoMemberMissing {
6939 caixa: c.source().to_string(),
6940 });
6941 }
6942 if !names.contains(c.destination()) {
6943 return Err(AplicacaoError::ContratoMemberMissing {
6944 caixa: c.destination().to_string(),
6945 });
6946 }
6947 // A `:contratos` entry is an *inter*-Servico contract
6948 // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
6949 // typed edge between two distinct graph nodes. An edge whose
6950 // `:de` equals its `:para` is a Servico contracting with
6951 // itself — a degenerate edge under every WIT shape. The
6952 // synchronous shapes were caught only incidentally, and with
6953 // a misleading diagnostic: `detect_sync_cycles` reported
6954 // `cart → cart` as a `ContratoCycle` whose path is
6955 // `["cart", "cart"]` — framing a self-edge as a multi-node
6956 // deadlock. The pub-sub shape slipped through entirely
6957 // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
6958 // `nats:pub-sub` edge from a member to itself silently
6959 // validated, then rendered a `CiliumNetworkPolicy` whose
6960 // endpointSelector and fromEndpoints both name the same
6961 // program — a self-allow rule that is a no-op, since
6962 // intra-pod traffic never traverses the mesh). A self-edge's
6963 // runtime meaning is an in-process call, which doesn't go
6964 // through the mesh at all, so no `:contratos` edge can carry
6965 // it. Firing the gate before the `:wit`/`target()` shape
6966 // checks means the structural "this edge can't exist" error
6967 // precedes the narrower payload-shape diagnostics, and shape-
6968 // agnostically covers all four `WitTarget` arms (HTTP / Store
6969 // / Capability / PubSub) at one point — closing the pub-sub
6970 // hole and replacing the misleading cycle diagnostic in one
6971 // gate. Peer of the duplicate-`:contratos` / duplicate-
6972 // `:membros` set gates: both reject a structurally
6973 // ill-formed graph at the typed surface, before the renderer
6974 // emits a K8s object that fails or no-ops far from the source
6975 // caixa.lisp.
6976 // Route the per-`:contratos` structural self-edge probe
6977 // through the lifted [`WitContract::is_self_loop`] typed
6978 // predicate rather than the raw `c.de == c.para` field-
6979 // equality check — the one production consumer of the per-
6980 // `:contratos` caller-equals-callee endpoint-equality axis
6981 // now keys off exactly one typed dispatch on the substrate
6982 // primitive, so any future rebrand of the axis (an M4-typed-
6983 // caller enum whose identity comparison rule the predicate
6984 // could route through, a per-cluster caller/callee-alias
6985 // table the M4 CR materializer resolves per-CR before the
6986 // equality probe) migrates as a single caixa-core edit
6987 // rather than a coordinated rewrite of the gate + every
6988 // downstream self-edge consumer. Peer of the sibling
6989 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
6990 // [`WitContract::is_store`] shape-predicate routing on the
6991 // `:wit` world-ref axis, extended onto the per-edge
6992 // endpoint-equality axis.
6993 //
6994 // Route the paired [`AplicacaoError::ContratoSelfLoop`]
6995 // diagnostic's `caixa:` / `wit:` carriers through the
6996 // lifted [`WitContract::source`] / [`WitContract::world_ref`]
6997 // scalar accessors rather than the raw `c.de.clone()` /
6998 // `c.wit.clone()` field-access `String`-carry sites — the
6999 // last unlifted per-`:contratos` raw-field-access
7000 // `.clone()` sites in the M3 mesh-slot validator's self-
7001 // edge refusal arm. `.source().to_string()` is byte-
7002 // identical to `.de.clone()` (pinned by the sibling
7003 // `source_returns_de_byte_equal_across_permutations` accessor
7004 // test), and `.world_ref().to_string()` is byte-identical
7005 // to `.wit.clone()` (pinned by the sibling
7006 // `world_ref_returns_wit_byte_equal_across_permutations`
7007 // accessor test) — so a future rebrand of either underlying
7008 // storage flows through the accessor's one body without a
7009 // coordinated per-consumer rewrite across the M3 mesh
7010 // validator.
7011 if c.is_self_loop() {
7012 return Err(AplicacaoError::ContratoSelfLoop {
7013 caixa: c.source().to_string(),
7014 wit: c.world_ref().to_string(),
7015 });
7016 }
7017 if c.world_ref().is_empty() {
7018 let (de, para) = c.edge_pair();
7019 return Err(AplicacaoError::EmptyWit { de, para });
7020 }
7021 // Shape ↔ target consistency — surfaces "HTTP wit without
7022 // :endpoint", "NATS wit with :endpoint set", etc. as named
7023 // build errors instead of silent renderer drops. Threaded
7024 // through the duplicate-edge diagnostic below (via
7025 // [`WitTarget::label`]) so the "which typed target arm did
7026 // the duplicate carry" question is answered by the typed
7027 // enum's variant discriminator, not by re-probing the raw
7028 // `Option<String>` payload fields.
7029 let target_view = c.target()?;
7030 // Contract identity: (de, para, wit, endpoint, subject, slot).
7031 // Two contracts that match on all six are the same typed edge
7032 // declared twice — author error, not a legitimate variant of
7033 // "same caller-callee pair, different payload" (e.g.
7034 // cart→catalog at /products vs /search), which keeps distinct
7035 // identity keys via the differing endpoint payloads.
7036 //
7037 // Route the six-axis dedup key through the lifted
7038 // [`WitContract::identity`] composite-projection accessor
7039 // rather than the inline six-tuple builder — the two
7040 // substrate primitives on the per-`:contratos` identity axis
7041 // (the [`ContratoIdentity`] type alias's six axes, this
7042 // dedup-key's six tuple arms) now migrate as a unit on any
7043 // future axis addition. Peer of the sibling per-`:contratos`
7044 // composite-projection [`WitContract::edge_pair`] /
7045 // [`WitContract::edge_triple`] accessors on the
7046 // caller-callee / caller-callee-wit prefix axes; extends
7047 // the discipline onto the full-identity axis that carries
7048 // the three payload-shape arms too.
7049 let key = c.identity();
7050 crate::render::insert_first_seen(&mut seen_contracts, key, || {
7051 // Route the per-`:contratos` duplicate-gate diagnostic's
7052 // `(de, para, wit)` triple through the lifted
7053 // [`WitContract::edge_triple`] typed accessor rather
7054 // than pairing `edge_pair()` for the `(de, para)` prefix
7055 // with a raw `c.wit.clone()` for the `wit:` tail — the
7056 // paired-with-raw-field-access shape was the last
7057 // per-`:contratos` diagnostic constructor bypassing the
7058 // substrate-primitive composite projection, sibling to
7059 // the eight [`AplicacaoError::Contrato*`] triple-
7060 // carrying constructors [`WitContract::target`]'s edge
7061 // closure feeds through the same accessor.
7062 let (de, para, wit) = c.edge_triple();
7063 AplicacaoError::ContratoDuplicate {
7064 de,
7065 para,
7066 wit,
7067 target: target_view.label(),
7068 }
7069 })?;
7070 }
7071
7072 // Cycles in the synchronous-edge subgraph are build errors
7073 // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
7074 // are "acyclic by construction" because the publisher fires
7075 // and forgets, so no caller blocks on a downstream that loops
7076 // back to it.
7077 self.detect_sync_cycles()?;
7078
7079 if let Some(e) = self.entrada() {
7080 // Route the per-`:entrada` composite-reference read
7081 // through the lifted [`AplicacaoSpec::entrada`] accessor
7082 // rather than the raw `&self.entrada` field access — the
7083 // shape-and-membership gate's traversal head is now the
7084 // canonical read-side surface every per-Aplicacao entrada
7085 // consumer routes through, closing the fourth of four
7086 // open-coded outer-field accesses on the per-`:entrada`
7087 // outer-composite axis.
7088 //
7089 // Shape gate on `:entrada :para` runs ahead of the
7090 // membership lookup. Every `:membros :caixa` past
7091 // `validate_membro_caixa` is a valid DNS-1123 label
7092 // (3f9d7a0), so the `names` set structurally cannot
7093 // contain an empty / malformed string and the membership-
7094 // lookup diagnostic always misframed the root cause as
7095 // "this caixa is not in `:membros`". The shape gate
7096 // routes structurally-impossible-to-match inputs through
7097 // the narrower self-locating diagnostic, preserving the
7098 // legitimate "well-shaped phantom reference" arm — the
7099 // same trajectory the peer `:membros :caixa` (3f9d7a0),
7100 // `:placement :clusters` (6c8c00b), and `:contratos :de`
7101 // / `:para` (8d5af6b) axes already follow. This closes
7102 // the fourth and last Aplicacao-level Servico-name
7103 // reference axis on the canonical DNS-1123 floor.
7104 // Route the per-`:entrada :para` byte-string reads through
7105 // the lifted [`Entrada::destination`] accessor rather than
7106 // the raw `e.para` field access — the three
7107 // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7108 // (shape-gate `validate_entrada_para` arg, membership
7109 // lookup, `EntradaMemberMissing` diagnostic carry) now key
7110 // off exactly one typed dispatch on the substrate
7111 // primitive, closing the last unlifted per-`:entrada :para`
7112 // raw-field-access axis on the M3 mesh-slot validator.
7113 // The `.destination().to_string()` at the diagnostic site
7114 // is byte-identical to `.para.clone()` — pinned by the
7115 // sibling `destination_returns_entrada_para_byte_equal` +
7116 // `destination_borrows_from_entrada_para_storage` accessor
7117 // tests — so a future rebrand of the underlying `:para`
7118 // storage (a lift from `String` to a typed
7119 // `ServicoName(String)` newtype, a per-Aplicacao interning
7120 // arena the M4 CR materializer authors, a
7121 // `smol_str::SmolStr` inline-buffer swap) flows through
7122 // the accessor's one body without a coordinated
7123 // per-consumer rewrite across the M3 mesh validator.
7124 validate_entrada_para(e.destination())?;
7125 if !names.contains(e.destination()) {
7126 return Err(AplicacaoError::EntradaMemberMissing {
7127 para: e.destination().to_string(),
7128 });
7129 }
7130 // Route the per-`:entrada :host` byte-string reads through
7131 // the lifted [`Entrada::hostname`] accessor rather than
7132 // the raw `e.host` field access — the emptiness gate and
7133 // the shape-gate `validate_entrada_host` arg now key off
7134 // exactly one typed dispatch on the substrate primitive,
7135 // closing the last unlifted per-`:entrada :host` raw-
7136 // field-access axis on the M3 mesh-slot validator. Peer
7137 // of the sibling per-`:entrada :para` convergence above
7138 // and pinned by the existing
7139 // `hostname_returns_entrada_host_byte_equal` +
7140 // `hostnames_returns_singleton_of_hostname_accessor`
7141 // accessor tests, so any future
7142 // Gateway-API-shaped host renormalization (a wildcard-
7143 // label lift, a trailing-`.` FQDN substitution, an IDNA
7144 // Punycode round-trip the SNI fan-out overlay authors)
7145 // flows through the accessor's one body without a
7146 // coordinated per-consumer rewrite across the M3 mesh
7147 // validator.
7148 if e.hostname().is_empty() {
7149 return Err(AplicacaoError::EmptyEntradaHost);
7150 }
7151 // The `:host` lands verbatim as a K8s Gateway API v1
7152 // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7153 // both apiserver-validated against the same restrictive
7154 // pattern: lowercase RFC 1123 DNS subdomain, optional
7155 // single leading wildcard label (`*.`), max length 253,
7156 // per-label max length 63, no IP literals, no scheme,
7157 // no port. Until this gate landed `validate()` only
7158 // refused the empty string (`EmptyEntradaHost`); a
7159 // structurally invalid hostname (`"https://example.com"`,
7160 // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7161 // `"_underscored.example.com"`, `"FOO.example.com"`,
7162 // `"checkout.quero.cloud."`) silently passed validate
7163 // and the apiserver `field is invalid` error surfaced at
7164 // `kubectl apply` time, far from the source caixa.lisp.
7165 // Lifting the gate to caixa-build time mirrors the
7166 // `:entrada :paths` value-shape trajectory (eb3456d) and
7167 // closes the last unstructured `:entrada` axis.
7168 validate_entrada_host(e.hostname())?;
7169 // Structural-floor gate on `:entrada :port`: every
7170 // validated `Entrada::port` past this gate lies in
7171 // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
7172 // type-inferred ceiling closes the top edge, so no companion
7173 // upper-cap arm is needed here — unlike the peer capped-
7174 // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
7175 // `require_positive_bounded_u32` bracket covers both edges).
7176 // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
7177 // accept-set-floor const rather than the prior inline
7178 // `if e.port == 0` byte-check so a future rebrand of the
7179 // accept-set floor (a hypothetical unprivileged-only
7180 // migration lifting the floor to `1024`, a per-cluster
7181 // scoping the operator pins through a future
7182 // `:placement :port-floor` slot as the M4 typed-slot
7183 // trajectory adds it, the future
7184 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7185 // per-Aplicacao gateway resolver reaching for the same
7186 // floor) is a one-line edit on the canonical
7187 // [`SERVICO_PORT_MIN`] declaration, not a coordinated
7188 // rewrite across the emit site + the pin test + every
7189 // future per-target renderer the substrate adds.
7190 if e.port() < SERVICO_PORT_MIN {
7191 return Err(AplicacaoError::EntradaPortZero);
7192 }
7193 // Each `:entrada :paths` entry becomes a K8s Gateway API
7194 // HTTPRoute `matches[].path.value`. The Gateway API rejects
7195 // values that don't start with `/` for `type: PathPrefix`,
7196 // and an empty value is meaningless. Surface those as build
7197 // errors (MESH-COMPOSITION §III.3) rather than apply-time
7198 // failures. Empty `:paths` itself is fine — caixa-mesh
7199 // falls back to a single `/` catch-all.
7200 let mut seen = std::collections::HashSet::new();
7201 // Route the per-entry value-shape gate's traversal head
7202 // through the lifted [`Entrada::paths`] slice accessor
7203 // rather than the raw `&e.paths` field access — the
7204 // per-Aplicacao `:entrada :paths` validate loop now keys
7205 // off the canonical raw-slot surface every downstream
7206 // per-`:entrada` path-list consumer (the sibling
7207 // [`Entrada::resolved_paths`] fallback-applying resolver
7208 // internal reads, `feira app graph`'s per-Aplicacao entrada
7209 // summary line's `{:?}` Debug print) routes through, so any
7210 // future rebrand on the typed slot's raw-slot reader lands
7211 // at exactly one place. Same convergence discipline as the
7212 // sibling [`Placement::clusters`] (a6e18d7) reader-site
7213 // convergences on the peer M3 mesh-slot `Vec<String>`-carry
7214 // axis.
7215 for p in e.paths() {
7216 if p.is_empty() {
7217 return Err(AplicacaoError::EntradaPathEmpty);
7218 }
7219 if !p.starts_with('/') {
7220 return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
7221 }
7222 // Per-entry value-shape gate: the path lands verbatim
7223 // as a K8s Gateway API HTTPRoute `matches[].path.value`
7224 // (caixa-mesh/src/lib.rs:498), apiserver-validated
7225 // against `maxLength: 1024` + the Gateway API webhook's
7226 // path-grammar rules (no `//`, no `/./`, no `/../`, no
7227 // query/fragment separators, no whitespace, no control
7228 // characters, no non-ASCII bytes). Until this gate
7229 // landed `validate` only refused the empty string and
7230 // missing-leading-slash (eb3456d); a structurally
7231 // invalid path (`"/api?q=1"`, `"/api#frag"`,
7232 // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
7233 // 1025-byte URL-shaped slug) silently passed validate
7234 // and the failure surfaced at `kubectl apply` time as
7235 // a Gateway API webhook rejection, far from the source
7236 // caixa.lisp, with no field naming the offending
7237 // `:paths` entry. Lifting the gate to caixa-build time
7238 // mirrors the `:entrada :host` value-shape trajectory
7239 // (c7d05ec) on the sibling axis — every author surface
7240 // that emits a Gateway API field now matches the
7241 // apiserver's accepted set at validate time.
7242 validate_entrada_path(p)?;
7243 crate::render::insert_first_seen(&mut seen, p.as_str(), || {
7244 AplicacaoError::EntradaPathDuplicate { path: p.clone() }
7245 })?;
7246 }
7247 }
7248
7249 self.validate_placement()?;
7250
7251 self.validate_politicas()?;
7252
7253 Ok(())
7254 }
7255
7256 /// Reject `:membros` values that are operationally meaningless. The
7257 /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
7258 /// every entry names a Servico that participates in the Aplicacao,
7259 /// and the rendered programs.yaml fan-out emits one entry per
7260 /// `:membros`. Three authoring footguns are closed here:
7261 ///
7262 /// - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
7263 /// a `programs:` entry whose `name:` is the empty string, which
7264 /// downstream `lareira-fleet-programs` rejects at template time
7265 /// with a non-localized error;
7266 /// - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
7267 /// an empty semver constraint, so the failure surfaces far from
7268 /// the source caixa.lisp;
7269 /// - duplicate `:caixa` names — two entries with the same name
7270 /// produce duplicate programs.yaml entries (one silently
7271 /// overwrites the other in the cluster's HelmRelease values), and
7272 /// contract membership lookups against `:contratos` collapse the
7273 /// two onto one node, masking authoring mistakes.
7274 ///
7275 /// Same value-shape discipline as `:placement :clusters` (where empty
7276 /// + duplicate cluster names are rejected) and `:entrada :paths`
7277 /// (where empty + duplicate path entries are rejected). Lifting these
7278 /// invariants to the typed surface mirrors the MESH-COMPOSITION
7279 /// §III.3 promise that the `:membros` set — the load-bearing identity
7280 /// of the application graph — is well-formed by construction.
7281 fn validate_membros(&self) -> Result<(), AplicacaoError> {
7282 if self.membros().is_empty() {
7283 return Err(AplicacaoError::NoMembros);
7284 }
7285 let mut seen = std::collections::HashSet::new();
7286 for m in self.membros() {
7287 // Route the `MembroCaixaEmpty` refusal-arm's per-member
7288 // empty-`:caixa` shape-gate through the typed
7289 // [`Membro::nome`] accessor rather than the raw `.caixa`
7290 // field access — the last un-lifted `.caixa` production-
7291 // code read site on the per-`:membros` member-caixa `:nome`
7292 // axis, sibling to the six caixa-core validator read sites
7293 // (member-set collector, per-member value-shape gate,
7294 // duplicate dedup key, cycle-detector adjacency-map seed,
7295 // self-loop gate) the 4a32abf lift already routed through
7296 // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7297 // per-`programs[]` entry-`name:` `String`-carry converge.
7298 // Prior to this converge the `MembroCaixaEmpty` refusal
7299 // arm was the solitary consumer bypassing the typed
7300 // dispatch — the same-loop iteration's very next call
7301 // `validate_membro_caixa(m.nome())` already routed through
7302 // the accessor, so an author landing an empty-`:caixa`
7303 // entry hit the accessor on the shape-gate line but
7304 // bypassed it on the emptiness line one line above. A
7305 // future extension of the `:membros :caixa` axis to a
7306 // richer author surface (a per-cluster alias table pinned
7307 // through a future `:placement`-scoped slot, a namespace-
7308 // qualified rewrite the M4 CR materializer applies per-CR,
7309 // a per-member overlay from the future `:membros
7310 // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7311 // that lands on the accessor would silently disagree
7312 // between the emptiness gate and every peer consumer —
7313 // an author-declared `:caixa "checkout"` value the
7314 // accessor rewrote to `""` under a future alias arm would
7315 // pass the raw `.is_empty()` gate here while the peer
7316 // `validate_membro_caixa(m.nome())` call one line below
7317 // (and every downstream emit-side consumer routing through
7318 // the accessor) tripped on the empty-value shape far from
7319 // this diagnostic. Pinned by the drift-detection test
7320 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7321 // below.
7322 if m.nome().is_empty() {
7323 return Err(AplicacaoError::MembroCaixaEmpty);
7324 }
7325 // Every emitted cluster artifact's `metadata.name` derives
7326 // from a `:membros :caixa` value verbatim — the rendered
7327 // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7328 // the [`crate::LABEL_PROGRAM`] label value on every CNP
7329 // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7330 // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7331 // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7332 // `metadata.name` when the member is the `:entrada :para`
7333 // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7334 // schema enforces the DNS-1123 label rule on admission;
7335 // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7336 // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7337 // mistaken-identity slug) silently passes the prior empty-/
7338 // duplicate-only gate and the failure surfaces at `kubectl
7339 // apply` time as a `metadata.name: Invalid value` rejection,
7340 // far from the source caixa.lisp, with no field naming the
7341 // offending `:membros` entry. Lifting the gate to caixa-build
7342 // time mirrors the `:entrada :host` value-shape trajectory
7343 // (c7d05ec) on the peer axis — every author surface that
7344 // emits a K8s name now matches the apiserver's accepted set
7345 // at validate time.
7346 validate_membro_caixa(m.nome())?;
7347 // The author surface for `:versao` is the same Cargo-shaped
7348 // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7349 // `"*"`) every `:deps` entry carries — and the lacre pipeline
7350 // resolves both axes through the same
7351 // [`crate::version::parse_requirement`] entry-point. The
7352 // shared [`crate::render::require_valid_versao_requirement`]
7353 // helper brackets the empty-first + parse cascade both peer
7354 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7355 // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7356 // route through, so drift between the three axes' accepted
7357 // requirement sets is structurally impossible and the parse-
7358 // side no-op the empty-first arm closes (semver's empty
7359 // parse yields an implicit `*`) lives in exactly one
7360 // predicate.
7361 crate::render::require_valid_versao_requirement(
7362 m.versao_requirement(),
7363 || AplicacaoError::MembroVersaoEmpty {
7364 caixa: m.nome().to_string(),
7365 },
7366 |reason| AplicacaoError::MembroVersaoInvalid {
7367 caixa: m.nome().to_string(),
7368 versao: m.versao_requirement().to_string(),
7369 reason,
7370 },
7371 )?;
7372 crate::render::insert_first_seen(&mut seen, m.nome(), || {
7373 AplicacaoError::MembroDuplicate {
7374 caixa: m.nome().to_string(),
7375 }
7376 })?;
7377 }
7378 Ok(())
7379 }
7380
7381 /// Reject `:placement` values that are operationally meaningless or
7382 /// internally contradictory. Each strategy variant has the same
7383 /// invariants on `:clusters` (non-empty list, non-empty unique
7384 /// entries) — the §III.1 author surface is uniform on this axis,
7385 /// even though the *meaning* of the list differs by strategy
7386 /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7387 /// shard pool).
7388 ///
7389 /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7390 /// are the same authoring footgun closed for `:politicas` zero
7391 /// values and `:entrada` empty paths: the field is *declared* but
7392 /// carries no meaning, so downstream renderers either skip it
7393 /// silently (cluster-fanout drops the empty entry, no diagnostic)
7394 /// or apply it literally and fail at admission time. Lifting both
7395 /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7396 /// violation is a build error" promise.
7397 ///
7398 /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7399 /// is required exactly when `:estrategia Sharded` (hash-keyed
7400 /// distribution, Akka cluster-sharding convention, §II.4) and
7401 /// refused on `:estrategia Replicated`/`SingleNode` (where no
7402 /// hash-keyed routing axis consumes it). The partition closes the
7403 /// "I think I configured sharding" footgun where an author writes
7404 /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7405 /// the typed slot's value silently vanishes at the renderer layer
7406 /// — every validated `Placement` past this call satisfies
7407 /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7408 fn validate_placement(&self) -> Result<(), AplicacaoError> {
7409 // Every strategy needs at least one named cluster: `Replicated`
7410 // and `SingleNode` use the list as hosting/takeover candidates
7411 // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7412 // §II.1), while `Sharded` uses it as the shard pool
7413 // (Akka cluster-sharding convention — §II.4). An empty list is
7414 // meaningless under any of the three.
7415 //
7416 // Route the paired pre-flight `.is_empty()` refusal probe and
7417 // the per-cluster validate loop's traversal head through the
7418 // lifted [`Placement::clusters`] slice-return accessor rather
7419 // than the raw `self.placement.clusters` field access — the
7420 // two production consumers of the per-`:placement` cluster-
7421 // pool `Vec`-carry now key off exactly one typed dispatch on
7422 // the substrate primitive, so any future rebrand on the axis
7423 // (a per-tenant cluster-pool overlay the operator pins through
7424 // a future `:placement :clusters-overrides` slot, a per-
7425 // Aplicacao dynamic cluster-pool derivation the future M5
7426 // adaptive-placement engine computes from `:affinity` weights)
7427 // migrates as a single caixa-core edit rather than a
7428 // coordinated rewrite of the paired arms — sibling of the
7429 // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7430 // arm migration on the per-`:supervisor` static-child-list
7431 // `Vec`-carry axis.
7432 //
7433 // Route the per-`:placement` outer-composite reference read
7434 // through the lifted [`AplicacaoSpec::placement`] outer accessor
7435 // rather than the raw `&self.placement` field access — the
7436 // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7437 // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7438 // axis-level lifted accessor family) now routes through the
7439 // substrate-primitive typed dispatch at the outer composition
7440 // altitude, the same shape the peer caixa-mesh
7441 // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7442 // and the sibling `feira app graph` per-Aplicacao print line
7443 // now key off after this accessor lift.
7444 let p = self.placement();
7445 if p.clusters().is_empty() {
7446 return Err(AplicacaoError::PlacementWithoutClusters {
7447 estrategia: p.estrategia(),
7448 });
7449 }
7450 let mut seen = std::collections::HashSet::new();
7451 for c in p.clusters() {
7452 // Per-entry value-shape gate: the cluster name lands in
7453 // every K8s context / `lareira-fleet-programs` aggregator
7454 // filter / future M4 CR materializer's per-cluster axis
7455 // a validated `:clusters` entry passes through, each
7456 // enforcing the DNS-1123 label rule on admission. Same
7457 // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7458 // on the peer name axis — both axes' validated values
7459 // are guaranteed-accepted by the apiserver without
7460 // re-validation at any downstream renderer or admission
7461 // layer.
7462 validate_placement_cluster(c)?;
7463 crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7464 AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7465 })?;
7466 }
7467 // Route the per-`:placement :affinity` per-hint value-shape
7468 // gate through the typed [`Placement::affinity`] accessor rather
7469 // than the raw `&self.placement.affinity` field access — the
7470 // sole open-coded field-access site on the per-`:placement`
7471 // M3-Adaptive-compression-hint axis the accessor lift now owns.
7472 // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7473 // the accessor's `Option<&str>` return type;
7474 // [`validate_placement_affinity`]'s `&str` parameter accepts
7475 // the narrower borrow without a re-allocation, so the routing
7476 // change is byte-for-byte in the pass arm and remains
7477 // byte-for-byte in every failure diagnostic
7478 // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7479 // String` field is populated inside
7480 // [`validate_placement_affinity`] via the peer `.to_string()`
7481 // path on the same borrowed slice). Peer of the sibling
7482 // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7483 // routing through [`Placement::shard_key`] at the caixa-core
7484 // site above — extends the "read `:placement` optional-scalars
7485 // through the typed accessor" discipline to the second
7486 // `Option<String>`-shape slot on the M3 mesh-slot family.
7487 //
7488 // Per-hint value-shape gate: the `:affinity` value lands
7489 // verbatim in the M3 Adaptive compression overlay
7490 // (caixa-mesh's `placement.affinity` emission) and every
7491 // future M4 placement-engine routing axis keying off the
7492 // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7493 // selector — each enforces the DNS-1123 label rule on
7494 // admission. Same typed-shape trajectory as `:placement
7495 // :clusters` (6c8c00b) on the sibling slot and the four
7496 // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7497 // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7498 // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7499 // on the Aplicacao surface to land on the canonical
7500 // [`crate::render::is_dns_1123_label`] floor.
7501 if let Some(a) = p.affinity() {
7502 validate_placement_affinity(a)?;
7503 }
7504 match p.estrategia() {
7505 // Route the `Sharded`-arm shape-gate cascade through the
7506 // typed [`Placement::shard_key`] accessor rather than the
7507 // raw `&self.placement.shard_key` field access — one of the
7508 // two open-coded field-access sites on the per-`:placement`
7509 // Akka-cluster-sharding-key axis the accessor lift now
7510 // owns. The `Some(k)`-bound `k` narrows from `&String` to
7511 // `&str` under the accessor's `Option<&str>` return type;
7512 // `str::is_empty` and [`validate_placement_shard_key`]'s
7513 // `&str` parameter both accept the narrower borrow without
7514 // a re-allocation.
7515 PlacementStrategy::Sharded => match p.shard_key() {
7516 None => return Err(AplicacaoError::ShardedWithoutKey),
7517 Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7518 // Per-axis value-shape gate on the Akka-cluster-sharding
7519 // `:shard-key` extractor expression. The shape gate runs
7520 // after the more self-locating `ShardedKeyEmpty` arm so
7521 // a `:shard-key ""` surfaces the narrower empty
7522 // diagnostic first; every non-empty `:shard-key` past
7523 // this call is guaranteed to be a printable-ASCII
7524 // single-token reference the future M4 Akka-style
7525 // cluster-sharding reconciler can hash without
7526 // re-validating at the runtime layer. Mirrors the
7527 // payload-axis shape gates on the peer `:contratos`
7528 // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7529 // 63e18a0 / c4213a4) — each lifts the runtime parser's
7530 // intersection-floor to a caixa-build-time gate.
7531 Some(k) => validate_placement_shard_key(k)?,
7532 },
7533 // `:shard-key` is the Akka-cluster-sharding axis
7534 // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7535 // across the cluster pool. `Replicated` (active-active across
7536 // every named cluster) and `SingleNode` (Erlang/OTP
7537 // distributed-app takeover/failover, §II.1) have no hash-keyed
7538 // routing axis to consume the slot; downstream renderers
7539 // (caixa-mesh's `placement.shardKey` overlay at
7540 // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7541 // sharding reconciler) ignore `:shard-key` outside the
7542 // `Sharded` arm by construction. Until this gate landed an
7543 // author who wrote `:placement (:estrategia Replicated
7544 // :shard-key "tenantId")` (an off-by-one strategy typo, a
7545 // copy-paste from a Sharded sibling caixa, the "I think I
7546 // configured sharding" footgun) silently passed validate and
7547 // the typed slot's value vanished at the renderer layer with
7548 // no diagnostic — the canonical "declared-but-inert" footgun
7549 // the empty-:affinity / empty-shard-key / zero-:politicas /
7550 // empty-:contratos-target gates already close on every other
7551 // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7552 // Lifting the rejection to a build-time gate closes the
7553 // Sharded ↔ non-Sharded partition over the typed
7554 // `:placement` slot: every validated `Placement` past this
7555 // call has `shard_key.is_some()` iff `estrategia ==
7556 // Sharded`, structurally — the future Akka reconciler can
7557 // reach for `placement.shard_key` knowing it's `Some` exactly
7558 // when the strategy consumes it, without re-deriving the
7559 // partition from inline strategy probes.
7560 PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7561 // Route the non-`Sharded`-arm declared-but-inert refusal
7562 // through the typed [`Placement::shard_key`] accessor —
7563 // the second of the two open-coded field-access sites the
7564 // accessor lift now owns. The `Some(k)`-bound `k` narrows
7565 // from `&String` to `&str`; the `AplicacaoError::
7566 // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7567 // materializes the owned `String` via `k.to_string()`
7568 // (peer to the sibling per-Membro `String`-carry sites
7569 // 4127bb6 routed through `m.nome().to_string()` /
7570 // `m.versao_requirement().to_string()`), so the whole
7571 // `Sharded` ↔ non-`Sharded` partition on the
7572 // `:shard-key` axis now flows through the same typed
7573 // dispatch as the sibling `Sharded`-arm shape gate.
7574 if let Some(k) = p.shard_key() {
7575 return Err(AplicacaoError::ShardKeyOnNonSharded {
7576 estrategia: p.estrategia(),
7577 shard_key: k.to_string(),
7578 });
7579 }
7580 }
7581 }
7582 Ok(())
7583 }
7584
7585 /// Reject `:politicas` values that are operationally meaningless.
7586 /// Each axis is optional — omitting it expresses "no policy on this
7587 /// axis". Carrying a *zero* value for a declared axis is the bug
7588 /// this function rejects: zero is either
7589 ///
7590 /// - re-interpreted as "infinite" by downstream proxies (Envoy's
7591 /// `RouteAction.timeout = 0s` disables the timeout entirely),
7592 /// directly contradicting MESH-COMPOSITION §V CSE invariant
7593 /// "every Aplicacao declares :politicas :timeout (no infinite
7594 /// blocking)", or
7595 /// - a renderer footgun (a 0-failure circuit breaker trips on the
7596 /// first call; a 0-rate rate-limit denies every request).
7597 ///
7598 /// Lifting these "0 means the opposite of what you think" idioms to
7599 /// the typed Aplicacao surface as build errors mirrors the §III.3
7600 /// promise that contract drift, capability leaks, and cycles are all
7601 /// build errors — not runtime surprises.
7602 fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7603 // Route the per-`:politicas` composite-reference read through
7604 // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7605 // than the raw `&self.politicas` field access — the per-axis
7606 // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7607 // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7608 // the substrate-primitive typed dispatch at the outer
7609 // composition altitude AND at every per-axis altitude, matching
7610 // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7611 // timeout/retry-overlay emitters that already key off the same
7612 // per-axis accessor family. The four-axis fan-out is now
7613 // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7614 // `p.retries` field-access sites (co-resident with the peer
7615 // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7616 // b0e741a / 21a6c3b already lifted) now route through
7617 // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7618 // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7619 // access axis on the M3 mesh-slot family.
7620 let p = self.politicas();
7621 if let Some(t) = p.timeout() {
7622 // Zero-floor + integer-millisecond canonical-form +
7623 // upper-cap bracket on the typed `:timeout` axis. See
7624 // [`crate::render::require_positive_canonical_bounded_duration`]
7625 // for the full three-arm ordering discipline (zero-floor
7626 // strictly precedes the canonical-form arm so
7627 // `Duration::ZERO` surfaces the self-locating
7628 // `PolicyTimeoutZero` diagnostic naming the omit-axis
7629 // remediation; canonical-form strictly precedes the cap
7630 // arm so a sub-millisecond above-cap `Duration` surfaces
7631 // the more fundamental round-trip-shape diagnostic first)
7632 // and the four peer typed-`Duration` sites that now share
7633 // this canonical bracket. Every validated value lies in
7634 // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7635 // granularity — the same top-and-bottom-edge discipline
7636 // [`POLICY_RETRIES_MAX`] and
7637 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7638 // capped-`u32` `:politicas` axes.
7639 crate::render::require_positive_canonical_bounded_duration(
7640 t,
7641 POLICY_TIMEOUT_MAX,
7642 || AplicacaoError::PolicyTimeoutZero,
7643 |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7644 |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7645 )?;
7646 }
7647 if let Some(r) = p.retries() {
7648 // Zero-floor + upper-cap bracket on the typed `:retries`
7649 // axis. See [`crate::render::require_positive_bounded_u32`]
7650 // for the ordering discipline (zero-floor arm strictly
7651 // precedes cap arm so `Some(0)` surfaces the self-locating
7652 // `PolicyRetriesZero` diagnostic with its omit-axis
7653 // remediation directly named, not the misleading
7654 // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7655 // this bracket landed the top edge ran all the way to
7656 // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7657 // Some(100_000), .. }` (or the equivalent author-surface
7658 // `(:retries 100000)` / `(:retries 4294967295)` typo
7659 // landing in the slot) silently passed validate. The
7660 // runtime substrate consuming the value (Envoy's
7661 // `retry_policy.num_retries`, the future
7662 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7663 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7664 // policy into a thundering-herd amplification vector —
7665 // the caller's one request fans out to `retries`
7666 // server-side calls per edge per traversal, multiplying
7667 // load by `(retries+1)^depth` across the
7668 // synchronous-`:contratos` subgraph at the precise moment
7669 // the substrate is already failing (transient failure is
7670 // the trigger), exactly the failure mode AWS App Mesh's
7671 // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7672 // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7673 // the sibling capped-`u32` `:politicas` axes
7674 // (`max_failures`, `rate_limit.rate`) and the peer capped-
7675 // `u32` axes in `:supervisor :max-restarts` +
7676 // `:limits :cpu`; all five now route through the same
7677 // canonical bracket helper.
7678 crate::render::require_positive_bounded_u32(
7679 r,
7680 POLICY_RETRIES_MAX,
7681 || AplicacaoError::PolicyRetriesZero,
7682 |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7683 )?;
7684 }
7685 if let Some(cb) = p.circuit_breaker() {
7686 // Zero-floor + upper-cap bracket on the typed
7687 // `:max-failures` axis. See
7688 // [`crate::render::require_positive_bounded_u32`] for the
7689 // ordering discipline (zero-floor arm strictly precedes
7690 // cap arm so `max_failures == 0` surfaces the
7691 // self-locating `PolicyBreakerZeroFailures` diagnostic
7692 // with its omit-axis remediation directly named, not the
7693 // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7694 // false` cap-arm miss). Until this bracket landed the top
7695 // edge ran all the way to `u32::MAX` and a struct-literal
7696 // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7697 // equivalent author-surface `(:max-failures 100000)` /
7698 // `(:max-failures 4294967295)` typo landing in the slot)
7699 // silently passed validate. The runtime substrate
7700 // consuming the value (Envoy's
7701 // `outlier_detection.consecutive_5xx`, the future
7702 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7703 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7704 // breaker policy into a no-op — the trip threshold is
7705 // structurally so high that no realistic
7706 // failures-per-`:window` traffic shape can reach it, the
7707 // breaker never trips, and every typed-slot consumer
7708 // emits an Envoy / Cilium L7 overlay carrying a
7709 // protection that is structurally never enforced. The
7710 // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7711 // peer with `retries` and `rate_limit.rate` on the same
7712 // helper.
7713 crate::render::require_positive_bounded_u32(
7714 cb.max_failures(),
7715 POLICY_BREAKER_MAX_FAILURES_MAX,
7716 || AplicacaoError::PolicyBreakerZeroFailures,
7717 |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7718 )?;
7719 // Zero-floor + integer-millisecond canonical-form +
7720 // upper-cap bracket on the typed `:window` axis. See
7721 // [`crate::render::require_positive_canonical_bounded_duration`]
7722 // for the full three-arm ordering discipline (peer to the
7723 // `:timeout` site immediately above); every validated
7724 // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7725 // (1ms..=1h), integer-millisecond granularity — the same
7726 // top-and-bottom-edge discipline
7727 // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7728 // duration-typed `:politicas :timeout` axis.
7729 crate::render::require_positive_canonical_bounded_duration(
7730 cb.window(),
7731 POLICY_BREAKER_WINDOW_MAX,
7732 || AplicacaoError::PolicyBreakerZeroWindow,
7733 |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7734 |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7735 )?;
7736 }
7737 if let Some(rl) = p.rate_limit() {
7738 // Zero-floor + upper-cap bracket on the typed
7739 // `:rate-limit` rate axis. See
7740 // [`crate::render::require_positive_bounded_u32`] for the
7741 // ordering discipline (zero-floor arm strictly precedes
7742 // cap arm so `rl.rate == 0` surfaces the self-locating
7743 // `PolicyRateLimitZero` diagnostic with its omit-axis
7744 // remediation directly named, not the misleading
7745 // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7746 // Until this bracket landed the top edge ran all the way
7747 // to `u32::MAX` and a struct-literal
7748 // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7749 // author-surface `(:rate-limit "4294967295/s")` /
7750 // `(:rate-limit "100000000/m")` typo landing in the slot)
7751 // silently passed validate. The runtime substrate
7752 // consuming the value (Envoy's
7753 // `local_rate_limit.token_bucket.max_tokens`, the future
7754 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7755 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7756 // rate-limit policy into a no-op limiter: the bucket
7757 // capacity is structurally so high that no realistic
7758 // per-edge traffic shape can drain it, the limiter never
7759 // trips, and every typed-slot consumer emits a "rate
7760 // declared" L7 overlay carrying enforcement that is
7761 // structurally never reached — the canonical
7762 // declared-but-inert footgun the sibling
7763 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7764 // the peer no-op-breaker shape. The bracket set is
7765 // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7766 // `max_failures` on the same helper. The rate bracket
7767 // strictly precedes the window-canonical gate so a
7768 // structurally absurd rate magnitude surfaces the more
7769 // fundamental amplification-shape diagnostic before the
7770 // narrower codec-round-trip-shape diagnostic on `:window`.
7771 crate::render::require_positive_bounded_u32(
7772 rl.rate(),
7773 POLICY_RATE_LIMIT_MAX,
7774 || AplicacaoError::PolicyRateLimitZero,
7775 |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7776 )?;
7777 // The `:rate-limit` author surface is the canonical
7778 // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7779 // accepts exactly the three-unit set (1s/60s/3600s) the
7780 // [`rate_limit_codec::render`] formatter emits the canonical
7781 // unit suffix for. A `RateLimit` whose `:window` is anything
7782 // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7783 // programmatically (struct literals in Rust + the typed
7784 // `Duration` field) but renders to a `<n>/<k>s` fragment
7785 // (the codec's fall-through) the parser then rejects on
7786 // round-trip — silently breaking the THEORY.md §V.2.7
7787 // render-determinism contract for any consumer that
7788 // serializes-then-deserializes the typed slot. Lifting the
7789 // canonical-window invariant to a build-time gate at
7790 // `validate_politicas` makes the codec's round-trip property
7791 // a structural property of the validated typed value:
7792 // every `RateLimit` past `AplicacaoSpec::validate` has a
7793 // window the codec round-trips losslessly, so the next
7794 // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7795 // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7796 // §III.2 #3) reaches for `rate_limit.window` knowing the
7797 // value is in the codec's accepted set without re-validating
7798 // at the renderer layer. Same trajectory as c4213a4 (typed
7799 // WitContract endpoint/subject/slot value-shape gates) and
7800 // the b0c8389 :behavior + :upgrade-from script-path lifts:
7801 // the typed slot's valid set matches its codec's accepted
7802 // set, structurally.
7803 // Route the canonical-window shape-gate through the substrate
7804 // primitive [`RateLimit::canonical_unit`] rather than the free
7805 // module-private [`is_canonical_rate_limit_window`] predicate:
7806 // both projections resolve `Duration → Option<RateLimitUnit>`
7807 // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7808 // arm on the closed-set typed enum), but the accessor is the
7809 // typed method every downstream consumer of the validated slot
7810 // ([`rate_limit_codec::render`]'s canonical arm above, the
7811 // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7812 // per-`:politicas :rate-limit` admission webhook, the future
7813 // per-`:contratos`-edge rate-limit-override overlay
7814 // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7815 // production consumers of the canonical-unit axis (the codec
7816 // render and this validate gate) now key off exactly one typed
7817 // dispatch on the substrate primitive, so any future extension
7818 // to `canonical_unit` (a per-cluster canonical-window overlay
7819 // the operator pins through a future `:contratos :rate-limit
7820 // -unit-overrides` slot, a per-tenant unit-alias table the M4
7821 // CR materializer resolves per-CR) reaches both consumers by
7822 // construction rather than a coordinated rewrite of every
7823 // free-helper call site.
7824 if rl.canonical_unit().is_none() {
7825 return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7826 window: rl.window(),
7827 });
7828 }
7829 }
7830 Ok(())
7831 }
7832
7833 /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
7834 /// A synchronous edge is any contract whose typed [`WitTarget`] is
7835 /// `Http`, `Store`, or `Capability` — the caller blocks on the
7836 /// callee, so a cycle would deadlock at runtime. Pub-sub edges
7837 /// (`WitTarget::PubSub`) are skipped: an event publisher does not
7838 /// block on its subscribers, so they can never close a sync loop.
7839 ///
7840 /// Iterative DFS with three-coloring; the reported cycle is the
7841 /// path of caixa names traversed from the back-edge target around
7842 /// to itself, in declaration order. Adjacency lists and DFS roots
7843 /// are visited in `BTreeMap` key order so the diagnostic is
7844 /// deterministic across runs.
7845 fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7846 use std::collections::{BTreeMap, BTreeSet};
7847
7848 #[derive(Clone, Copy, PartialEq, Eq)]
7849 enum Mark {
7850 White,
7851 Gray,
7852 Black,
7853 }
7854
7855 let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7856 for m in self.membros() {
7857 adj.entry(m.nome()).or_default();
7858 }
7859 for c in self.contratos() {
7860 // target() was already called by validate(); re-running here
7861 // keeps detect_sync_cycles self-contained for callers that
7862 // reuse it (M4 per-edge policy resolver) without revalidating.
7863 //
7864 // The pub-sub-arm check routes through the lifted
7865 // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7866 // arm-discriminator predicate rather than a raw `matches!(…,
7867 // WitTarget::PubSub { .. })` on the variant so a future
7868 // rebrand on the axis (an M4 per-edge WIT registry split of
7869 // [`WitTarget::PubSub`] into shape-specific peers, a
7870 // per-consumer rename that the accept-set already carries)
7871 // reaches this call site through the derive rather than a
7872 // scattered per-arm `matches!` rewrite — same
7873 // `IsVariant`-derived-arm-discriminator discipline the
7874 // peer closed-set typed enums ([`crate::CaixaKind`] via
7875 // f5bba80, [`PlacementStrategy`] via 766ec63,
7876 // [`crate::supervisor::RestartStrategy`] +
7877 // [`crate::supervisor::RestartPolicy`],
7878 // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7879 // already route through on the substrate's other typed-enum
7880 // arm-discriminator axes.
7881 if c.target()?.is_pubsub() {
7882 continue;
7883 }
7884 adj.entry(c.source()).or_default().insert(c.destination());
7885 }
7886
7887 let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7888 let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7889
7890 // Stable DFS root order — BTreeMap iteration is sorted by key.
7891 let roots: Vec<&str> = adj.keys().copied().collect();
7892
7893 // Frame: (node, sorted-neighbours snapshot, next-edge index).
7894 for root in roots {
7895 if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
7896 continue;
7897 }
7898 let root_neighbors: Vec<&str> = adj
7899 .get(root)
7900 .map(|s| s.iter().copied().collect())
7901 .unwrap_or_default();
7902 let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
7903 color.insert(root, Mark::Gray);
7904
7905 loop {
7906 // Read+advance the top frame in one borrow scope so we
7907 // can later mutate the stack (push/pop) without holding
7908 // a borrow across.
7909 let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
7910 let node = top.0;
7911 if top.2 >= top.1.len() {
7912 (node, None)
7913 } else {
7914 let nxt = top.1[top.2];
7915 top.2 += 1;
7916 (node, Some(nxt))
7917 }
7918 });
7919 let Some((node, nxt_opt)) = step else { break };
7920 let Some(nxt) = nxt_opt else {
7921 color.insert(node, Mark::Black);
7922 stack.pop();
7923 continue;
7924 };
7925 let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
7926 match nxt_color {
7927 Mark::Gray => {
7928 // Reconstruct the cycle from `node` back through
7929 // the parent chain to `nxt`, then close.
7930 let mut cycle = Vec::new();
7931 let mut cur = node;
7932 cycle.push(cur.to_string());
7933 while cur != nxt {
7934 match parent.get(cur).copied() {
7935 Some(p) => {
7936 cur = p;
7937 cycle.push(cur.to_string());
7938 }
7939 None => break,
7940 }
7941 }
7942 cycle.reverse();
7943 cycle.push(nxt.to_string());
7944 return Err(AplicacaoError::ContratoCycle { cycle });
7945 }
7946 Mark::White => {
7947 parent.insert(nxt, node);
7948 color.insert(nxt, Mark::Gray);
7949 let nxt_neighbors: Vec<&str> = adj
7950 .get(nxt)
7951 .map(|s| s.iter().copied().collect())
7952 .unwrap_or_default();
7953 stack.push((nxt, nxt_neighbors, 0));
7954 }
7955 Mark::Black => {}
7956 }
7957 }
7958 }
7959 Ok(())
7960 }
7961
7962 /// Substrate-canonical destination-facing TCP port every emitted
7963 /// per-Aplicacao artifact must key `destination`-shaped port axes
7964 /// off. Returns the typed `:entrada :port` scalar when this
7965 /// Aplicacao's `:entrada` block names `destination` under its
7966 /// `:para` axis (the destination Servico *is* the ingress apex, so
7967 /// the substrate honors the author-declared listener port
7968 /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
7969 /// fallback otherwise (every non-apex destination — the internal
7970 /// mesh Servicos `:contratos` reach across, the future per-edge
7971 /// policy resolver's per-destination probe targets, the
7972 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
7973 /// L4 port resolver — reads the same substrate-canonical port floor
7974 /// by construction).
7975 ///
7976 /// Prior to this lift the "if :entrada matches this destination use
7977 /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
7978 /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
7979 /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
7980 /// prior to this lift), with no typed method on the substrate primitive
7981 /// that named the rule. A future per-destination port axis addition
7982 /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
7983 /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
7984 /// per-Servico listener ports land, a per-cluster override the operator
7985 /// pins through a future `:placement :default-port` slot — would have
7986 /// to be threaded through every renderer's inline cascade in lockstep
7987 /// or one consumer would silently disagree on which port a given
7988 /// destination Servico's ingress lands at. Lifting the rule to a
7989 /// typed method on the substrate primitive means the M4 CR
7990 /// materializer, the future per-edge policy resolver, and every
7991 /// downstream test-fixture navigator reach for exactly one typed
7992 /// dispatch — the resolver's accept-set moves as a unit on any
7993 /// future axis addition.
7994 ///
7995 /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
7996 /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
7997 /// the typed primitive, thin projections at each consumer"
7998 /// discipline lifts on the sibling `:contratos` payload / `:politicas
7999 /// :rate-limit` unit-suffix axes; extends the discipline onto the
8000 /// destination-facing port-resolution axis every per-Aplicacao
8001 /// L4-fallback renderer consumes.
8002 #[must_use]
8003 pub fn port_for_destination(&self, destination: &str) -> u16 {
8004 // Route the per-`:entrada` composite-reference read through
8005 // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8006 // the raw `self.entrada.as_ref()` field access — the
8007 // per-destination L4-port fallback resolver's composite-
8008 // projection seed is now the canonical read-side surface
8009 // every per-Aplicacao entrada consumer routes through, peer
8010 // of the sibling `validate` per-`:entrada` shape-and-
8011 // membership gate migration on the same outer-composite
8012 // axis.
8013 // Route the per-`:entrada` apex-destination membership probe
8014 // through the lifted [`Entrada::destination`] accessor rather
8015 // than the raw `e.para == destination` field access — the last
8016 // un-lifted `.para` production-code read site on the per-
8017 // `:entrada` `:para` axis, sibling to the four caixa-core
8018 // consumer sites the peer 15ddd8c converge already routed
8019 // through the accessor (the three
8020 // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8021 // membership gate sites: the `validate_entrada_para` DNS-1123
8022 // shape gate, the per-`:membros` membership lookup, and the
8023 // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8024 // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8025 // `entrada.para`-projection converge at
8026 // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8027 // route-name projection site). Prior to this converge the
8028 // `port_for_destination` resolver was the solitary consumer
8029 // bypassing the typed dispatch on the `.para` axis — the two
8030 // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8031 // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8032 // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8033 // reach through the same accessor family compose with this
8034 // resolver at the emit boundary via the apex-identity
8035 // invariant `spec.port_for_destination(entrada.destination())
8036 // == entrada.port` the sibling
8037 // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8038 // pin pins across four permutations. A future extension of the
8039 // `:entrada :para` axis to a richer author surface (a per-
8040 // cluster alias overlay the operator pins through a future
8041 // `:placement`-scoped slot, a namespace-qualified rewrite the
8042 // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8043 // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8044 // §III.2 acknowledges) that lands on the accessor would silently
8045 // disagree between this resolver and the two `caixa-mesh` emit
8046 // sites — an author-declared `:para "cart"` value the accessor
8047 // rewrote to `"cart-v2"` under a future canary arm would leave
8048 // the resolver's membership arm falling through to
8049 // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8050 // `.para`) while the peer emit-site consumers landed on the
8051 // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8052 // silently disagreed on which destination port a given typed
8053 // `:entrada` resolves to at cluster-apply time. Pinned by the
8054 // drift-detection test
8055 // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8056 // below.
8057 self.entrada()
8058 .filter(|e| e.destination() == destination)
8059 .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8060 }
8061}
8062
8063/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8064/// entry may name the Aplicacao's own `:nome`.
8065///
8066/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8067/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8068/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8069/// Servicos that compose the app; an Aplicacao is never its own constituent),
8070/// and the lacre pipeline's closure-resolution would otherwise be handed a
8071/// node that is its own parent: a one-node cycle it either rejects far from
8072/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8073/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8074/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8075/// label + lacre closure root), a member whose `:caixa` equals the
8076/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8077/// peer.
8078///
8079/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8080/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8081/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8082/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8083/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8084/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8085/// (the Aplicacao :membros set; the supervision-tree :children list was the
8086/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8087/// every validated Supervisor's children are distinct from its `:nome`,
8088/// every validated Aplicacao's membros are distinct from its `:nome`. The
8089/// transitive consequence is that `:entrada :para` and `:contratos`
8090/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8091/// name the Aplicacao itself, without re-deriving the partition.
8092pub fn validate_no_self_membership(
8093 membros: &[Membro],
8094 parent_nome: &str,
8095) -> Result<(), AplicacaoError> {
8096 for m in membros {
8097 if m.nome() == parent_nome {
8098 return Err(AplicacaoError::MembroIsSelfAplicacao {
8099 caixa: parent_nome.to_string(),
8100 });
8101 }
8102 }
8103 Ok(())
8104}
8105
8106#[derive(Debug, Error, PartialEq, Eq)]
8107pub enum AplicacaoError {
8108 #[error("Aplicacao must declare at least one :membros entry")]
8109 NoMembros,
8110 #[error(
8111 ":membros entry has empty :caixa (every member must name a Servico; \
8112 omit the entry instead of carrying an empty name)"
8113 )]
8114 MembroCaixaEmpty,
8115 #[error(
8116 ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8117 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8118 name / label value the member name lands in; use a lowercase \
8119 alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8120 )]
8121 MembroCaixaInvalid { caixa: String, reason: String },
8122 #[error(
8123 ":membros entry {caixa:?} has empty :versao (every member must pin a \
8124 semver constraint that resolves through the lacre pipeline)"
8125 )]
8126 MembroVersaoEmpty { caixa: String },
8127 #[error(
8128 ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8129 requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8130 `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8131 carries; the lacre pipeline resolves both through the same parser)"
8132 )]
8133 MembroVersaoInvalid {
8134 caixa: String,
8135 versao: String,
8136 reason: String,
8137 },
8138 #[error(
8139 ":membros entry {caixa:?} appears more than once (the graph node set \
8140 is a set, not a multiset; duplicate members produce duplicate \
8141 programs.yaml entries and ambiguous :contratos membership lookups)"
8142 )]
8143 MembroDuplicate { caixa: String },
8144 #[error(
8145 "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8146 never its own constituent Servico (the application graph is a DAG rooted \
8147 at the Aplicacao; :membros names the *other* caixas that compose the \
8148 app, not the app itself). Since every :nome is a globally-unique \
8149 substrate identity, a member naming the Aplicacao's own :nome is a \
8150 one-node lacre-closure recursion, not a coincidentally-named peer; \
8151 drop the self-referential :membros entry or rename it to the actual \
8152 constituent caixa."
8153 )]
8154 MembroIsSelfAplicacao { caixa: String },
8155 #[error(
8156 "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8157 caixa declared in :membros; omit the contract or fill the {slot} field with a \
8158 member name)"
8159 )]
8160 ContratoCaixaEmpty { slot: &'static str },
8161 #[error(
8162 "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8163 :contratos {slot} value names a member of :membros, which is itself a \
8164 DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8165 object the member name lands in — Service, Pod, identity-based Cilium \
8166 selector; use a lowercase alphanumeric + hyphen identifier like \
8167 `\"checkout\"` or `\"cart-v2\"`)"
8168 )]
8169 ContratoCaixaInvalid {
8170 slot: &'static str,
8171 caixa: String,
8172 reason: String,
8173 },
8174 #[error("contrato references caixa {caixa:?} not declared in :membros")]
8175 ContratoMemberMissing { caixa: String },
8176 #[error(
8177 "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8178 entry is an inter-Servico contract whose :de and :para must name distinct \
8179 :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8180 the contract, or point :para at the member it actually calls)"
8181 )]
8182 ContratoSelfLoop { caixa: String, wit: String },
8183 #[error("contrato {de:?} → {para:?} has empty :wit")]
8184 EmptyWit { de: String, para: String },
8185 #[error(
8186 "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8187 {reason} (the substrate dispatches `:wit` values on the canonical \
8188 lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8189 `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8190 demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8191 kebab-case identifier per segment)"
8192 )]
8193 ContratoWitInvalid {
8194 de: String,
8195 para: String,
8196 wit: String,
8197 reason: String,
8198 },
8199 #[error(
8200 ":entrada :para is empty (every :entrada must route to a caixa declared in \
8201 :membros; fill the :para field with a member name)"
8202 )]
8203 EntradaParaEmpty,
8204 #[error(
8205 ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8206 :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8207 label per the K8s apiserver's `metadata.name` rule on every object the \
8208 member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8209 Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8210 `\"checkout\"` or `\"cart-v2\"`)"
8211 )]
8212 EntradaParaInvalid { para: String, reason: String },
8213 #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8214 EntradaMemberMissing { para: String },
8215 #[error(":entrada must declare a non-empty :host")]
8216 EmptyEntradaHost,
8217 #[error(
8218 ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8219 (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8220 `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8221 like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8222 )]
8223 EntradaHostInvalid { host: String, reason: String },
8224 #[error(":entrada :port must be in 1..=65535, got 0")]
8225 EntradaPortZero,
8226 #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8227 EntradaPathEmpty,
8228 #[error(
8229 ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8230 )]
8231 EntradaPathNotAbsolute { path: String },
8232 #[error(
8233 ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8234 value: {reason} (the K8s apiserver enforces the same shape on \
8235 `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8236 single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8237 requires percent-encoding `%XX` for non-ASCII and whitespace)"
8238 )]
8239 EntradaPathInvalid { path: String, reason: String },
8240 #[error(":entrada :paths entry {path:?} appears more than once")]
8241 EntradaPathDuplicate { path: String },
8242 #[error(
8243 ":placement {estrategia} requires at least one :clusters entry \
8244 (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8245 )]
8246 PlacementWithoutClusters { estrategia: PlacementStrategy },
8247 #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8248 PlacementClusterEmpty,
8249 #[error(
8250 ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8251 (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8252 in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8253 future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8254 — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8255 identifier like `\"rio\"` or `\"mar-east\"`)"
8256 )]
8257 PlacementClusterInvalid { cluster: String, reason: String },
8258 #[error(":placement :clusters entry {cluster:?} appears more than once")]
8259 PlacementClusterDuplicate { cluster: String },
8260 #[error(
8261 ":placement :affinity must be non-empty when set (omit :affinity to express \
8262 `no placement hint`)"
8263 )]
8264 PlacementAffinityEmpty,
8265 #[error(
8266 ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8267 (placement hints land verbatim in the M3 Adaptive compression overlay's \
8268 `placement.affinity` field and in every future M4 placement-engine routing \
8269 axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8270 selector — both enforce the DNS-1123 label rule on admission; use a \
8271 lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8272 `\"low-latency\"`, or `\"anti-affinity\"`)"
8273 )]
8274 PlacementAffinityInvalid { affinity: String, reason: String },
8275 #[error(":placement Sharded requires :shard-key")]
8276 ShardedWithoutKey,
8277 #[error(
8278 ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8279 hashes every entity onto the same shard, defeating sharding entirely)"
8280 )]
8281 ShardedKeyEmpty,
8282 #[error(
8283 ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8284 entity-id extractor expression: {reason} (the future M4 Akka-style \
8285 cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8286 as a single-token property reference and hashes the extracted entity ID \
8287 to compute shard placement; use a printable-ASCII extractor expression \
8288 like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8289 `\"${{tenant}}\"`)"
8290 )]
8291 ShardKeyInvalid { shard_key: String, reason: String },
8292 #[error(
8293 ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8294 Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8295 convention); :estrategia Replicated runs every cluster active-active and \
8296 :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8297 distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8298 to :estrategia Sharded if hash-keyed routing is the intent"
8299 )]
8300 ShardKeyOnNonSharded {
8301 estrategia: PlacementStrategy,
8302 shard_key: String,
8303 },
8304 #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8305 ContratoMissingTarget {
8306 de: String,
8307 para: String,
8308 wit: String,
8309 expected: &'static str,
8310 },
8311 #[error(
8312 "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8313 expected `:{expected}` only"
8314 )]
8315 ContratoWrongTarget {
8316 de: String,
8317 para: String,
8318 wit: String,
8319 expected: &'static str,
8320 },
8321 #[error(
8322 "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8323 like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8324 that matches no traffic and silently drops every request)"
8325 )]
8326 ContratoEndpointEmpty { de: String, para: String },
8327 #[error(
8328 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8329 (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8330 :entrada :paths)"
8331 )]
8332 ContratoEndpointNotAbsolute {
8333 de: String,
8334 para: String,
8335 endpoint: String,
8336 },
8337 #[error(
8338 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8339 Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8340 emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8341 caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8342 shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8343 like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8344 and whitespace)"
8345 )]
8346 ContratoEndpointInvalid {
8347 de: String,
8348 para: String,
8349 endpoint: String,
8350 reason: String,
8351 },
8352 #[error(
8353 "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8354 subject is a no-op subscribe; omit :subject only if the WIT world is not \
8355 pub-sub-shaped)"
8356 )]
8357 ContratoSubjectEmpty { de: String, para: String },
8358 #[error(
8359 "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8360 NATS subject: {reason} (the NATS server's subject parser enforces the \
8361 same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8362 single-token and `>` multi-token wildcards — at publish/subscribe time; \
8363 use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8364 `\"orders.*.completed\"` — a malformed subject silently drops every \
8365 message at runtime far from the source caixa.lisp)"
8366 )]
8367 ContratoSubjectInvalid {
8368 de: String,
8369 para: String,
8370 subject: String,
8371 reason: String,
8372 },
8373 #[error(
8374 "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8375 addresses the bucket root, defeating the per-key isolation the slot exists \
8376 for; omit :slot only if the WIT world is not store-shaped)"
8377 )]
8378 ContratoSlotEmpty { de: String, para: String },
8379 #[error(
8380 "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8381 WASI keyvalue store slot template: {reason} (the substrate enforces \
8382 the printable-ASCII intersection-floor every kv backend admits — \
8383 use a single-token path / template expression like `\"checkout/$orderId\"`, \
8384 `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8385 percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8386 slot either gets rejected on write by strict backends or silently \
8387 corrupts the next read on permissive ones, far from the source caixa.lisp)"
8388 )]
8389 ContratoSlotInvalid {
8390 de: String,
8391 para: String,
8392 slot: String,
8393 reason: String,
8394 },
8395 #[error(
8396 "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8397 or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8398 cycle.join(" → ")
8399 )]
8400 ContratoCycle { cycle: Vec<String> },
8401 #[error(
8402 ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8403 than once (the typed graph edges are a set, not a multiset; duplicate \
8404 contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8405 values that K8s admission rejects far from the source caixa.lisp)"
8406 )]
8407 ContratoDuplicate {
8408 de: String,
8409 para: String,
8410 wit: String,
8411 target: String,
8412 },
8413 #[error(
8414 ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8415 contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8416 express `no per-call deadline on this axis`"
8417 )]
8418 PolicyTimeoutZero,
8419 #[error(
8420 ":politicas :retries must be > 0 when set; omit :retries to express \
8421 `no retries on transient failure`"
8422 )]
8423 PolicyRetriesZero,
8424 #[error(
8425 ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8426 (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8427 retry policy into a thundering-herd amplification vector on transient \
8428 failure (one caller request fans out to `(retries+1)^depth` server-side \
8429 calls across the synchronous-:contratos subgraph), exactly the failure \
8430 mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8431 Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8432 or omit :retries to disable retries entirely"
8433 )]
8434 PolicyRetriesExceedsCap { retries: u32 },
8435 #[error(
8436 ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8437 breaker trips on the first call); omit :circuit-breaker to disable it"
8438 )]
8439 PolicyBreakerZeroFailures,
8440 #[error(
8441 ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8442 mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8443 above this cap turns the typed breaker policy into a no-op: the trip \
8444 threshold is structurally so high that no realistic failures-per-:window \
8445 traffic shape can reach it, so the breaker never trips and every typed-slot \
8446 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8447 Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8448 structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8449 Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8450 omit :circuit-breaker to disable the breaker entirely"
8451 )]
8452 PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8453 #[error(
8454 ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8455 tracks no failures); omit :circuit-breaker to disable it"
8456 )]
8457 PolicyBreakerZeroWindow,
8458 #[error(
8459 ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8460 request); omit :rate-limit to disable rate limiting"
8461 )]
8462 PolicyRateLimitZero,
8463 #[error(
8464 ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8465 (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8466 rate-limit policy into a no-op limiter: the token-bucket capacity is \
8467 structurally so high that no realistic per-edge traffic shape can drain it, \
8468 so the limiter never trips and every typed-slot consumer (the future \
8469 CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8470 local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8471 that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8472 Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8473 Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8474 Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8475 to disable rate limiting entirely"
8476 )]
8477 PolicyRateLimitExceedsCap { rate: u32 },
8478 #[error(
8479 ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8480 the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8481 rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8482 non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8483 three canonical windows)"
8484 )]
8485 PolicyRateLimitWindowNotCanonical { window: Duration },
8486 #[error(
8487 ":politicas :timeout must be an integer number of milliseconds — the canonical \
8488 authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8489 duration codec round-trips losslessly; got {timeout:?} which carries a \
8490 sub-millisecond residue that either truncates to a different `Duration` on \
8491 re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8492 to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8493 zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8494 (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8495 )]
8496 PolicyTimeoutNotCanonical { timeout: Duration },
8497 #[error(
8498 ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8499 (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8500 per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8501 overlays carry a deadline so long no realistic synchronous-:contratos \
8502 traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8503 CSE invariant degenerates to enforcement only at the per-Servico \
8504 `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8505 `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8506 (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8507 ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8508 maxes out at the same `3600s` ceiling) or omit :timeout to express \
8509 `no per-call deadline on this axis` (the synchronous-call deadline then \
8510 relies entirely on the per-Servico `:limits :wall-clock` axis)"
8511 )]
8512 PolicyTimeoutExceedsCap { timeout: Duration },
8513 #[error(
8514 ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8515 the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8516 the shared duration codec round-trips losslessly; got {window:?} which carries a \
8517 sub-millisecond residue that either truncates to a different `Duration` on \
8518 re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8519 Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8520 )]
8521 PolicyBreakerWindowNotCanonical { window: Duration },
8522 #[error(
8523 ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8524 (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8525 rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8526 is structurally so long that transient failures are never forgotten, the breaker \
8527 trips once and stays tripped for the lifetime of the component, and every typed-slot \
8528 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8529 outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8530 Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8531 default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8532 the breaker entirely"
8533 )]
8534 PolicyBreakerWindowExceedsCap { window: Duration },
8535}
8536
8537#[cfg(test)]
8538mod tests {
8539 use super::*;
8540
8541 fn membro(name: &str, ver: &str) -> Membro {
8542 Membro {
8543 caixa: name.into(),
8544 versao: ver.into(),
8545 }
8546 }
8547
8548 fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8549 WitContract {
8550 de: de.into(),
8551 para: para.into(),
8552 wit: "wasi:http/proxy".into(),
8553 endpoint: Some(ep.into()),
8554 subject: None,
8555 slot: None,
8556 }
8557 }
8558
8559 fn three_member_spec() -> AplicacaoSpec {
8560 AplicacaoSpec {
8561 membros: vec![
8562 membro("catalog", "^0.1"),
8563 membro("cart", "^0.1"),
8564 membro("payment", "^0.2"),
8565 ],
8566 contratos: vec![
8567 contract_http("cart", "catalog", "/products/:id"),
8568 contract_http("cart", "payment", "/charge"),
8569 ],
8570 politicas: MeshPolicy {
8571 timeout: Some(Duration::from_secs(30)),
8572 retries: Some(3),
8573 mtls_required: Some(true),
8574 ..Default::default()
8575 },
8576 placement: Placement {
8577 estrategia: PlacementStrategy::Replicated,
8578 clusters: vec!["rio".into(), "mar".into()],
8579 affinity: Some("data-locality".into()),
8580 shard_key: None,
8581 },
8582 entrada: Some(Entrada {
8583 host: "checkout.quero.cloud".into(),
8584 para: "cart".into(),
8585 paths: vec!["/api/cart".into(), "/api/products".into()],
8586 port: 8080,
8587 }),
8588 }
8589 }
8590
8591 #[test]
8592 fn happy_path_validates() {
8593 three_member_spec().validate().unwrap();
8594 }
8595
8596 #[test]
8597 fn rejects_empty_membros() {
8598 let mut s = three_member_spec();
8599 s.membros = vec![];
8600 assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8601 }
8602
8603 #[test]
8604 fn rejects_empty_membro_caixa() {
8605 // A `:caixa ""` entry has no name to render into programs.yaml
8606 // and no caixa.lisp to resolve at lacre time.
8607 let mut s = three_member_spec();
8608 s.membros[1].caixa = String::new();
8609 assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8610 }
8611
8612 #[test]
8613 fn rejects_empty_membro_versao() {
8614 // A `:versao ""` entry can't pin a semver constraint, so the
8615 // lacre pipeline fails far from the source.
8616 let mut s = three_member_spec();
8617 s.membros[2].versao = String::new();
8618 let err = s.validate().unwrap_err();
8619 assert!(
8620 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8621 "got {err:?}"
8622 );
8623 }
8624
8625 #[test]
8626 fn rejects_duplicate_membro_caixa() {
8627 // Two `:membros` entries with the same `:caixa` collapse to one
8628 // node in the membership HashSet, which masks `:contratos`
8629 // membership errors and produces duplicate programs.yaml entries.
8630 let mut s = three_member_spec();
8631 s.membros.push(membro("cart", "^0.2"));
8632 let err = s.validate().unwrap_err();
8633 assert!(
8634 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8635 "got {err:?}"
8636 );
8637 }
8638
8639 #[test]
8640 fn rejects_invalid_membro_versao_requirement() {
8641 // The fail-before-pass-after pin: a non-empty but malformed
8642 // semver requirement (`"^bad-version"`) silently passed
8643 // `validate()` on every pre-gate codebase because the prior
8644 // shape only refused the empty string. The parse failure
8645 // surfaced far downstream at lacre-resolve time with a
8646 // `semver::Error` that didn't name which `:membros` entry
8647 // carried the typo. The new gate moves the check to caixa-build
8648 // time at the source caixa.lisp.
8649 let mut s = three_member_spec();
8650 s.membros[2].versao = "^bad-version".into();
8651 let err = s.validate().unwrap_err();
8652 assert!(
8653 matches!(
8654 err,
8655 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8656 if caixa == "payment" && versao == "^bad-version"
8657 ),
8658 "got {err:?}"
8659 );
8660 }
8661
8662 #[test]
8663 fn rejects_membro_versao_with_double_caret_typo() {
8664 // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8665 // Cargo-shaped requirement on first glance but fails the parser
8666 // because semver doesn't accept stacked operators. Pin this
8667 // adjacent-shape footgun explicitly so a future relaxation that
8668 // accepts "looks-canonical-but-isn't" forms surfaces here.
8669 let mut s = three_member_spec();
8670 s.membros[0].versao = "^^0.1".into();
8671 let err = s.validate().unwrap_err();
8672 assert!(
8673 matches!(
8674 err,
8675 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8676 if caixa == "catalog" && versao == "^^0.1"
8677 ),
8678 "got {err:?}"
8679 );
8680 }
8681
8682 #[test]
8683 fn rejects_membro_versao_with_v_prefixed_tag() {
8684 // `"v0.1"` is the canonical "git-tag-shape leaking into the
8685 // semver requirement slot" typo — an author copies the
8686 // publish-side git-tag string verbatim into `:versao`, but
8687 // Cargo's semver parser rejects the leading `v` (only digits +
8688 // canonical operators are valid in the major-version
8689 // position). The gate's diagnostic names which member entry
8690 // carried the v-prefix so the fix is one edit, not a grep
8691 // through every member's `:versao`. (Note: bare `x`-glob
8692 // shorthands like `^0.1.x` are *accepted* by the semver crate
8693 // as an `*` wildcard on the patch axis — they're a Cargo-side
8694 // valid shape, not a typo, so the gate intentionally lets them
8695 // through.)
8696 let mut s = three_member_spec();
8697 s.membros[1].versao = "v0.1".into();
8698 let err = s.validate().unwrap_err();
8699 assert!(
8700 matches!(
8701 err,
8702 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8703 if caixa == "cart" && versao == "v0.1"
8704 ),
8705 "got {err:?}"
8706 );
8707 }
8708
8709 #[test]
8710 fn accepts_canonical_membro_versao_forms() {
8711 // The four Cargo-shaped requirement forms `:deps :versao`
8712 // already accepts via `crate::parse_requirement` must pass the
8713 // membros gate without re-validating at the resolver layer.
8714 // Pin every leg so a future tightening of the canonical set
8715 // surfaces here as a test failure.
8716 for form in [
8717 "^0.1", // caret — minor-range pin (the most common shape)
8718 "~0.1.2", // tilde — patch-range pin
8719 "0.1.0", // exact — single-version pin
8720 "*", // wildcard — explicitly any-version (semver::VersionReq::STAR)
8721 ">=0.1, <2", // multi-range — comma-separated comparators
8722 ] {
8723 let mut s = three_member_spec();
8724 for m in &mut s.membros {
8725 m.versao = form.into();
8726 }
8727 s.validate()
8728 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8729 }
8730 }
8731
8732 #[test]
8733 fn membro_versao_empty_takes_precedence_over_invalid() {
8734 // Order pin: the existing `MembroVersaoEmpty` diagnostic
8735 // (which doesn't try to parse) fires before the new
8736 // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8737 // `:versao` keeps its narrower error message — `parse_requirement`
8738 // would also reject `""`, but the empty-string arm is the more
8739 // self-locating diagnostic for the author.
8740 let mut s = three_member_spec();
8741 s.membros[1].versao = String::new();
8742 let err = s.validate().unwrap_err();
8743 assert!(
8744 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8745 "got {err:?}"
8746 );
8747 }
8748
8749 #[test]
8750 fn membro_versao_invalid_fires_before_duplicate_check() {
8751 // Order pin: a malformed requirement on a non-duplicate entry
8752 // surfaces *its own* diagnostic (which names the offending
8753 // `:versao` string), even when a later entry would otherwise
8754 // collapse onto an earlier name. The per-entry shape gate runs
8755 // inline before the duplicate-key insert, parallel to
8756 // `membros_validation_runs_before_contratos_membership_check`
8757 // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8758 let mut s = three_member_spec();
8759 s.membros[0].versao = "^bad".into();
8760 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8761 let err = s.validate().unwrap_err();
8762 assert!(
8763 matches!(
8764 err,
8765 AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8766 ),
8767 "got {err:?}"
8768 );
8769 }
8770
8771 #[test]
8772 fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8773 // The diagnostic-shape pin: the error names the offending
8774 // `:versao` value verbatim so the author can grep their
8775 // caixa.lisp without re-running the build, and carries a
8776 // non-empty `reason` from `semver::VersionReq::parse` so the
8777 // parser's own wording flows through to the diagnostic.
8778 let mut s = three_member_spec();
8779 s.membros[2].versao = "not-a-req".into();
8780 let err = s.validate().unwrap_err();
8781 let AplicacaoError::MembroVersaoInvalid {
8782 caixa,
8783 versao,
8784 reason,
8785 } = err
8786 else {
8787 panic!("expected MembroVersaoInvalid, got other variant");
8788 };
8789 assert_eq!(caixa, "payment");
8790 assert_eq!(versao, "not-a-req");
8791 assert!(
8792 !reason.is_empty(),
8793 "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8794 );
8795 }
8796
8797 #[test]
8798 fn membro_versao_invalid_runs_before_contratos_check() {
8799 // A malformed `:versao` on any member must surface its own
8800 // diagnostic (which names *which* member to fix) before any
8801 // `:contratos` membership lookup raises `ContratoMemberMissing`.
8802 // The `:contratos` gate runs after `validate_membros`, so this
8803 // is structurally guaranteed — pin it explicitly so a future
8804 // refactor that reorders the gates surfaces here.
8805 let mut s = three_member_spec();
8806 s.membros[1].versao = "^^0.1".into();
8807 // Add a contrato whose `:para` doesn't exist — would normally
8808 // raise ContratoMemberMissing at the membership lookup, but
8809 // the membros gate must fire first.
8810 s.contratos
8811 .push(contract_http("cart", "phantom", "/never-reached"));
8812 let err = s.validate().unwrap_err();
8813 assert!(
8814 matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8815 "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8816 );
8817 }
8818
8819 #[test]
8820 fn membros_validation_runs_before_contratos_membership_check() {
8821 // If `:membros` carries a duplicate, the membership-collapse
8822 // would silently accept a `:contratos :para "phantom"` so long
8823 // as some entry hashes to "phantom". Pinning order: the
8824 // duplicate-membros error fires first, regardless of whether
8825 // contratos reference real members.
8826 let mut s = three_member_spec();
8827 s.membros = vec![
8828 membro("cart", "^0.1"),
8829 membro("cart", "^0.2"),
8830 membro("catalog", "^0.1"),
8831 membro("payment", "^0.1"),
8832 ];
8833 let err = s.validate().unwrap_err();
8834 assert!(
8835 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8836 "got {err:?}"
8837 );
8838 }
8839
8840 #[test]
8841 fn distinct_membros_validate() {
8842 // Pin the happy-path: every `:membros` entry has a non-empty
8843 // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8844 // The fixture already satisfies this; this test makes the
8845 // invariant explicit so a future refactor of the fixture can't
8846 // silently break the guarantee.
8847 three_member_spec().validate().unwrap();
8848 }
8849
8850 // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8851
8852 #[test]
8853 fn rejects_membro_caixa_with_uppercase() {
8854 // The canonical "I copied the Servico's display name verbatim"
8855 // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8856 // but author tools often round-trip a TitleCase or CamelCase
8857 // identifier from an ADR or a sketch. Pin the diagnostic names
8858 // the offending name and suggests the lower-cased fix in one
8859 // edit, mirroring the `rejects_entrada_host_with_uppercase`
8860 // gate's shape (c7d05ec).
8861 let mut s = three_member_spec();
8862 s.membros[1].caixa = "Cart".into();
8863 let err = s.validate().unwrap_err();
8864 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8865 panic!("expected MembroCaixaInvalid, got other variant");
8866 };
8867 assert_eq!(caixa, "Cart");
8868 assert!(
8869 reason.contains("uppercase"),
8870 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8871 );
8872 assert!(
8873 reason.contains("\"cart\""),
8874 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8875 );
8876 }
8877
8878 #[test]
8879 fn rejects_membro_caixa_with_underscore() {
8880 // The canonical "I'm thinking of a Python module / Postgres
8881 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8882 // label schema. K8s rejects `metadata.name: my_cart` at admission
8883 // time with an opaque `field is invalid` (no source-citing
8884 // diagnostic). The gate moves it to caixa-build time.
8885 let mut s = three_member_spec();
8886 s.membros[0].caixa = "my_cart".into();
8887 let err = s.validate().unwrap_err();
8888 assert!(
8889 matches!(
8890 err,
8891 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8892 if caixa == "my_cart" && reason.contains('_')
8893 ),
8894 "got {err:?}"
8895 );
8896 }
8897
8898 #[test]
8899 fn rejects_membro_caixa_with_dot() {
8900 // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
8901 // subdomain — even though K8s `metadata.name` itself accepts
8902 // dots (DNS-1123 subdomain rule), this string also lands as a
8903 // K8s Service name (DNS-1035 label — no dots) and as a label
8904 // value on identity-based Cilium selectors. The strictest floor
8905 // among the use sites wins. The "I want to namespace my member
8906 // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
8907 let mut s = three_member_spec();
8908 s.membros[2].caixa = "team.cart".into();
8909 let err = s.validate().unwrap_err();
8910 assert!(
8911 matches!(
8912 err,
8913 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8914 if caixa == "team.cart" && reason.contains('.')
8915 ),
8916 "got {err:?}"
8917 );
8918 }
8919
8920 #[test]
8921 fn rejects_membro_caixa_with_leading_hyphen() {
8922 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
8923 // with an alphanumeric. The K8s apiserver rejects `-cart`
8924 // outright; the renderer would emit a `metadata.name: "-cart"`
8925 // that fails admission far from the source caixa.lisp.
8926 let mut s = three_member_spec();
8927 s.membros[0].caixa = "-cart".into();
8928 let err = s.validate().unwrap_err();
8929 assert!(
8930 matches!(
8931 err,
8932 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8933 if caixa == "-cart" && reason.contains("start and end")
8934 ),
8935 "got {err:?}"
8936 );
8937 }
8938
8939 #[test]
8940 fn rejects_membro_caixa_with_trailing_hyphen() {
8941 // The symmetric arm of the boundary rule. Pin separately so
8942 // both ends of the label are covered against a future relaxation
8943 // that only checks one boundary.
8944 let mut s = three_member_spec();
8945 s.membros[1].caixa = "cart-".into();
8946 let err = s.validate().unwrap_err();
8947 assert!(
8948 matches!(
8949 err,
8950 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8951 if caixa == "cart-"
8952 ),
8953 "got {err:?}"
8954 );
8955 }
8956
8957 #[test]
8958 fn rejects_membro_caixa_with_unicode() {
8959 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8960 // (`xn--…`) by the author before it reaches K8s. The byte-by-
8961 // byte ASCII validity check rejects multi-byte UTF-8 sequences
8962 // by the first byte that fails the `[a-z0-9-]` predicate.
8963 let mut s = three_member_spec();
8964 s.membros[2].caixa = "café".into();
8965 let err = s.validate().unwrap_err();
8966 assert!(
8967 matches!(
8968 err,
8969 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8970 if caixa == "café"
8971 ),
8972 "got {err:?}"
8973 );
8974 }
8975
8976 #[test]
8977 fn rejects_membro_caixa_with_whitespace() {
8978 // Whitespace is the canonical "I pasted from a sketch / doc"
8979 // footgun. The apiserver rejects every `metadata.name` value
8980 // carrying whitespace; pin the gate fires at the right boundary.
8981 let mut s = three_member_spec();
8982 s.membros[0].caixa = "my cart".into();
8983 let err = s.validate().unwrap_err();
8984 assert!(
8985 matches!(
8986 err,
8987 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8988 if caixa == "my cart"
8989 ),
8990 "got {err:?}"
8991 );
8992 }
8993
8994 #[test]
8995 fn rejects_membro_caixa_too_long() {
8996 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
8997 // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
8998 // exactly. The gate's reason names both the cap and the actual
8999 // length so the author can shorten in one edit.
9000 let mut s = three_member_spec();
9001 let too_long = "a".repeat(64);
9002 s.membros[1].caixa = too_long.clone();
9003 let err = s.validate().unwrap_err();
9004 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9005 panic!("expected MembroCaixaInvalid");
9006 };
9007 assert_eq!(caixa, too_long);
9008 assert!(
9009 reason.contains("63") && reason.contains("64"),
9010 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
9011 );
9012 }
9013
9014 #[test]
9015 fn membro_caixa_max_length_validates() {
9016 // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
9017 // so a future tightening (e.g. dropping to 62) surfaces here as
9018 // a regression, mirroring `entrada_host_max_length_validates`
9019 // (c7d05ec).
9020 let mut s = three_member_spec();
9021 s.membros[2].caixa = "a".repeat(63);
9022 s.entrada.as_mut().unwrap().para = "a".repeat(63);
9023 // remove contratos referencing the renamed member; they'd
9024 // raise ContratoMemberMissing otherwise
9025 s.contratos
9026 .retain(|c| c.de != "payment" && c.para != "payment");
9027 s.validate().unwrap();
9028 }
9029
9030 #[test]
9031 fn accepts_canonical_membro_caixa_forms() {
9032 // The DNS-1123 label shapes a caixa author is realistically
9033 // going to write: single-word lowercase, hyphen-joined, ending
9034 // in a digit-suffixed version (`cart-v2`), starting with a
9035 // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
9036 // DNS-1035 which requires a letter at position 0), single-
9037 // character (`a` — boundary). Pin every leg so a future
9038 // tightening that bans (e.g.) digit-start identifiers surfaces
9039 // here.
9040 for form in [
9041 "checkout",
9042 "cart",
9043 "cart-v2",
9044 "a",
9045 "c0",
9046 "3rd-party-shim",
9047 "x-1-2-3-4",
9048 ] {
9049 let mut s = three_member_spec();
9050 // Renaming a member also requires updating downstream refs;
9051 // drop everything else and rebuild a minimal spec around
9052 // just the one renamed member.
9053 s.membros = vec![membro(form, "^0.1")];
9054 s.contratos = vec![];
9055 s.entrada = None;
9056 s.validate()
9057 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
9058 }
9059 }
9060
9061 #[test]
9062 fn membro_caixa_empty_takes_precedence_over_invalid() {
9063 // Order pin: the existing `MembroCaixaEmpty` diagnostic
9064 // (which doesn't try to parse) fires before the new
9065 // `MembroCaixaInvalid` parse-side diagnostic, so an empty
9066 // `:caixa` keeps its narrower error message — the new gate
9067 // would also reject `""`, but the empty-string arm is the more
9068 // self-locating diagnostic for the author. Mirrors the
9069 // `entrada_host_empty_takes_precedence_over_invalid` pin
9070 // (c7d05ec).
9071 let mut s = three_member_spec();
9072 s.membros[1].caixa = String::new();
9073 let err = s.validate().unwrap_err();
9074 assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
9075 }
9076
9077 #[test]
9078 fn membro_caixa_invalid_fires_before_versao_check() {
9079 // Order pin: an invalid-shape `:caixa` surfaces *its own*
9080 // diagnostic (which names the offending caixa name), even when
9081 // the same entry's `:versao` is also empty/invalid. The shape
9082 // gate runs first because the diagnostic is more self-locating —
9083 // an empty/invalid `:versao` on an invalid-shape caixa name is
9084 // a downstream-fix-after-the-caixa-rename concern.
9085 let mut s = three_member_spec();
9086 s.membros[1].caixa = "Cart".into();
9087 s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
9088 let err = s.validate().unwrap_err();
9089 assert!(
9090 matches!(
9091 err,
9092 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
9093 ),
9094 "got {err:?}"
9095 );
9096 }
9097
9098 #[test]
9099 fn membro_caixa_invalid_fires_before_duplicate_check() {
9100 // Order pin: a malformed-shape `:caixa` on an earlier entry
9101 // surfaces *its own* diagnostic, even when a later entry would
9102 // otherwise collapse onto a duplicate name. The per-entry shape
9103 // gate runs inline before the duplicate-key insert, parallel
9104 // to `membro_versao_invalid_fires_before_duplicate_check`.
9105 let mut s = three_member_spec();
9106 s.membros[0].caixa = "Catalog".into();
9107 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
9108 let err = s.validate().unwrap_err();
9109 assert!(
9110 matches!(
9111 err,
9112 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
9113 ),
9114 "got {err:?}"
9115 );
9116 }
9117
9118 #[test]
9119 fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
9120 // The diagnostic-shape pin: the error names the offending
9121 // `:caixa` value verbatim so the author can grep their
9122 // caixa.lisp without re-running the build, and carries a
9123 // non-empty `reason` naming the specific violation. Same
9124 // shape every typed-shape gate enshrines (c7d05ec's
9125 // `entrada_host_diagnostic_carries_offending_host`,
9126 // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
9127 let mut s = three_member_spec();
9128 s.membros[2].caixa = "BAD_NAME".into();
9129 let err = s.validate().unwrap_err();
9130 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9131 panic!("expected MembroCaixaInvalid");
9132 };
9133 assert_eq!(caixa, "BAD_NAME");
9134 assert!(
9135 !reason.is_empty(),
9136 "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
9137 );
9138 }
9139
9140 #[test]
9141 fn rejects_contrato_with_unknown_de() {
9142 let mut s = three_member_spec();
9143 s.contratos.push(contract_http("phantom", "catalog", "/x"));
9144 let err = s.validate().unwrap_err();
9145 assert!(
9146 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9147 );
9148 }
9149
9150 #[test]
9151 fn rejects_contrato_with_unknown_para() {
9152 let mut s = three_member_spec();
9153 s.contratos.push(contract_http("cart", "phantom", "/x"));
9154 let err = s.validate().unwrap_err();
9155 assert!(
9156 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9157 );
9158 }
9159
9160 #[test]
9161 fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
9162 // The read-path pin: the phantom-`:de` refusal arm's
9163 // `ContratoMemberMissing.caixa` carrier must be observed through
9164 // the lifted [`WitContract::source`] accessor, not the raw
9165 // `.de.clone()` field-access `String`-carry. Peer of the sibling
9166 // per-`:contratos` self-loop arm's `.source().to_string()` /
9167 // `.world_ref().to_string()` `String`-carry sites the earlier
9168 // convergence lifted onto the same accessor pair. A future
9169 // silent detour that reintroduced the raw `.de.clone()` at the
9170 // wrap envelope while the shape-gate and membership lookup
9171 // routed through the accessor would surface here as a byte-equal
9172 // miss between the fired diagnostic's `caixa:` field and the
9173 // offending edge's `.source()` — pinning the accessor as the
9174 // sole read path across the phantom-name refusal arm's arg +
9175 // wrap-envelope emit surface.
9176 let mut s = three_member_spec();
9177 let phantom = contract_http("phantom", "catalog", "/x");
9178 s.contratos.push(phantom.clone());
9179 let err = s.validate().unwrap_err();
9180 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9181 panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
9182 };
9183 assert_eq!(
9184 caixa,
9185 phantom.source(),
9186 "ContratoMemberMissing.caixa on the phantom-:de arm must \
9187 byte-equal WitContract::source — the wrap envelope must \
9188 route through the lifted accessor rather than the raw \
9189 .de.clone() field-access String-carry"
9190 );
9191 }
9192
9193 #[test]
9194 fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9195 // The symmetric read-path pin on the `:para` phantom-name
9196 // refusal arm — same shape as the sibling `:de` pin above but
9197 // on the callee-Servico axis. Pins the wrap envelope's
9198 // `caixa:` field is observed through the lifted
9199 // [`WitContract::destination`] accessor, not the raw
9200 // `.para.clone()` field-access `String`-carry.
9201 let mut s = three_member_spec();
9202 let phantom = contract_http("cart", "phantom", "/x");
9203 s.contratos.push(phantom.clone());
9204 let err = s.validate().unwrap_err();
9205 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9206 panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
9207 };
9208 assert_eq!(
9209 caixa,
9210 phantom.destination(),
9211 "ContratoMemberMissing.caixa on the phantom-:para arm must \
9212 byte-equal WitContract::destination — the wrap envelope \
9213 must route through the lifted accessor rather than the raw \
9214 .para.clone() field-access String-carry"
9215 );
9216 }
9217
9218 #[test]
9219 fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
9220 // The read-path pin on the `:de` DNS-1123-malformed shape-gate
9221 // refusal arm — the `validate_contrato_caixa` arg must be
9222 // observed through the lifted [`WitContract::source`] accessor,
9223 // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
9224 // value routes through the shared
9225 // [`crate::render::require_valid_dns_1123_label`] floor with the
9226 // accessor-projected value; the fired
9227 // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
9228 // the offending edge's `.source()`, pinning that the arg + the
9229 // downstream `caixa: caixa.to_string()` wrap route through the
9230 // same accessor's read path.
9231 let mut s = three_member_spec();
9232 let malformed = contract_http("BAD_NAME", "catalog", "/x");
9233 s.contratos.push(malformed.clone());
9234 let err = s.validate().unwrap_err();
9235 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9236 panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
9237 };
9238 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9239 assert_eq!(
9240 caixa,
9241 malformed.source(),
9242 "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
9243 byte-equal WitContract::source — the shape-gate arg + wrap \
9244 envelope must route through the lifted accessor rather \
9245 than the raw &c.de &String-borrow"
9246 );
9247 }
9248
9249 #[test]
9250 fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9251 // Symmetric arm to the sibling `:de` malformed-shape pin above,
9252 // on the `:para` axis. Pins the shape-gate arg + wrap envelope
9253 // route through the lifted [`WitContract::destination`]
9254 // accessor. `:para` runs after the `:de` shape gate in the
9255 // canonical edge-direction order, so the `:de` value must be
9256 // well-shaped for the `:para` gate to fire — the `cart` :de is
9257 // canonical.
9258 let mut s = three_member_spec();
9259 let malformed = contract_http("cart", "BAD_NAME", "/x");
9260 s.contratos.push(malformed.clone());
9261 let err = s.validate().unwrap_err();
9262 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9263 panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
9264 };
9265 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9266 assert_eq!(
9267 caixa,
9268 malformed.destination(),
9269 "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
9270 byte-equal WitContract::destination — the shape-gate arg + \
9271 wrap envelope must route through the lifted accessor \
9272 rather than the raw &c.para &String-borrow"
9273 );
9274 }
9275
9276 // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
9277
9278 #[test]
9279 fn rejects_contrato_de_empty() {
9280 // `:de ""` previously fell through to `ContratoMemberMissing`
9281 // (with `caixa: ""`) because the validated `:membros :caixa`
9282 // set never contains the empty string. The narrower
9283 // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9284 // the offending slot.
9285 let mut s = three_member_spec();
9286 s.contratos.push(contract_http("", "catalog", "/x"));
9287 let err = s.validate().unwrap_err();
9288 assert_eq!(
9289 err,
9290 AplicacaoError::ContratoCaixaEmpty {
9291 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9292 },
9293 "got {err:?}"
9294 );
9295 }
9296
9297 #[test]
9298 fn rejects_contrato_para_empty() {
9299 // Symmetric arm to `:de ""` — `:para ""` previously fell
9300 // through to `ContratoMemberMissing { caixa: "" }`.
9301 let mut s = three_member_spec();
9302 s.contratos.push(contract_http("cart", "", "/x"));
9303 let err = s.validate().unwrap_err();
9304 assert_eq!(
9305 err,
9306 AplicacaoError::ContratoCaixaEmpty {
9307 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9308 },
9309 "got {err:?}"
9310 );
9311 }
9312
9313 #[test]
9314 fn rejects_contrato_de_with_uppercase() {
9315 // The canonical "I copied the Servico's TitleCase display
9316 // name from an ADR" typo. Until this gate landed `:de "Cart"`
9317 // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9318 // as "this caixa isn't in `:membros`" when the root cause is
9319 // "this `:de` value's shape can never legitimately match a
9320 // validated member (DNS-1123 labels are lowercase)". The
9321 // narrower diagnostic names the offending slot, the value
9322 // verbatim, and the parser-shaped reason.
9323 let mut s = three_member_spec();
9324 s.contratos.push(contract_http("Cart", "catalog", "/x"));
9325 let err = s.validate().unwrap_err();
9326 let AplicacaoError::ContratoCaixaInvalid {
9327 slot,
9328 caixa,
9329 reason,
9330 } = err
9331 else {
9332 panic!("expected ContratoCaixaInvalid, got other variant");
9333 };
9334 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9335 assert_eq!(caixa, "Cart");
9336 assert!(
9337 reason.contains("uppercase"),
9338 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9339 );
9340 }
9341
9342 #[test]
9343 fn rejects_contrato_para_with_underscore() {
9344 // The canonical "I'm thinking of a Python module" leak —
9345 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9346 // Pin the `:para` axis surfaces the same diagnostic shape as
9347 // the `:de` axis on the underscore violation.
9348 let mut s = three_member_spec();
9349 s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9350 let err = s.validate().unwrap_err();
9351 assert!(
9352 matches!(
9353 err,
9354 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9355 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9356 ),
9357 "got {err:?}"
9358 );
9359 }
9360
9361 #[test]
9362 fn rejects_contrato_de_with_dot() {
9363 // A `:contratos :de` value is a single DNS-1123 *label*, not
9364 // a subdomain — mirroring the `:membros :caixa` floor. The
9365 // strictest floor among the use sites wins.
9366 let mut s = three_member_spec();
9367 s.contratos
9368 .push(contract_http("team.cart", "catalog", "/x"));
9369 let err = s.validate().unwrap_err();
9370 assert!(
9371 matches!(
9372 err,
9373 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9374 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9375 ),
9376 "got {err:?}"
9377 );
9378 }
9379
9380 #[test]
9381 fn rejects_contrato_para_with_unicode() {
9382 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9383 // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9384 // validity check rejects multi-byte UTF-8 by the first
9385 // non-`[a-z0-9-]` byte.
9386 let mut s = three_member_spec();
9387 s.contratos.push(contract_http("cart", "café", "/x"));
9388 let err = s.validate().unwrap_err();
9389 assert!(
9390 matches!(
9391 err,
9392 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9393 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9394 ),
9395 "got {err:?}"
9396 );
9397 }
9398
9399 #[test]
9400 fn rejects_contrato_de_with_leading_hyphen() {
9401 // DNS-1123 boundary rule: labels must start and end with an
9402 // alphanumeric. K8s rejects `-cart` outright; the narrower
9403 // shape diagnostic now names the violation at caixa-build
9404 // time rather than the misframed membership-lookup arm.
9405 let mut s = three_member_spec();
9406 s.contratos.push(contract_http("-cart", "catalog", "/x"));
9407 let err = s.validate().unwrap_err();
9408 assert!(
9409 matches!(
9410 err,
9411 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9412 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9413 ),
9414 "got {err:?}"
9415 );
9416 }
9417
9418 #[test]
9419 fn contrato_de_empty_takes_precedence_over_invalid() {
9420 // Order pin: the `ContratoCaixaEmpty` arm fires before the
9421 // `ContratoCaixaInvalid` parse-side arm — same empty-first
9422 // cascade `validate_membro_caixa` / `validate_placement_cluster`
9423 // / `validate_entrada_host` already establish on their peer
9424 // name axes. The empty string is a structurally distinct
9425 // authoring footgun (the author left the field blank, vs.
9426 // typed a malformed value), so it gets its own diagnostic.
9427 let mut s = three_member_spec();
9428 s.contratos.push(contract_http("", "catalog", "/x"));
9429 let err = s.validate().unwrap_err();
9430 assert_eq!(
9431 err,
9432 AplicacaoError::ContratoCaixaEmpty {
9433 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9434 }
9435 );
9436 }
9437
9438 #[test]
9439 fn contrato_de_shape_fires_before_para_shape() {
9440 // Per-axis order pin: within one `:contratos` entry, the `:de`
9441 // shape gate fires before the `:para` shape gate — same
9442 // edge-direction order the existing `ContratoMemberMissing` /
9443 // `ContratoSelfLoop` / target-dispatch checks use, so the
9444 // diagnostic for a contract with both `:de` and `:para`
9445 // malformed is stable. Authors fixing the surfaced `:de`
9446 // first will see `:para`'s diagnostic on re-run.
9447 let mut s = three_member_spec();
9448 s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9449 let err = s.validate().unwrap_err();
9450 assert!(
9451 matches!(
9452 err,
9453 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9454 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9455 ),
9456 "got {err:?}"
9457 );
9458 }
9459
9460 #[test]
9461 fn contrato_shape_fires_before_membership_lookup() {
9462 // The load-bearing pin: an invalid-shape `:de` surfaces its
9463 // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9464 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9465 // an invalid-shape `:de` could never legitimately match any
9466 // member — the prior `ContratoMemberMissing` diagnostic was
9467 // a structural impossibility framed as a graph-membership
9468 // failure. The shape gate now routes every such input through
9469 // the narrower self-locating diagnostic.
9470 let mut s = three_member_spec();
9471 s.contratos.push(contract_http("Cart", "catalog", "/x"));
9472 let err = s.validate().unwrap_err();
9473 assert!(
9474 matches!(
9475 err,
9476 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9477 ),
9478 "got {err:?}"
9479 );
9480 // And the symmetric case: an invalid-shape `:para` surfaces
9481 // its own diagnostic too, even when `:de` is well-shaped.
9482 let mut s = three_member_spec();
9483 s.contratos.push(contract_http("cart", "Catalog", "/x"));
9484 let err = s.validate().unwrap_err();
9485 assert!(
9486 matches!(
9487 err,
9488 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9489 ),
9490 "got {err:?}"
9491 );
9492 }
9493
9494 #[test]
9495 fn contrato_shape_fires_before_self_edge_check() {
9496 // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9497 // bugs: the shape violation (uppercase) and the self-edge
9498 // violation. The narrower per-axis shape diagnostic surfaces
9499 // first because fixing the shape may reveal that the author
9500 // also meant to point `:para` at a different member — the
9501 // self-edge framing is only useful once both endpoints have
9502 // valid shape.
9503 let mut s = three_member_spec();
9504 s.contratos.push(contract_http("Cart", "Cart", "/x"));
9505 let err = s.validate().unwrap_err();
9506 assert!(
9507 matches!(
9508 err,
9509 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9510 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9511 ),
9512 "got {err:?}"
9513 );
9514 }
9515
9516 #[test]
9517 fn contrato_well_shaped_phantom_still_raises_member_missing() {
9518 // Strict-improvement pin: a well-shaped `:de` that simply
9519 // isn't in `:membros` (a phantom reference — author meant
9520 // to add the member but didn't, or renamed and missed an
9521 // update) still surfaces `ContratoMemberMissing`, unchanged.
9522 // The shape gate only intercepts inputs that could never
9523 // legitimately match a validated member; legitimately-shaped
9524 // phantom references remain on the graph-membership axis.
9525 let mut s = three_member_spec();
9526 s.contratos
9527 .push(contract_http("phantom-shim", "catalog", "/x"));
9528 let err = s.validate().unwrap_err();
9529 assert!(
9530 matches!(
9531 err,
9532 AplicacaoError::ContratoMemberMissing { ref caixa }
9533 if caixa == "phantom-shim"
9534 ),
9535 "got {err:?}"
9536 );
9537 }
9538
9539 #[test]
9540 fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9541 // The diagnostic-shape pin: the error names the offending
9542 // slot (`:de` or `:para`) verbatim and the offending value
9543 // verbatim plus a non-empty parser-shaped reason, so the
9544 // author can grep their caixa.lisp for `:de "<name>"` /
9545 // `:para "<name>"` and fix it in one edit. Same diagnostic
9546 // shape as `MembroCaixaInvalid` (3f9d7a0) and
9547 // `PlacementClusterInvalid` (6c8c00b).
9548 let mut s = three_member_spec();
9549 s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9550 let err = s.validate().unwrap_err();
9551 let AplicacaoError::ContratoCaixaInvalid {
9552 slot,
9553 caixa,
9554 reason,
9555 } = err
9556 else {
9557 panic!("expected ContratoCaixaInvalid, got {err:?}");
9558 };
9559 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9560 assert_eq!(caixa, "BAD_NAME");
9561 assert!(
9562 !reason.is_empty(),
9563 "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9564 );
9565 }
9566
9567 #[test]
9568 fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9569 // Scalar-value pin: the two author-facing kebab-case labels the
9570 // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9571 // admits on the `:contratos` per-entry endpoint-shape axis,
9572 // one arm per typed sub-slot. Mirrors the peer scalar-value
9573 // pin the sibling top-level M2 / M3 / Supervisor
9574 // author-facing-label consts carry
9575 // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9576 // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9577 // slot itself), so every altitude of the typed-slot algebra
9578 // shares the same "one canonical byte-string per arm"
9579 // discipline. A future rebrand (`:de` → `:from` matching the
9580 // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9581 // sibling, `:para` → `:to` matching the same, or
9582 // `:de`/`:para` → `:source`/`:target` matching the WIT
9583 // world's `import`/`export` half-vocabulary) lands as an
9584 // edit to exactly one const, and every consumer that reaches
9585 // for the label picks it up at build time rather than at
9586 // runtime as a downstream `ContratoCaixaEmpty` /
9587 // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9588 // diagnostic mismatch far from the rename's commit.
9589 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9590 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9591 }
9592
9593 #[test]
9594 fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9595 // Production-through-const pin: the two per-axis labels the
9596 // per-`:contratos` entry endpoint-shape gate at
9597 // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9598 // argument to [`validate_contrato_caixa`] route through the
9599 // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9600 // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9601 // future rebrand that reaches the const but not the gate (or
9602 // vice versa) surfaces here at build time rather than at
9603 // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9604 // `slot: <stale-kebab-case>` diagnostic far from the rename's
9605 // commit. Mirror of the peer
9606 // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9607 // pin (882f498) on the sibling M3 top-level slot axis.
9608 let mut s = three_member_spec();
9609 s.contratos.push(contract_http("", "catalog", "/x"));
9610 assert_eq!(
9611 s.validate().unwrap_err(),
9612 AplicacaoError::ContratoCaixaEmpty {
9613 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9614 }
9615 );
9616 let mut s = three_member_spec();
9617 s.contratos.push(contract_http("cart", "", "/x"));
9618 assert_eq!(
9619 s.validate().unwrap_err(),
9620 AplicacaoError::ContratoCaixaEmpty {
9621 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9622 }
9623 );
9624 }
9625
9626 #[test]
9627 fn accepts_canonical_contrato_caixa_forms() {
9628 // The DNS-1123 label shapes a caixa author is realistically
9629 // going to write on a `:contratos :de` / `:para`. Pin every
9630 // leg so a future tightening that bans (e.g.) digit-start
9631 // identifiers surfaces here, mirroring
9632 // `accepts_canonical_membro_caixa_forms` on the peer name
9633 // axis.
9634 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9635 let mut s = three_member_spec();
9636 s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9637 s.contratos = vec![contract_http("checkout", form, "/x")];
9638 s.entrada = None;
9639 s.validate().unwrap_or_else(|e| {
9640 panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9641 });
9642
9643 let mut s = three_member_spec();
9644 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9645 s.contratos = vec![contract_http(form, "catalog", "/x")];
9646 s.entrada = None;
9647 s.validate().unwrap_or_else(|e| {
9648 panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9649 });
9650 }
9651 }
9652
9653 #[test]
9654 fn rejects_empty_wit() {
9655 let mut s = three_member_spec();
9656 s.contratos.push(WitContract {
9657 de: "cart".into(),
9658 para: "catalog".into(),
9659 wit: "".into(),
9660 endpoint: None,
9661 subject: None,
9662 slot: None,
9663 });
9664 let err = s.validate().unwrap_err();
9665 assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9666 }
9667
9668 #[test]
9669 fn rejects_entrada_to_unknown_member() {
9670 let mut s = three_member_spec();
9671 s.entrada.as_mut().unwrap().para = "phantom".into();
9672 assert!(matches!(
9673 s.validate().unwrap_err(),
9674 AplicacaoError::EntradaMemberMissing { .. }
9675 ));
9676 }
9677
9678 // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9679
9680 #[test]
9681 fn rejects_entrada_para_empty() {
9682 // `:para ""` previously fell through to
9683 // `EntradaMemberMissing { para: "" }` because the validated
9684 // `:membros :caixa` set never contains the empty string. The
9685 // narrower `EntradaParaEmpty` diagnostic now names the
9686 // offending slot directly — same empty-first cascade
9687 // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9688 // `ContratoCaixaEmpty` establish on the peer name axes.
9689 let mut s = three_member_spec();
9690 s.entrada.as_mut().unwrap().para = String::new();
9691 let err = s.validate().unwrap_err();
9692 assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9693 }
9694
9695 #[test]
9696 fn rejects_entrada_para_with_uppercase() {
9697 // The canonical "I copied the Servico's TitleCase display
9698 // name from an ADR" typo. Until this gate landed `:para "Cart"`
9699 // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9700 // as "this caixa isn't in `:membros`" when the root cause is
9701 // "this `:para` value's shape can never legitimately match a
9702 // validated member (DNS-1123 labels are lowercase)". The
9703 // narrower diagnostic names the value verbatim plus the
9704 // parser-shaped reason.
9705 let mut s = three_member_spec();
9706 s.entrada.as_mut().unwrap().para = "Cart".into();
9707 let err = s.validate().unwrap_err();
9708 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9709 panic!("expected EntradaParaInvalid, got other variant");
9710 };
9711 assert_eq!(para, "Cart");
9712 assert!(
9713 reason.contains("uppercase"),
9714 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9715 );
9716 }
9717
9718 #[test]
9719 fn rejects_entrada_para_with_underscore() {
9720 // The canonical "I'm thinking of a Python module" leak —
9721 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9722 let mut s = three_member_spec();
9723 s.entrada.as_mut().unwrap().para = "my_cart".into();
9724 let err = s.validate().unwrap_err();
9725 assert!(
9726 matches!(
9727 err,
9728 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9729 if para == "my_cart" && reason.contains('_')
9730 ),
9731 "got {err:?}"
9732 );
9733 }
9734
9735 #[test]
9736 fn rejects_entrada_para_with_dot() {
9737 // An `:entrada :para` value is a single DNS-1123 *label*, not
9738 // a subdomain — mirroring the `:membros :caixa` floor. The
9739 // strictest floor among the use sites wins.
9740 let mut s = three_member_spec();
9741 s.entrada.as_mut().unwrap().para = "team.cart".into();
9742 let err = s.validate().unwrap_err();
9743 assert!(
9744 matches!(
9745 err,
9746 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9747 if para == "team.cart" && reason.contains('.')
9748 ),
9749 "got {err:?}"
9750 );
9751 }
9752
9753 #[test]
9754 fn rejects_entrada_para_with_unicode() {
9755 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9756 // (`xn--…`) before it reaches K8s.
9757 let mut s = three_member_spec();
9758 s.entrada.as_mut().unwrap().para = "café".into();
9759 let err = s.validate().unwrap_err();
9760 assert!(
9761 matches!(
9762 err,
9763 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9764 ),
9765 "got {err:?}"
9766 );
9767 }
9768
9769 #[test]
9770 fn rejects_entrada_para_with_leading_hyphen() {
9771 // DNS-1123 boundary rule: labels must start and end with an
9772 // alphanumeric. K8s rejects `-cart` outright.
9773 let mut s = three_member_spec();
9774 s.entrada.as_mut().unwrap().para = "-cart".into();
9775 let err = s.validate().unwrap_err();
9776 assert!(
9777 matches!(
9778 err,
9779 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9780 if para == "-cart" && reason.contains("start and end")
9781 ),
9782 "got {err:?}"
9783 );
9784 }
9785
9786 #[test]
9787 fn rejects_entrada_para_with_trailing_hyphen() {
9788 // Symmetric boundary arm.
9789 let mut s = three_member_spec();
9790 s.entrada.as_mut().unwrap().para = "cart-".into();
9791 let err = s.validate().unwrap_err();
9792 assert!(
9793 matches!(
9794 err,
9795 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9796 if para == "cart-" && reason.contains("start and end")
9797 ),
9798 "got {err:?}"
9799 );
9800 }
9801
9802 #[test]
9803 fn rejects_entrada_para_too_long() {
9804 // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9805 // bytes per label. K8s rejects longer names at admission on
9806 // every `metadata.name` axis.
9807 let mut s = three_member_spec();
9808 s.entrada.as_mut().unwrap().para = "a".repeat(64);
9809 let err = s.validate().unwrap_err();
9810 assert!(
9811 matches!(
9812 err,
9813 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9814 if para.len() == 64 && reason.contains("max length")
9815 ),
9816 "got {err:?}"
9817 );
9818 }
9819
9820 #[test]
9821 fn entrada_para_empty_takes_precedence_over_invalid() {
9822 // Order pin: the `EntradaParaEmpty` arm fires before the
9823 // `EntradaParaInvalid` parse-side arm — same empty-first
9824 // cascade `validate_membro_caixa` / `validate_placement_cluster`
9825 // / `validate_contrato_caixa` already establish.
9826 let mut s = three_member_spec();
9827 s.entrada.as_mut().unwrap().para = String::new();
9828 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
9829 }
9830
9831 #[test]
9832 fn entrada_para_shape_fires_before_membership_lookup() {
9833 // The load-bearing pin: an invalid-shape `:para` surfaces its
9834 // *own* diagnostic, not the misframed `EntradaMemberMissing`.
9835 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9836 // an invalid-shape `:para` could never legitimately match any
9837 // member — the prior `EntradaMemberMissing` diagnostic framed
9838 // a structural impossibility as a graph-membership failure.
9839 let mut s = three_member_spec();
9840 s.entrada.as_mut().unwrap().para = "Cart".into();
9841 let err = s.validate().unwrap_err();
9842 assert!(
9843 matches!(
9844 err,
9845 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9846 ),
9847 "got {err:?}"
9848 );
9849 }
9850
9851 #[test]
9852 fn entrada_para_shape_fires_before_host_gate() {
9853 // Per-`:entrada` order pin: the `:para` shape gate fires
9854 // before the `:host` gate, mirroring the existing
9855 // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9856 // ordering where the member-lookup arm preceded the host gate.
9857 // The shape gate slots ahead of that, so a malformed `:para`
9858 // surfaces its own diagnostic even when `:host` is also wrong.
9859 let mut s = three_member_spec();
9860 let e = s.entrada.as_mut().unwrap();
9861 e.para = "Cart".into();
9862 e.host = "BAD HOST".into();
9863 let err = s.validate().unwrap_err();
9864 assert!(
9865 matches!(
9866 err,
9867 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9868 ),
9869 "got {err:?}"
9870 );
9871 }
9872
9873 #[test]
9874 fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9875 // Strict-improvement pin: a well-shaped `:para` that simply
9876 // isn't in `:membros` (a phantom reference — author meant to
9877 // add the member but didn't, or renamed and missed an
9878 // update) still surfaces `EntradaMemberMissing`, unchanged.
9879 // The shape gate only intercepts inputs that could never
9880 // legitimately match a validated member.
9881 let mut s = three_member_spec();
9882 s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9883 let err = s.validate().unwrap_err();
9884 assert!(
9885 matches!(
9886 err,
9887 AplicacaoError::EntradaMemberMissing { ref para }
9888 if para == "phantom-shim"
9889 ),
9890 "got {err:?}"
9891 );
9892 }
9893
9894 #[test]
9895 fn entrada_para_invalid_diagnostic_carries_offending_para() {
9896 // The diagnostic-shape pin: the error names the offending
9897 // `:para` value verbatim plus a non-empty parser-shaped
9898 // reason, so the author can grep their caixa.lisp for
9899 // `:para "<name>"` and fix it in one edit. Same diagnostic
9900 // shape as `MembroCaixaInvalid` (3f9d7a0),
9901 // `PlacementClusterInvalid` (6c8c00b), and
9902 // `ContratoCaixaInvalid` (8d5af6b).
9903 let mut s = three_member_spec();
9904 s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
9905 let err = s.validate().unwrap_err();
9906 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9907 panic!("expected EntradaParaInvalid, got {err:?}");
9908 };
9909 assert_eq!(para, "BAD_NAME");
9910 assert!(
9911 !reason.is_empty(),
9912 "EntradaParaInvalid `reason` must carry a parser-shaped wording"
9913 );
9914 }
9915
9916 #[test]
9917 fn accepts_canonical_entrada_para_forms() {
9918 // Positive-control sweep covering the DNS-1123 label shapes a
9919 // caixa author is realistically going to write on `:entrada
9920 // :para`. Pin every leg so a future tightening that bans
9921 // (e.g.) digit-start identifiers surfaces here, mirroring
9922 // `accepts_canonical_membro_caixa_forms` and
9923 // `accepts_canonical_contrato_caixa_forms` on the peer name
9924 // axes.
9925 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9926 let mut s = three_member_spec();
9927 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9928 s.contratos = vec![contract_http(form, "catalog", "/x")];
9929 s.entrada = Some(Entrada {
9930 host: "checkout.quero.cloud".into(),
9931 para: form.into(),
9932 paths: vec!["/api".into()],
9933 port: 8080,
9934 });
9935 s.validate().unwrap_or_else(|e| {
9936 panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
9937 });
9938 }
9939 }
9940
9941 #[test]
9942 fn rejects_replicated_without_clusters() {
9943 let mut s = three_member_spec();
9944 s.placement.clusters = vec![];
9945 assert!(matches!(
9946 s.validate().unwrap_err(),
9947 AplicacaoError::PlacementWithoutClusters { .. }
9948 ));
9949 }
9950
9951 #[test]
9952 fn rejects_sharded_without_key() {
9953 let mut s = three_member_spec();
9954 s.placement.estrategia = PlacementStrategy::Sharded;
9955 s.placement.shard_key = None;
9956 s.placement.clusters = vec!["rio".into()];
9957 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
9958 }
9959
9960 #[test]
9961 fn sharded_with_key_validates() {
9962 let mut s = three_member_spec();
9963 s.placement.estrategia = PlacementStrategy::Sharded;
9964 s.placement.shard_key = Some("$tenantId".into());
9965 s.validate().unwrap();
9966 }
9967
9968 #[test]
9969 fn round_trip_via_json_preserves_shape() {
9970 let s = three_member_spec();
9971 let json = serde_json::to_string(&s.membros).unwrap();
9972 let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
9973 assert_eq!(back, s.membros);
9974
9975 let json = serde_json::to_string(&s.contratos).unwrap();
9976 let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
9977 assert_eq!(back, s.contratos);
9978
9979 let json = serde_json::to_string(&s.placement).unwrap();
9980 let back: Placement = serde_json::from_str(&json).unwrap();
9981 assert_eq!(back, s.placement);
9982
9983 let json = serde_json::to_string(&s.entrada).unwrap();
9984 let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
9985 assert_eq!(back, s.entrada);
9986 }
9987
9988 #[test]
9989 fn rate_limit_round_trip_seconds() {
9990 let policy = MeshPolicy {
9991 rate_limit: Some(RateLimit {
9992 rate: 100,
9993 window: Duration::from_secs(1),
9994 }),
9995 ..Default::default()
9996 };
9997 let json = serde_json::to_string(&policy).unwrap();
9998 assert!(json.contains("\"100/s\""));
9999 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10000 assert_eq!(back.rate_limit.unwrap().rate, 100);
10001 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
10002 }
10003
10004 #[test]
10005 fn rate_limit_round_trip_minutes() {
10006 let policy = MeshPolicy {
10007 rate_limit: Some(RateLimit {
10008 rate: 5000,
10009 window: Duration::from_secs(60),
10010 }),
10011 ..Default::default()
10012 };
10013 let json = serde_json::to_string(&policy).unwrap();
10014 assert!(json.contains("\"5000/m\""));
10015 }
10016
10017 #[test]
10018 fn circuit_breaker_round_trip() {
10019 let policy = MeshPolicy {
10020 circuit_breaker: Some(CircuitBreaker {
10021 max_failures: 5,
10022 window: Duration::from_secs(60),
10023 }),
10024 ..Default::default()
10025 };
10026 let json = serde_json::to_string(&policy).unwrap();
10027 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10028 assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
10029 assert_eq!(
10030 back.circuit_breaker.unwrap().window,
10031 Duration::from_secs(60)
10032 );
10033 }
10034
10035 #[test]
10036 fn rejects_http_contrato_without_endpoint() {
10037 let mut s = three_member_spec();
10038 s.contratos.push(WitContract {
10039 de: "cart".into(),
10040 para: "catalog".into(),
10041 wit: "wasi:http/proxy".into(),
10042 endpoint: None,
10043 subject: None,
10044 slot: None,
10045 });
10046 let err = s.validate().unwrap_err();
10047 assert!(matches!(
10048 err,
10049 AplicacaoError::ContratoMissingTarget {
10050 expected: WitTarget::HTTP_FIELD_NAME,
10051 ..
10052 }
10053 ));
10054 }
10055
10056 #[test]
10057 fn rejects_http_contrato_with_subject() {
10058 let mut s = three_member_spec();
10059 s.contratos.push(WitContract {
10060 de: "cart".into(),
10061 para: "catalog".into(),
10062 wit: "wasi:http/proxy".into(),
10063 endpoint: Some("/x".into()),
10064 subject: Some("not.allowed.here".into()),
10065 slot: None,
10066 });
10067 let err = s.validate().unwrap_err();
10068 assert!(matches!(
10069 err,
10070 AplicacaoError::ContratoWrongTarget {
10071 expected: WitTarget::HTTP_FIELD_NAME,
10072 ..
10073 }
10074 ));
10075 }
10076
10077 #[test]
10078 fn rejects_pubsub_contrato_without_subject() {
10079 let mut s = three_member_spec();
10080 s.contratos.push(WitContract {
10081 de: "cart".into(),
10082 para: "catalog".into(),
10083 wit: "nats:pub-sub".into(),
10084 endpoint: None,
10085 subject: None,
10086 slot: None,
10087 });
10088 let err = s.validate().unwrap_err();
10089 assert!(matches!(
10090 err,
10091 AplicacaoError::ContratoMissingTarget {
10092 expected: WitTarget::PUBSUB_FIELD_NAME,
10093 ..
10094 }
10095 ));
10096 }
10097
10098 #[test]
10099 fn rejects_pubsub_contrato_with_endpoint() {
10100 let mut s = three_member_spec();
10101 s.contratos.push(WitContract {
10102 de: "cart".into(),
10103 para: "catalog".into(),
10104 wit: "kafka:topic".into(),
10105 endpoint: Some("/wrong".into()),
10106 subject: Some("topic.x".into()),
10107 slot: None,
10108 });
10109 let err = s.validate().unwrap_err();
10110 assert!(matches!(
10111 err,
10112 AplicacaoError::ContratoWrongTarget {
10113 expected: WitTarget::PUBSUB_FIELD_NAME,
10114 ..
10115 }
10116 ));
10117 }
10118
10119 #[test]
10120 fn rejects_store_contrato_without_slot() {
10121 let mut s = three_member_spec();
10122 s.contratos.push(WitContract {
10123 de: "cart".into(),
10124 para: "catalog".into(),
10125 wit: "wasi:keyvalue/store".into(),
10126 endpoint: None,
10127 subject: None,
10128 slot: None,
10129 });
10130 let err = s.validate().unwrap_err();
10131 assert!(matches!(
10132 err,
10133 AplicacaoError::ContratoMissingTarget {
10134 expected: WitTarget::STORE_FIELD_NAME,
10135 ..
10136 }
10137 ));
10138 }
10139
10140 // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
10141
10142 #[test]
10143 fn rejects_http_contrato_with_empty_endpoint() {
10144 // `Some("")` for an HTTP endpoint passes the presence check
10145 // (target() previously returned WitTarget::Http { endpoint: "" })
10146 // but renders as a `path: ""` Cilium L7 rule that matches no
10147 // traffic. Same value-shape footgun closed for :entrada :paths
10148 // entries (eb3456d).
10149 let mut s = three_member_spec();
10150 s.contratos.push(WitContract {
10151 de: "cart".into(),
10152 para: "catalog".into(),
10153 wit: "wasi:http/proxy".into(),
10154 endpoint: Some(String::new()),
10155 subject: None,
10156 slot: None,
10157 });
10158 let err = s.validate().unwrap_err();
10159 assert!(
10160 matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
10161 if de == "cart" && para == "catalog"),
10162 "got {err:?}"
10163 );
10164 }
10165
10166 #[test]
10167 fn rejects_http_contrato_with_relative_endpoint() {
10168 // Cilium L7 :path + Gateway API PathPrefix both require a
10169 // leading `/`. Same shape required of :entrada :paths
10170 // (eb3456d). Lifted into target() so every consumer of the
10171 // typed WitTarget view inherits the guarantee.
10172 let mut s = three_member_spec();
10173 s.contratos.push(WitContract {
10174 de: "cart".into(),
10175 para: "catalog".into(),
10176 wit: "wasi:http/proxy".into(),
10177 endpoint: Some("products/:id".into()),
10178 subject: None,
10179 slot: None,
10180 });
10181 let err = s.validate().unwrap_err();
10182 assert!(
10183 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10184 if endpoint == "products/:id"),
10185 "got {err:?}"
10186 );
10187 }
10188
10189 #[test]
10190 fn rejects_pubsub_contrato_with_empty_subject() {
10191 // NATS / Kafka publish without a subject is a no-op subscribe;
10192 // never the author's intent. Same empty-string rejection as
10193 // :membros :caixa, :placement :clusters entries, :entrada
10194 // :paths entries — every value carried by every typed slot is
10195 // value-shape-checked at validate().
10196 let mut s = three_member_spec();
10197 s.contratos.push(WitContract {
10198 de: "cart".into(),
10199 para: "catalog".into(),
10200 wit: "nats:pub-sub".into(),
10201 endpoint: None,
10202 subject: Some(String::new()),
10203 slot: None,
10204 });
10205 let err = s.validate().unwrap_err();
10206 assert!(
10207 matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
10208 if de == "cart" && para == "catalog"),
10209 "got {err:?}"
10210 );
10211 }
10212
10213 #[test]
10214 fn rejects_store_contrato_with_empty_slot() {
10215 // An empty slot template addresses the bucket root, defeating
10216 // the per-key isolation the slot exists for — a footgun on
10217 // `wasi:keyvalue/store` whose closest analog is the empty
10218 // shard-key rejected on :placement Sharded (c7c7799).
10219 let mut s = three_member_spec();
10220 s.contratos.push(WitContract {
10221 de: "cart".into(),
10222 para: "catalog".into(),
10223 wit: "wasi:keyvalue/store".into(),
10224 endpoint: None,
10225 subject: None,
10226 slot: Some(String::new()),
10227 });
10228 let err = s.validate().unwrap_err();
10229 assert!(
10230 matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
10231 if de == "cart" && para == "catalog"),
10232 "got {err:?}"
10233 );
10234 }
10235
10236 #[test]
10237 fn http_contrato_root_endpoint_validates() {
10238 // Pin the boundary case: a single-`/` endpoint is the catch-all
10239 // form the Gateway HTTPRoute renderer falls back to when
10240 // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
10241 // must remain a valid contrato endpoint too.
10242 let mut s = three_member_spec();
10243 s.contratos.push(contract_http("cart", "catalog", "/"));
10244 s.validate().unwrap();
10245 }
10246
10247 // ── :contratos :endpoint value-shape gate ────────────────────────────
10248 //
10249 // Mirrors the `:entrada :paths` value-shape suite on the peer
10250 // HTTP-path axis. Until this gate landed `WitContract::target()`
10251 // only refused the empty string + the missing-leading-`/` form
10252 // (c4213a4); a structurally invalid endpoint passed validate and
10253 // landed verbatim as a Cilium L7 `path:` rule
10254 // (caixa-mesh/src/lib.rs:311) that either silently dropped all
10255 // traffic or was rejected at apply time by Cilium policy admission.
10256 // Every authoring footgun the K8s Gateway API webhook / Cilium
10257 // policy validator would catch on admission now becomes a caixa-
10258 // build-time `ContratoEndpointInvalid` with the offending
10259 // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
10260 // shape as `EntradaPathInvalid` on the sibling axis; same shared
10261 // predicate (`crate::render::is_gateway_api_http_path`) ensures
10262 // drift between the two axes' rule enforcement is a build error
10263 // at the predicate.
10264
10265 fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
10266 // Fresh spec per call so the would-be-duplicate edge
10267 // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
10268 // `three_member_spec`'s pre-existing
10269 // `(cart, catalog, …, /products/:id)` entry — only the
10270 // endpoint payload differs.
10271 let mut s = three_member_spec();
10272 s.contratos.push(contract_http("cart", "catalog", ep));
10273 s.validate().unwrap_err()
10274 }
10275
10276 #[test]
10277 fn rejects_http_contrato_endpoint_with_query() {
10278 // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
10279 // silently rendered as a Cilium L7 `path: "/charge?token=X"`
10280 // rule the L7 matcher would never satisfy.
10281 let err = contrato_endpoint_err("/charge?token=X");
10282 assert!(
10283 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10284 if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10285 "got {err:?}"
10286 );
10287 }
10288
10289 #[test]
10290 fn rejects_http_contrato_endpoint_with_fragment() {
10291 let err = contrato_endpoint_err("/charge#frag");
10292 assert!(
10293 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10294 if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10295 "got {err:?}"
10296 );
10297 }
10298
10299 #[test]
10300 fn rejects_http_contrato_endpoint_with_whitespace() {
10301 let err = contrato_endpoint_err("/foo bar");
10302 assert!(
10303 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10304 if endpoint == "/foo bar" && reason.contains("whitespace")),
10305 "got {err:?}"
10306 );
10307 }
10308
10309 #[test]
10310 fn rejects_http_contrato_endpoint_with_control_char() {
10311 let err = contrato_endpoint_err("/api/\x01bar");
10312 assert!(
10313 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10314 if endpoint == "/api/\x01bar" && reason.contains("control character")),
10315 "got {err:?}"
10316 );
10317 }
10318
10319 #[test]
10320 fn rejects_http_contrato_endpoint_with_non_ascii() {
10321 let err = contrato_endpoint_err("/api/café");
10322 assert!(
10323 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10324 if endpoint == "/api/café" && reason.contains("non-ASCII")),
10325 "got {err:?}"
10326 );
10327 }
10328
10329 #[test]
10330 fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10331 let err = contrato_endpoint_err("/api//cart");
10332 assert!(
10333 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10334 if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10335 "got {err:?}"
10336 );
10337 }
10338
10339 #[test]
10340 fn rejects_http_contrato_endpoint_with_dot_segment() {
10341 let err = contrato_endpoint_err("/api/./cart");
10342 assert!(
10343 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10344 if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10345 "got {err:?}"
10346 );
10347 }
10348
10349 #[test]
10350 fn rejects_http_contrato_endpoint_with_parent_segment() {
10351 // Path-traversal in a contrato endpoint is the canonical
10352 // "L7 rule that the workload's HTTP server's path-resolution
10353 // logic interprets differently than the policy enforcer"
10354 // footgun. Rejected outright at validate time.
10355 let err = contrato_endpoint_err("/api/../etc");
10356 assert!(
10357 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10358 if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10359 "got {err:?}"
10360 );
10361 }
10362
10363 #[test]
10364 fn rejects_http_contrato_endpoint_too_long() {
10365 // 1025-byte endpoint — one over the Gateway API
10366 // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10367 // path matcher has no inherent length limit but the policy
10368 // CR itself rides through the K8s apiserver, which enforces
10369 // ConfigMap-shaped limits; sharing the Gateway API cap is the
10370 // conservative floor.
10371 let big = format!("/api/{}", "a".repeat(1020));
10372 assert_eq!(big.len(), 1025);
10373 let err = contrato_endpoint_err(&big);
10374 assert!(
10375 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10376 if endpoint == &big && reason.contains("max length of 1024")),
10377 "got {err:?}"
10378 );
10379 }
10380
10381 #[test]
10382 fn http_contrato_endpoint_max_length_validates() {
10383 // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10384 // in the cap surfaces here and at
10385 // `rejects_http_contrato_endpoint_too_long` simultaneously,
10386 // mirroring `entrada_path_max_length_validates` on the peer
10387 // axis.
10388 let big = format!("/api/{}", "a".repeat(1019));
10389 assert_eq!(big.len(), 1024);
10390 let mut s = three_member_spec();
10391 s.contratos.push(contract_http("cart", "catalog", &big));
10392 s.validate().unwrap();
10393 }
10394
10395 #[test]
10396 fn http_contrato_endpoint_accepts_canonical_forms() {
10397 // Positive-set sweep: every canonical HTTP-path shape the
10398 // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10399 // plain paths, hidden-file-style `.config` segments distinct
10400 // from the `.` segment, digit-bearing segments, the canonical
10401 // route-template `:param` form, trailing-slash form,
10402 // percent-encoded segments, the `/foo..bar` interior-`..`-
10403 // substring forms that are NOT `..` segments) must remain a
10404 // valid contrato endpoint too. Drift between this list and
10405 // the entrada path positive sweep surfaces at the shared
10406 // `is_gateway_api_http_path` substrate-side suite — one
10407 // source of truth. Uses a fresh `(payment, catalog)` edge so
10408 // none of the swept endpoints collide with the pre-existing
10409 // `(cart, catalog, /products/:id)` / `(cart, payment,
10410 // /charge)` entries in `three_member_spec`.
10411 for ep in [
10412 "/",
10413 "/charge",
10414 "/v1/charge",
10415 "/api/.config",
10416 "/products/:id",
10417 "/api/cart/",
10418 "/api/caf%C3%A9",
10419 "/foo..bar",
10420 "/...",
10421 ] {
10422 let mut s = three_member_spec();
10423 s.contratos.push(contract_http("payment", "catalog", ep));
10424 s.validate()
10425 .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10426 }
10427 }
10428
10429 #[test]
10430 fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10431 // Ordering pin: `ContratoEndpointEmpty` is the more self-
10432 // locating diagnostic on `""` and must lead — the value-
10433 // shape gate is only reached after the empty-check fires.
10434 // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10435 // on the peer axis.
10436 let mut s = three_member_spec();
10437 s.contratos.push(WitContract {
10438 de: "cart".into(),
10439 para: "catalog".into(),
10440 wit: "wasi:http/proxy".into(),
10441 endpoint: Some(String::new()),
10442 subject: None,
10443 slot: None,
10444 });
10445 let err = s.validate().unwrap_err();
10446 assert!(
10447 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10448 "got {err:?}"
10449 );
10450 }
10451
10452 #[test]
10453 fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10454 // Ordering pin: an endpoint without a leading `/` surfaces the
10455 // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10456 // value-shape gate is only consulted on endpoints that already
10457 // satisfy the absolute-prefix invariant. Mirrors
10458 // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10459 let err = contrato_endpoint_err("bad path");
10460 assert!(
10461 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10462 if endpoint == "bad path"),
10463 "got {err:?}"
10464 );
10465 }
10466
10467 #[test]
10468 fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10469 // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10470 // `:para` + a non-empty reason flow through verbatim so the
10471 // author can grep their caixa.lisp for the offending contrato
10472 // block and fix it in one edit. Same shape as
10473 // `entrada_path_diagnostic_carries_offending_path`.
10474 let err = contrato_endpoint_err("/api?q=1");
10475 match err {
10476 AplicacaoError::ContratoEndpointInvalid {
10477 de,
10478 para,
10479 endpoint,
10480 reason,
10481 } => {
10482 assert_eq!(de, "cart");
10483 assert_eq!(para, "catalog");
10484 assert_eq!(endpoint, "/api?q=1");
10485 assert!(!reason.is_empty(), "reason field must be non-empty");
10486 }
10487 other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10488 }
10489 }
10490
10491 #[test]
10492 fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10493 // The compounding theorem: every &str inside a WitTarget
10494 // returned by target() is non-empty (and absolute, for Http).
10495 // Renderers downstream of typed_view() can rely on this
10496 // without re-checking — the type system carries the proof.
10497 let http = contract_http("cart", "catalog", "/x");
10498 match http.target().unwrap() {
10499 WitTarget::Http { endpoint } => {
10500 assert!(!endpoint.is_empty());
10501 assert!(endpoint.starts_with('/'));
10502 }
10503 other => panic!("expected Http, got {other:?}"),
10504 }
10505 let nats = WitContract {
10506 de: "a".into(),
10507 para: "b".into(),
10508 wit: "nats:pub-sub".into(),
10509 endpoint: None,
10510 subject: Some("topic.x".into()),
10511 slot: None,
10512 };
10513 match nats.target().unwrap() {
10514 WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10515 other => panic!("expected PubSub, got {other:?}"),
10516 }
10517 let kv = WitContract {
10518 de: "a".into(),
10519 para: "b".into(),
10520 wit: "wasi:keyvalue/store".into(),
10521 endpoint: None,
10522 subject: None,
10523 slot: Some("checkout/$orderId".into()),
10524 };
10525 match kv.target().unwrap() {
10526 WitTarget::Store { slot } => assert!(!slot.is_empty()),
10527 other => panic!("expected Store, got {other:?}"),
10528 }
10529 }
10530
10531 #[test]
10532 fn target_diagnostic_names_offending_endpoint_value() {
10533 // When the malformed endpoint string is non-trivial, the
10534 // diagnostic carries the actual value back to the author —
10535 // not a generic "endpoint malformed" error.
10536 let bad = WitContract {
10537 de: "src".into(),
10538 para: "dst".into(),
10539 wit: "wasi:http/proxy".into(),
10540 endpoint: Some("api/v1/charge".into()),
10541 subject: None,
10542 slot: None,
10543 };
10544 match bad.target().unwrap_err() {
10545 AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10546 assert_eq!(de, "src");
10547 assert_eq!(para, "dst");
10548 assert_eq!(endpoint, "api/v1/charge");
10549 }
10550 other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10551 }
10552 }
10553
10554 #[test]
10555 fn rejects_unknown_wit_with_target_set() {
10556 let mut s = three_member_spec();
10557 s.contratos.push(WitContract {
10558 de: "cart".into(),
10559 para: "catalog".into(),
10560 wit: "custom:exchange".into(),
10561 endpoint: Some("/leaked".into()),
10562 subject: None,
10563 slot: None,
10564 });
10565 let err = s.validate().unwrap_err();
10566 assert!(matches!(
10567 err,
10568 AplicacaoError::ContratoWrongTarget {
10569 expected: WitTarget::CAPABILITY_EXPECTED,
10570 ..
10571 }
10572 ));
10573 }
10574
10575 #[test]
10576 fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10577 // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10578 // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10579 // fourth arm of the same "which payload field name goes in the
10580 // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10581 // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10582 // consts cover on the peer HTTP / PubSub / Store arms
10583 // (`wit_target_field_name_pins_per_variant`). Until this lift
10584 // landed the byte-string sat twice — once inline in the
10585 // [`WitContract::target`] Capability-arm rejection at the
10586 // production dispatch, once in `rejects_unknown_wit_with_target_set`
10587 // pinning against the same literal — with no compile-time link
10588 // between them. Same "one canonical declaration, next to the
10589 // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10590 // lift established for the payload-less arm's human-readable
10591 // label axis; this test is the shape peer of
10592 // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10593 // pair (routes-through-const + scalar-value pin) on the
10594 // wrong-target diagnostic-scalar axis.
10595 //
10596 // Fail-before-pass-after was verified locally by mutating the
10597 // const declaration to `"capability"` — the scalar-value pin
10598 // below fires (`"capability" != "none"`) and the routes-through
10599 // assertion below still holds (production and const walk in
10600 // lockstep), which is the correct behavior: a rename on the
10601 // const drifts here first, not at a downstream consumer.
10602 assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10603
10604 let mut s = three_member_spec();
10605 s.contratos.push(WitContract {
10606 de: "cart".into(),
10607 para: "catalog".into(),
10608 wit: "custom:exchange".into(),
10609 endpoint: Some("/leaked".into()),
10610 subject: None,
10611 slot: None,
10612 });
10613 match s.validate().unwrap_err() {
10614 AplicacaoError::ContratoWrongTarget { expected, .. } => {
10615 assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10616 }
10617 other => panic!("expected ContratoWrongTarget, got {other:?}"),
10618 }
10619 }
10620
10621 #[test]
10622 fn unknown_wit_capability_only_validates() {
10623 let mut s = three_member_spec();
10624 s.contratos.push(WitContract {
10625 de: "cart".into(),
10626 para: "catalog".into(),
10627 // A WIT world we haven't yet shaped — accept it as a typed
10628 // capability edge so authors aren't blocked while the WIT
10629 // registry catches up. No payload field may be carried.
10630 wit: "custom:exchange".into(),
10631 endpoint: None,
10632 subject: None,
10633 slot: None,
10634 });
10635 s.validate().unwrap();
10636 let added = s.contratos.last().unwrap();
10637 assert_eq!(added.target().unwrap(), WitTarget::Capability);
10638 }
10639
10640 #[test]
10641 fn target_typed_view_round_trips_each_shape() {
10642 let http = contract_http("cart", "catalog", "/products/:id");
10643 assert_eq!(
10644 http.target().unwrap(),
10645 WitTarget::Http {
10646 endpoint: "/products/:id"
10647 }
10648 );
10649 let nats = WitContract {
10650 de: "a".into(),
10651 para: "b".into(),
10652 wit: "nats:pub-sub".into(),
10653 endpoint: None,
10654 subject: Some("topic.x".into()),
10655 slot: None,
10656 };
10657 assert_eq!(
10658 nats.target().unwrap(),
10659 WitTarget::PubSub { subject: "topic.x" }
10660 );
10661 let kv = WitContract {
10662 de: "a".into(),
10663 para: "b".into(),
10664 wit: "wasi:keyvalue/store".into(),
10665 endpoint: None,
10666 subject: None,
10667 slot: Some("checkout/$orderId".into()),
10668 };
10669 assert_eq!(
10670 kv.target().unwrap(),
10671 WitTarget::Store {
10672 slot: "checkout/$orderId"
10673 }
10674 );
10675 }
10676
10677 #[test]
10678 fn wit_contract_kind_predicates() {
10679 let http = contract_http("a", "b", "/x");
10680 assert!(http.is_http());
10681 assert!(!http.is_pubsub());
10682 assert!(!http.is_store());
10683 assert!(!http.is_capability());
10684
10685 let nats = WitContract {
10686 de: "a".into(),
10687 para: "b".into(),
10688 wit: "nats:pub-sub".into(),
10689 endpoint: None,
10690 subject: Some("topic.x".into()),
10691 slot: None,
10692 };
10693 assert!(nats.is_pubsub());
10694 assert!(!nats.is_http());
10695 assert!(!nats.is_capability());
10696
10697 let kv = WitContract {
10698 de: "a".into(),
10699 para: "b".into(),
10700 wit: "wasi:keyvalue/store".into(),
10701 endpoint: None,
10702 subject: None,
10703 slot: Some("checkout/$orderId".into()),
10704 };
10705 assert!(kv.is_store());
10706 assert!(!kv.is_http());
10707 assert!(!kv.is_capability());
10708
10709 // Fourth arm on the paired closed-set predicate family: the
10710 // payload-less capability edge that projects to the payload-
10711 // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10712 // Extends the 3-arm predicate sweep this test opened to cover
10713 // the closed 4-way partition [`WitContract::is_capability`]
10714 // closes on the pre-projection WIT-shape axis, matched with the
10715 // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10716 // 4-arm predicate set.
10717 let cap = WitContract {
10718 de: "a".into(),
10719 para: "b".into(),
10720 wit: "custom:capability-only".into(),
10721 endpoint: None,
10722 subject: None,
10723 slot: None,
10724 };
10725 assert!(cap.is_capability());
10726 assert!(!cap.is_http());
10727 assert!(!cap.is_pubsub());
10728 assert!(!cap.is_store());
10729 }
10730
10731 // ── :contratos :wit value-shape gate ─────────────────────────────────
10732 //
10733 // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10734 // dispatch-discriminator axis. Until this gate landed
10735 // `WitContract::target()` accepted any non-empty string and
10736 // silently demoted unrecognized shapes to a capability-only L4
10737 // edge — the canonical "I thought I had L7 HTTP routing, got
10738 // L4-only" footgun. Every authoring footgun the WIT registry's
10739 // own grammar rejects (uppercase, hyphen-for-colon typo,
10740 // whitespace, empty package, doubled `@`, …) now becomes a
10741 // caixa-build-time `ContratoWitInvalid` with the offending
10742 // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10743 // as `ContratoEndpointInvalid` on the sibling axis; same shared
10744 // predicate (`crate::render::is_wit_world_ref`) ensures drift
10745 // between any two axes' rule enforcement is a build error at the
10746 // predicate, not piecemeal across renderers.
10747
10748 fn contrato_wit_err(wit: &str) -> AplicacaoError {
10749 // Fresh spec per call so the new contract doesn't collide on
10750 // identity with `three_member_spec`'s pre-existing entries.
10751 // The new edge uses `(payment, catalog)` — a pair the fixture
10752 // doesn't already declare — with no payload field set, so the
10753 // wit-shape gate fires before any payload-shape arm.
10754 let mut s = three_member_spec();
10755 s.contratos.push(WitContract {
10756 de: "payment".into(),
10757 para: "catalog".into(),
10758 wit: wit.into(),
10759 endpoint: None,
10760 subject: None,
10761 slot: None,
10762 });
10763 s.validate().unwrap_err()
10764 }
10765
10766 #[test]
10767 fn rejects_wit_with_uppercase_namespace() {
10768 // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10769 // didn't match the lowercase `wasi:http/` prefix is_http() keys
10770 // off, so the dispatch fell through to the capability arm and
10771 // the contract silently rendered as an L4-only Cilium edge.
10772 // The new gate surfaces the uppercase typo at validate time
10773 // with the offending `:wit` named.
10774 let err = contrato_wit_err("WASI:http/proxy");
10775 assert!(
10776 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10777 if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10778 "got {err:?}"
10779 );
10780 }
10781
10782 #[test]
10783 fn rejects_wit_with_hyphen_for_colon_typo() {
10784 // The canonical "I forgot the `:` separator" typo — pre-gate
10785 // this passed as Capability silently, so the renderer emitted
10786 // an L4-only policy where the author expected L7 HTTP rules.
10787 let err = contrato_wit_err("wasi-http/proxy");
10788 assert!(
10789 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10790 if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10791 "got {err:?}"
10792 );
10793 }
10794
10795 #[test]
10796 fn rejects_wit_with_multiple_colons() {
10797 // Doubled `:` — the namespace/package split has nowhere to
10798 // anchor, so the dispatch silently demotes to Capability.
10799 let err = contrato_wit_err("wasi:http:proxy");
10800 assert!(
10801 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10802 if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10803 "got {err:?}"
10804 );
10805 }
10806
10807 #[test]
10808 fn rejects_wit_with_empty_package() {
10809 // `wasi:` — namespace alone with no package. Pre-gate this
10810 // failed neither the is_http nor is_pubsub nor is_store
10811 // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10812 // a bare `wasi:`), so it silently demoted to Capability.
10813 let err = contrato_wit_err("wasi:");
10814 assert!(
10815 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10816 if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10817 "got {err:?}"
10818 );
10819 }
10820
10821 #[test]
10822 fn rejects_wit_with_underscore() {
10823 // Underscore — WIT identifiers are kebab-case, same rule
10824 // DNS-1123 enforces on its peer axes. The diagnostic carries
10825 // the explicit "use `-` instead" remediation.
10826 let err = contrato_wit_err("wasi:http_proxy");
10827 assert!(
10828 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10829 if wit == "wasi:http_proxy" && reason.contains('_')),
10830 "got {err:?}"
10831 );
10832 }
10833
10834 #[test]
10835 fn rejects_wit_with_whitespace() {
10836 // Whitespace mid-token — the prefix check matches but the
10837 // package-and-onward parse silently demoted to Capability.
10838 let err = contrato_wit_err("wasi:http proxy");
10839 assert!(
10840 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10841 if wit == "wasi:http proxy" && reason.contains("whitespace")),
10842 "got {err:?}"
10843 );
10844 }
10845
10846 #[test]
10847 fn rejects_wit_with_non_ascii() {
10848 // Un-percent-encoded non-ASCII byte — the canonical "I copied
10849 // the package name from a doc with smart quotes / accented
10850 // characters" footgun.
10851 let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
10852 assert!(
10853 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10854 if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
10855 "got {err:?}"
10856 );
10857 }
10858
10859 #[test]
10860 fn rejects_wit_with_consecutive_hyphens() {
10861 // `pub--sub` — WIT identifiers join words with single hyphens.
10862 let err = contrato_wit_err("nats:pub--sub");
10863 assert!(
10864 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10865 if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10866 "got {err:?}"
10867 );
10868 }
10869
10870 #[test]
10871 fn rejects_wit_with_trailing_at_no_version() {
10872 // `wasi:http/proxy@` — the version-suffix author started to
10873 // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10874 // parser would reject this; surface it at validate time.
10875 let err = contrato_wit_err("wasi:http/proxy@");
10876 assert!(
10877 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10878 if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10879 "got {err:?}"
10880 );
10881 }
10882
10883 #[test]
10884 fn rejects_wit_too_long() {
10885 // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10886 // The legitimate-shape arms all pass (lowercase, single `:`,
10887 // kebab-case identifiers); only the cap arm fires. Surfaces
10888 // the paste-from-binary / accidental-multi-line-blob landing
10889 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10890 // on the peer axis.
10891 let big = format!("wasi:{}", "a".repeat(124));
10892 assert_eq!(big.len(), 129);
10893 let err = contrato_wit_err(&big);
10894 assert!(
10895 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10896 if wit == &big && reason.contains("max length of 128")),
10897 "got {err:?}"
10898 );
10899 }
10900
10901 #[test]
10902 fn wit_max_length_validates() {
10903 // 128-byte WIT reference — exactly the cap. Boundary pin:
10904 // drift in the cap surfaces here and at `rejects_wit_too_long`
10905 // simultaneously, mirroring
10906 // `http_contrato_endpoint_max_length_validates` on the peer
10907 // axis.
10908 let big = format!("wasi:{}", "a".repeat(123));
10909 assert_eq!(big.len(), 128);
10910 let mut s = three_member_spec();
10911 s.contratos.push(WitContract {
10912 de: "payment".into(),
10913 para: "catalog".into(),
10914 wit: big,
10915 endpoint: None,
10916 subject: None,
10917 slot: None,
10918 });
10919 s.validate().unwrap();
10920 }
10921
10922 #[test]
10923 fn wit_accepts_canonical_forms_at_aplicacao_layer() {
10924 // Positive-set sweep through the AplicacaoSpec::validate
10925 // surface (rather than the substrate-side predicate directly)
10926 // — pins every shape the existing test fixtures + the
10927 // checkout-aplicacao example carry, so the gate's accept-set
10928 // matches the substrate's emit-set. Drift between this list
10929 // and `render::tests::wit_world_ref_accepts_canonical_forms`
10930 // surfaces at the substrate layer's positive sweep — one
10931 // source of truth for the rule.
10932 for wit in [
10933 "wasi:http/proxy",
10934 "wasi:keyvalue/store",
10935 "nats:pub-sub",
10936 "kafka:topic",
10937 "custom:exchange",
10938 "pleme:cap/audit",
10939 "wasi:http/proxy@0.2.0",
10940 ] {
10941 // Payload field paired to the dispatched WIT shape so the
10942 // shape-↔-target arm doesn't fire instead of the wit-shape
10943 // arm we're exercising. Routes off the same
10944 // `wit_shape_is_http` / `wit_shape_is_pubsub` /
10945 // `wit_shape_is_store` free functions the production
10946 // `WitContract::is_http` / `is_pubsub` / `is_store`
10947 // methods delegate to (both consult the lifted
10948 // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
10949 // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
10950 // future prefix addition to the routing accept-set
10951 // reaches this test's payload-dispatch arm by
10952 // construction — no per-test-site drift can hide a
10953 // shape-→-target-slot mismatch that would silently
10954 // demote a canonical `:wit` value to the
10955 // `(None, None, None)` capability-only arm and let the
10956 // `AplicacaoSpec::validate` positive sweep pass on a
10957 // shape it should exercise as HTTP / pub-sub / store.
10958 let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
10959 (Some("/x".into()), None, None)
10960 } else if wit_shape_is_pubsub(wit) {
10961 (None, Some("topic.x".into()), None)
10962 } else if wit_shape_is_store(wit) {
10963 (None, None, Some("bucket/$key".into()))
10964 } else {
10965 (None, None, None)
10966 };
10967 let mut s = three_member_spec();
10968 s.contratos.push(WitContract {
10969 de: "payment".into(),
10970 para: "catalog".into(),
10971 wit: wit.into(),
10972 endpoint,
10973 subject,
10974 slot,
10975 });
10976 s.validate()
10977 .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
10978 }
10979 }
10980
10981 #[test]
10982 fn wit_shape_predicates_accept_canonical_prefix_set() {
10983 // Positive-set sweep pinning every prefix in
10984 // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
10985 // WIT_STORE_SHAPE_PREFIXES against the three free-function
10986 // dispatch predicates. The six prefixes are the load-bearing
10987 // routing keys the substrate's WIT-shape dispatch consults
10988 // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
10989 // key/value-store-slot admission); any drift between the
10990 // free-function accept-set and this list surfaces here
10991 // rather than at apply time as a silent
10992 // shape-→-capability-only demotion.
10993 assert!(wit_shape_is_http("wasi:http/proxy"));
10994 assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
10995 assert!(wit_shape_is_http("http:incoming"));
10996
10997 assert!(wit_shape_is_pubsub("nats:pub-sub"));
10998 assert!(wit_shape_is_pubsub("kafka:topic"));
10999
11000 assert!(wit_shape_is_store("wasi:keyvalue/store"));
11001 assert!(wit_shape_is_store("kv:cache/session"));
11002 }
11003
11004 #[test]
11005 fn wit_shape_predicates_reject_uncanonical_forms() {
11006 // Negative-set pin: the six canonical prefixes are
11007 // lowercase-only (mirrors the `is_wit_world_ref` substrate
11008 // predicate's lowercase invariant — see its docstring on the
11009 // "I thought I had L7 HTTP routing, got L4-only" footgun).
11010 // The empty string, an uppercase-prefixed form, a hyphen-
11011 // instead-of-colon typo, and a bare kebab identifier all miss
11012 // every shape arm — reachable-by-construction only via the
11013 // `is_wit_world_ref` gate that admission-checks the `:wit`
11014 // value first, but pinned here so any future
11015 // free-function change (e.g. a case-insensitive
11016 // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
11017 // this unit level.
11018 for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
11019 assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
11020 assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
11021 assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
11022 }
11023 }
11024
11025 #[test]
11026 fn wit_shape_predicates_partition_canonical_set() {
11027 // Every canonical prefix routes to exactly one shape arm —
11028 // the three prefix sets are pairwise disjoint. Pins the
11029 // routing property [`WitContract::target`] relies on: an
11030 // `is_http()` return of `true` guarantees `is_pubsub()` and
11031 // `is_store()` return `false`, so the shape-→-target-slot
11032 // dispatch (endpoint vs subject vs slot) is unambiguous.
11033 // Drift (e.g. a future `"kv:"` moved into the HTTP set
11034 // without removal from the store set) would silently route
11035 // one prefix to two arms and the first-matching-arm order
11036 // becomes load-bearing — this pin surfaces it as a build
11037 // error instead.
11038 for prefix in WIT_HTTP_SHAPE_PREFIXES {
11039 let sample = format!("{prefix}x");
11040 assert!(wit_shape_is_http(&sample));
11041 assert!(!wit_shape_is_pubsub(&sample));
11042 assert!(!wit_shape_is_store(&sample));
11043 }
11044 for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
11045 let sample = format!("{prefix}x");
11046 assert!(!wit_shape_is_http(&sample));
11047 assert!(wit_shape_is_pubsub(&sample));
11048 assert!(!wit_shape_is_store(&sample));
11049 }
11050 for prefix in WIT_STORE_SHAPE_PREFIXES {
11051 let sample = format!("{prefix}x");
11052 assert!(!wit_shape_is_http(&sample));
11053 assert!(!wit_shape_is_pubsub(&sample));
11054 assert!(wit_shape_is_store(&sample));
11055 }
11056 }
11057
11058 #[test]
11059 fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
11060 // Positive pin: [`wit_shape_matches`] is exactly the
11061 // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
11062 // parameterized on the accept-set. Two-prefix accept-set,
11063 // one-prefix accept-set, and empty accept-set (which must
11064 // reject everything, including the empty string — an empty
11065 // `any()` fold returns `false`) all pinned so a future
11066 // reimplementation that swaps `starts_with` for `contains`,
11067 // `==`, or a case-folded comparator surfaces at unit-test
11068 // time.
11069 let two = &["wasi:http/", "http:"];
11070 assert!(wit_shape_matches("wasi:http/proxy", two));
11071 assert!(wit_shape_matches("http:incoming", two));
11072 assert!(!wit_shape_matches("wasi:keyvalue/store", two));
11073
11074 let one = &["nats:"];
11075 assert!(wit_shape_matches("nats:pub-sub", one));
11076 assert!(!wit_shape_matches("kafka:topic", one));
11077
11078 // Empty accept-set matches nothing — the identity element
11079 // for the disjunctive `any()` fold across the prefix set.
11080 // Reachable via a future `wit_shape_is_<name>` const paired
11081 // to a still-empty prefix table on a nascent shape-arm draft.
11082 let empty: &[&str] = &[];
11083 assert!(!wit_shape_matches("wasi:http/proxy", empty));
11084 assert!(!wit_shape_matches("", empty));
11085
11086 // starts_with, not contains: a prefix embedded mid-string
11087 // never matches. Pins the routing invariant [`WitContract::target`]
11088 // relies on (an authored `:wit "custom:wasi:http/"` string
11089 // does not silently route through the HTTP arm just because
11090 // it happens to contain the canonical HTTP prefix).
11091 assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
11092 }
11093
11094 #[test]
11095 fn wit_shape_predicates_delegate_to_wit_shape_matches() {
11096 // Equivalence pin: each per-shape predicate is exactly
11097 // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
11098 // every canonical prefix + the empty string + one negative
11099 // sample against every peer so a future predicate that grew
11100 // its own inline `iter().any(starts_with)` (rather than
11101 // delegating through the lifted combinator) drifts loudly here
11102 // — the peer-const table's contents must agree with the
11103 // predicate's accept-set by construction.
11104 let samples = [
11105 String::new(),
11106 "wasi:http/proxy".to_string(),
11107 "http:incoming".to_string(),
11108 "nats:pub-sub".to_string(),
11109 "kafka:topic".to_string(),
11110 "wasi:keyvalue/store".to_string(),
11111 "kv:cache/session".to_string(),
11112 "custom-shape".to_string(),
11113 "WASI:HTTP/proxy".to_string(),
11114 ];
11115 for wit in &samples {
11116 assert_eq!(
11117 wit_shape_is_http(wit),
11118 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11119 "wit_shape_is_http drifted from combinator on {wit:?}",
11120 );
11121 assert_eq!(
11122 wit_shape_is_pubsub(wit),
11123 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
11124 "wit_shape_is_pubsub drifted from combinator on {wit:?}",
11125 );
11126 assert_eq!(
11127 wit_shape_is_store(wit),
11128 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
11129 "wit_shape_is_store drifted from combinator on {wit:?}",
11130 );
11131 }
11132 }
11133
11134 #[test]
11135 fn wit_contract_shape_methods_delegate_to_free_functions() {
11136 // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
11137 // `is_store` are `&self` conveniences on top of the free
11138 // functions — for every canonical prefix the method's return
11139 // matches its free-function peer. Sweeps the union of the
11140 // three prefix sets so a future method that grew its own
11141 // inline prefix logic (rather than delegating) drifts loudly
11142 // here on the first prefix the free function accepts and the
11143 // method doesn't.
11144 for shape_set in [
11145 WIT_HTTP_SHAPE_PREFIXES,
11146 WIT_PUBSUB_SHAPE_PREFIXES,
11147 WIT_STORE_SHAPE_PREFIXES,
11148 ] {
11149 for prefix in shape_set {
11150 let c = WitContract {
11151 de: "cart".into(),
11152 para: "catalog".into(),
11153 wit: format!("{prefix}x"),
11154 endpoint: None,
11155 subject: None,
11156 slot: None,
11157 };
11158 assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
11159 assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
11160 assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
11161 assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11162 }
11163 }
11164 // Capability-arm delegation sweep: two representative
11165 // Capability-shaped `:wit` values (a bare non-prefix-matching
11166 // WIT world, the deliberately-shaped empty string
11167 // [`WitContract::is_capability`]'s docstring calls out as
11168 // syntactically Capability). Extends the free-function
11169 // delegation pin onto the fourth arm so a future
11170 // [`WitContract::is_capability`] rewrite that grew an inline
11171 // prefix-set scan (rather than delegating through
11172 // [`wit_shape_is_capability`]) drifts loudly here on the first
11173 // Capability-shaped sample.
11174 for wit in ["custom:capability-only", ""] {
11175 let c = WitContract {
11176 de: "cart".into(),
11177 para: "catalog".into(),
11178 wit: wit.into(),
11179 endpoint: None,
11180 subject: None,
11181 slot: None,
11182 };
11183 assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11184 }
11185 }
11186
11187 #[test]
11188 fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
11189 // 4-way partition-witness pin on the raw `&str` axis: for every
11190 // canonical prefix in the three payload-arm accept-sets,
11191 // exactly one of the four [`wit_shape_is_http`] /
11192 // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11193 // [`wit_shape_is_capability`] free functions returns `true` and
11194 // the other three return `false` — the four-arm partition
11195 // witness that locks the free-function WIT-shape-classifier
11196 // family into a partition of the `:contratos :wit` axis
11197 // load-bearing. Peer of the sibling [`WitContract`]-surface
11198 // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
11199 // partition pin — extends the discipline onto the raw `&str`
11200 // axis so any future arm addition (a hypothetical
11201 // `wasi:sockets/*` transport-layer shape, an `oci:*`
11202 // capability-import carrier per the sibling
11203 // [`wit_shape_matches`] docstring's trajectory bullet) that
11204 // landed on one of the payload-arm free functions without
11205 // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
11206 // here as two arms returning `true` simultaneously at
11207 // caixa-core build time rather than a silent per-consumer
11208 // misclassification at renderer emit time.
11209 for shape_set in [
11210 WIT_HTTP_SHAPE_PREFIXES,
11211 WIT_PUBSUB_SHAPE_PREFIXES,
11212 WIT_STORE_SHAPE_PREFIXES,
11213 ] {
11214 for prefix in shape_set {
11215 let wit = format!("{prefix}x");
11216 let hits = [
11217 wit_shape_is_http(&wit),
11218 wit_shape_is_pubsub(&wit),
11219 wit_shape_is_store(&wit),
11220 wit_shape_is_capability(&wit),
11221 ]
11222 .iter()
11223 .filter(|&&b| b)
11224 .count();
11225 assert_eq!(
11226 hits,
11227 1,
11228 "raw-&str WIT-shape 4-way predicate partition must \
11229 admit exactly one arm per canonical prefix; got {hits} \
11230 hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
11231 is_capability={})",
11232 wit_shape_is_http(&wit),
11233 wit_shape_is_pubsub(&wit),
11234 wit_shape_is_store(&wit),
11235 wit_shape_is_capability(&wit),
11236 );
11237 }
11238 }
11239 // Capability-arm sweep on the raw `&str` axis: two
11240 // representative Capability-shaped `:wit` values (a bare non-
11241 // prefix-matching WIT world, the deliberately-shaped empty
11242 // string the pure classifier still admits per
11243 // [`wit_shape_is_capability`]'s docstring). Both must land on
11244 // the fourth arm exclusively so the partition witness holds
11245 // across the full 4-arm closure on the raw `&str` axis.
11246 for wit in ["custom:capability-only", ""] {
11247 let hits = [
11248 wit_shape_is_http(wit),
11249 wit_shape_is_pubsub(wit),
11250 wit_shape_is_store(wit),
11251 wit_shape_is_capability(wit),
11252 ]
11253 .iter()
11254 .filter(|&&b| b)
11255 .count();
11256 assert_eq!(
11257 hits, 1,
11258 "raw-&str WIT-shape 4-way predicate partition must \
11259 admit exactly one arm on Capability-shaped wit={wit:?}"
11260 );
11261 assert!(
11262 wit_shape_is_capability(wit),
11263 "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
11264 );
11265 }
11266 }
11267
11268 #[test]
11269 fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
11270 // Composition-witness pin: [`wit_shape_is_capability`] is the
11271 // exact-inverse disjunction of the sibling payload-arm free-
11272 // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
11273 // / [`wit_shape_is_store`]. A future reimplementation that
11274 // grew its own prefix-set scan (e.g. inlining a fourth
11275 // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
11276 // not own today) rather than delegating to the sibling trio
11277 // would drift loudly here — the composition contract binds the
11278 // fourth-arm free-function predicate to the exact-inverse of
11279 // the three payload-arm free-function predicates, so any
11280 // rebrand of any prefix-set const flows through
11281 // [`wit_shape_is_capability`] by construction without a
11282 // coordinated per-consumer rewrite. Peer of the sibling
11283 // [`WitContract`]-surface
11284 // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
11285 // composition pin — extends the discipline onto the raw
11286 // `&str` axis.
11287 let mut cases: Vec<String> = Vec::new();
11288 for shape_set in [
11289 WIT_HTTP_SHAPE_PREFIXES,
11290 WIT_PUBSUB_SHAPE_PREFIXES,
11291 WIT_STORE_SHAPE_PREFIXES,
11292 ] {
11293 for prefix in shape_set {
11294 cases.push(format!("{prefix}x"));
11295 }
11296 }
11297 cases.push("custom:capability-only".to_string());
11298 cases.push(String::new());
11299 for wit in cases {
11300 assert_eq!(
11301 wit_shape_is_capability(&wit),
11302 !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
11303 "wit_shape_is_capability must equal \
11304 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
11305 at wit={wit:?}"
11306 );
11307 }
11308 }
11309
11310 #[test]
11311 fn wit_shape_classifier_family_is_const_fn() {
11312 // Fail-before-pass-after pin on the 4-arm free-function WIT-
11313 // shape classifier family's `const`-eval posture. Each of the
11314 // four peer classifiers ([`wit_shape_is_http`] /
11315 // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11316 // [`wit_shape_is_capability`]) and the underlying combinator
11317 // [`wit_shape_matches`] must be `pub const fn` — any future
11318 // accidental downgrade to non-`const` fails the `const fn`
11319 // wrappers below at caixa-core build time with E0015
11320 // (`cannot call non-const function`), strictly stronger than
11321 // a runtime `assert!` and strictly stronger than the module-
11322 // scope `const _: () = assert!(…)` pins immediately after the
11323 // classifier declarations (those anchor specific accept-set
11324 // truth-table entries; this pin anchors the `const` posture
11325 // itself via `const fn` wrappers that are only well-formed
11326 // when the callee is itself `const fn`).
11327 //
11328 // Verified fail-before-pass-after by locally reverting
11329 // `pub const fn` → `pub fn` on each classifier and observing
11330 // E0015 at every corresponding wrapper call site (build
11331 // error, no test-time surface), then restoring `pub const fn`
11332 // and observing the pin pass at test time. Peer of the
11333 // sibling M3
11334 // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11335 // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11336 // M2
11337 // [`child_spec_restart_accessor_is_const_fn`] /
11338 // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11339 // and M3
11340 // [`placement_estrategia_accessor_is_const_fn`] /
11341 // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11342 // sibling `const`-eval-surface-pass axes.
11343 const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
11344 wit_shape_matches(wit, prefixes)
11345 }
11346 const fn http_via_const_fn(wit: &str) -> bool {
11347 wit_shape_is_http(wit)
11348 }
11349 const fn pubsub_via_const_fn(wit: &str) -> bool {
11350 wit_shape_is_pubsub(wit)
11351 }
11352 const fn store_via_const_fn(wit: &str) -> bool {
11353 wit_shape_is_store(wit)
11354 }
11355 const fn capability_via_const_fn(wit: &str) -> bool {
11356 wit_shape_is_capability(wit)
11357 }
11358 // Sweep one canonical accept-set sample per arm plus the
11359 // payload-less/empty capability samples, asserting the
11360 // wrapper and direct dispatches agree byte-for-byte across
11361 // the closed 4-arm partition.
11362 let cases: [(&str, bool, bool, bool, bool); 6] = [
11363 ("wasi:http/proxy", true, false, false, false),
11364 ("http:incoming", true, false, false, false),
11365 ("nats:events", false, true, false, false),
11366 ("kafka:topic", false, true, false, false),
11367 ("wasi:keyvalue/store", false, false, true, false),
11368 ("kv:cache", false, false, true, false),
11369 ];
11370 for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
11371 assert_eq!(
11372 matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
11373 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11374 "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
11375 );
11376 assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
11377 assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
11378 assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
11379 assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11380 assert_eq!(wit_shape_is_http(wit), is_http);
11381 assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
11382 assert_eq!(wit_shape_is_store(wit), is_store);
11383 }
11384 // Payload-less capability arm (the 4th partition arm).
11385 let capability_samples: [&str; 3] =
11386 ["wasi:filesystem/preopens", "custom:capability-only", ""];
11387 for wit in capability_samples {
11388 assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11389 assert!(wit_shape_is_capability(wit));
11390 assert!(!wit_shape_is_http(wit));
11391 assert!(!wit_shape_is_pubsub(wit));
11392 assert!(!wit_shape_is_store(wit));
11393 }
11394 }
11395
11396 #[test]
11397 fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
11398 // Composition-witness pin: [`wit_shape_matches`] agrees with
11399 // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
11400 // dispatch (the prior non-`const` implementation) across
11401 // boundary lengths — empty `wit`, empty prefix, one-byte
11402 // slack, prefix longer than `wit`, one-byte trailing slack.
11403 // The rewrite to a byte-level manual starts_with loop (the
11404 // enabler for the `pub const fn` posture) must not change any
11405 // truth-table entry on the canonical accept-set — this pin
11406 // sweeps a targeted boundary corpus and asserts byte-for-byte
11407 // agreement, locking the const-fn rewrite's semantics against
11408 // the prior iterator body by construction.
11409 let prefixes = &["wasi:http/", "http:"][..];
11410 let cases: [(&str, bool); 12] = [
11411 ("wasi:http/proxy", true),
11412 ("wasi:http/", true), // exact-length match on prefix
11413 ("wasi:http", false), // one byte short
11414 ("http:", true),
11415 ("http:incoming", true),
11416 ("http", false), // one byte short
11417 ("", false),
11418 ("wasi:https/proxy", false),
11419 ("nats:events", false),
11420 ("HTTPS:", false), // uppercase — no case-fold in classifier
11421 ("wasi:HTTP/proxy", false),
11422 ("wasi:http", false),
11423 ];
11424 for (wit, expected) in cases {
11425 assert_eq!(
11426 wit_shape_matches(wit, prefixes),
11427 expected,
11428 "wit_shape_matches disagrees with reference at wit={wit:?}",
11429 );
11430 // Byte-equal to the iterator body it replaced.
11431 let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
11432 assert_eq!(
11433 wit_shape_matches(wit, prefixes),
11434 via_iter,
11435 "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
11436 );
11437 }
11438 // Empty prefix set → always false regardless of `wit`.
11439 let empty: &[&str] = &[];
11440 assert!(!wit_shape_matches("", empty));
11441 assert!(!wit_shape_matches("wasi:http/proxy", empty));
11442 // Empty prefix inside a non-empty set → always true (every
11443 // string starts with the empty string, matching the
11444 // iterator body's semantics on `str::starts_with("")`).
11445 let contains_empty: &[&str] = &["nats:", ""];
11446 assert!(wit_shape_matches("", contains_empty));
11447 assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
11448 }
11449
11450 #[test]
11451 fn wit_contract_is_capability_partitions_the_wit_shape_space() {
11452 // 4-way partition-witness pin: for every canonical prefix in
11453 // the payload-arm accept-sets, exactly one of the four
11454 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11455 // [`WitContract::is_store`] / [`WitContract::is_capability`]
11456 // predicates returns `true` and the other three return `false`
11457 // — the four-arm partition witness that locks the substrate's
11458 // WIT-shape-space closure on the pre-projection axis load-
11459 // bearing. A future arm addition (a hypothetical fourth
11460 // payload-shape prefix set, a `wasi:sockets/*` transport-layer
11461 // shape) that landed on one of the payload-arm predicates
11462 // without shrinking [`WitContract::is_capability`]'s accept-set
11463 // would surface here as two arms returning `true` simultaneously
11464 // — a partition-witness break the pin catches at caixa-core
11465 // build time rather than a silent per-consumer misclassification
11466 // at renderer emit time. Peer of the sibling `WitTarget`-side
11467 // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
11468 // partition-witness pin on the post-projection payload-scalar
11469 // arm-set — extends the discipline onto the pre-projection
11470 // 4-arm shape-space.
11471 for shape_set in [
11472 WIT_HTTP_SHAPE_PREFIXES,
11473 WIT_PUBSUB_SHAPE_PREFIXES,
11474 WIT_STORE_SHAPE_PREFIXES,
11475 ] {
11476 for prefix in shape_set {
11477 let c = WitContract {
11478 de: "cart".into(),
11479 para: "catalog".into(),
11480 wit: format!("{prefix}x"),
11481 endpoint: None,
11482 subject: None,
11483 slot: None,
11484 };
11485 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11486 .iter()
11487 .filter(|&&b| b)
11488 .count();
11489 assert_eq!(
11490 hits,
11491 1,
11492 "WitContract WIT-shape 4-way predicate partition must \
11493 admit exactly one arm per canonical prefix; got {hits} \
11494 hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
11495 is_capability={})",
11496 c.wit,
11497 c.is_http(),
11498 c.is_pubsub(),
11499 c.is_store(),
11500 c.is_capability(),
11501 );
11502 }
11503 }
11504 // Capability-arm sweep: two representative capability shapes
11505 // (a bare WIT world outside the three payload-arm prefix sets,
11506 // and the deliberately-shaped empty string that
11507 // [`crate::render::is_wit_world_ref`] rejects at
11508 // [`WitContract::target`] time but which the pure classifier
11509 // still admits — see the method docstring's "purely syntactic
11510 // classification" note). Both must land on the fourth arm
11511 // exclusively, so the partition witness holds across the full
11512 // 4-arm closure.
11513 for wit in ["custom:capability-only", ""] {
11514 let c = WitContract {
11515 de: "cart".into(),
11516 para: "catalog".into(),
11517 wit: wit.into(),
11518 endpoint: None,
11519 subject: None,
11520 slot: None,
11521 };
11522 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11523 .iter()
11524 .filter(|&&b| b)
11525 .count();
11526 assert_eq!(
11527 hits, 1,
11528 "WitContract WIT-shape 4-way predicate partition must \
11529 admit exactly one arm on Capability-shaped wit={wit:?}"
11530 );
11531 assert!(
11532 c.is_capability(),
11533 "wit={wit:?} must project onto the Capability arm"
11534 );
11535 }
11536 }
11537
11538 #[test]
11539 fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
11540 // Composition-witness pin: [`WitContract::is_capability`] is the
11541 // exact-inverse disjunction of the sibling payload-arm predicate
11542 // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11543 // [`WitContract::is_store`]. A future reimplementation that
11544 // grew its own prefix-set scan (e.g. inlining a fourth
11545 // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
11546 // own today) rather than delegating to the sibling trio would
11547 // drift loudly here — the composition contract binds the
11548 // fourth-arm predicate to the exact-inverse of the three
11549 // payload-arm predicates, so any rebrand of any prefix-set const
11550 // flows through this method by construction without a
11551 // coordinated per-consumer rewrite. Sweeps the union of the
11552 // three payload-arm prefix sets plus two Capability-shaped
11553 // shapes (a bare non-prefix-matching WIT world, the deliberately-
11554 // empty string the pure classifier still admits per the method
11555 // docstring's "purely syntactic classification" note).
11556 let mut cases: Vec<String> = Vec::new();
11557 for shape_set in [
11558 WIT_HTTP_SHAPE_PREFIXES,
11559 WIT_PUBSUB_SHAPE_PREFIXES,
11560 WIT_STORE_SHAPE_PREFIXES,
11561 ] {
11562 for prefix in shape_set {
11563 cases.push(format!("{prefix}x"));
11564 }
11565 }
11566 cases.push("custom:capability-only".to_string());
11567 cases.push(String::new());
11568 for wit in cases {
11569 let c = WitContract {
11570 de: "cart".into(),
11571 para: "catalog".into(),
11572 wit: wit.clone(),
11573 endpoint: None,
11574 subject: None,
11575 slot: None,
11576 };
11577 assert_eq!(
11578 c.is_capability(),
11579 !c.is_http() && !c.is_pubsub() && !c.is_store(),
11580 "WitContract::is_capability must equal \
11581 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11582 );
11583 }
11584 }
11585
11586 #[test]
11587 fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11588 // Cross-projection-witness pin: whenever [`WitContract::target`]
11589 // succeeds, the pre-projection [`WitContract::is_capability`]
11590 // classification agrees with the post-projection
11591 // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11592 // predicate — the 4-arm typed partition on the substrate's
11593 // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11594 // partition on the pre-projection axis line up by construction.
11595 // A future divergence between the two axes (a peer
11596 // [`WitTarget`] variant addition that landed on the typed-view
11597 // surface without a peer prefix-set + [`WitContract`] predicate
11598 // extension, or vice versa) would surface here at caixa-core
11599 // build time rather than a silent per-consumer split at renderer
11600 // emit time. Peer of the sibling pre-/post-projection
11601 // agreement pins the payload-carrier trio
11602 // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11603 // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11604 // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11605 // post-projection — b11bb49 trio lift) already carry across the
11606 // three payload arms — this pin closes the pair on the fourth
11607 // payload-less arm.
11608 let http = WitContract {
11609 de: "cart".into(),
11610 para: "catalog".into(),
11611 wit: "wasi:http/proxy".into(),
11612 endpoint: Some("/x".into()),
11613 subject: None,
11614 slot: None,
11615 };
11616 assert!(!http.is_capability());
11617 assert!(!http.target().unwrap().is_capability());
11618
11619 let nats = WitContract {
11620 de: "cart".into(),
11621 para: "catalog".into(),
11622 wit: "nats:pub-sub".into(),
11623 endpoint: None,
11624 subject: Some("events.x".into()),
11625 slot: None,
11626 };
11627 assert!(!nats.is_capability());
11628 assert!(!nats.target().unwrap().is_capability());
11629
11630 let kv = WitContract {
11631 de: "cart".into(),
11632 para: "catalog".into(),
11633 wit: "wasi:keyvalue/store".into(),
11634 endpoint: None,
11635 subject: None,
11636 slot: Some("checkout/$orderId".into()),
11637 };
11638 assert!(!kv.is_capability());
11639 assert!(!kv.target().unwrap().is_capability());
11640
11641 let cap = WitContract {
11642 de: "cart".into(),
11643 para: "catalog".into(),
11644 wit: "custom:capability-only".into(),
11645 endpoint: None,
11646 subject: None,
11647 slot: None,
11648 };
11649 assert!(cap.is_capability());
11650 assert!(cap.target().unwrap().is_capability());
11651 }
11652
11653 #[test]
11654 fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
11655 // Load-bearing contract pin: on every canonical
11656 // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
11657 // [`WitContract::target_projected`] returns byte-equal to
11658 // [`WitContract::target`]`().unwrap()` — the post-validation
11659 // projection accessor is a thin panicking wrapper over the
11660 // pre-validation validator, no extra work in the projection
11661 // path. Any future divergence (a validator-side normalization
11662 // the projection doesn't route through, an accessor-side
11663 // caching layer the validator doesn't populate) would surface
11664 // here at caixa-core build time rather than a silent per-consumer
11665 // split at renderer emit time. Sweeps the closed 4-arm
11666 // [`WitTarget`] partition ([`WitTarget::Http`] /
11667 // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
11668 // [`WitTarget::Capability`]) so every arm carries a byte-equality
11669 // pin on the two-accessor pair.
11670 for (wit, endpoint, subject, slot) in [
11671 ("wasi:http/proxy", Some("/x"), None, None),
11672 ("nats:pub-sub", None, Some("events.x"), None),
11673 ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
11674 ("custom:capability-only", None, None, None),
11675 ] {
11676 let c = WitContract {
11677 de: "cart".into(),
11678 para: "catalog".into(),
11679 wit: wit.into(),
11680 endpoint: endpoint.map(str::to_string),
11681 subject: subject.map(str::to_string),
11682 slot: slot.map(str::to_string),
11683 };
11684 assert_eq!(
11685 c.target_projected(),
11686 c.target().unwrap(),
11687 "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
11688 );
11689 }
11690 }
11691
11692 #[test]
11693 #[should_panic(expected = "validated by typed_view")]
11694 fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
11695 // Panic-path pin: [`WitContract::target_projected`] threads the
11696 // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
11697 // through its expect-panic when called on a contract whose
11698 // (`:wit`, payload) shape has not been crossed by
11699 // [`AplicacaoSpec::validate`] — a contract with a structurally-
11700 // invalid `:wit` (hyphen-for-colon typo) that would surface
11701 // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
11702 // A future rebrand on the panic-message axis would land at one
11703 // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
11704 // and this pin's [`should_panic(expected = …)`] literal would
11705 // migrate alongside — the pin catches drift between the const
11706 // and the accessor's `expect(…)` call by construction.
11707 let c = WitContract {
11708 de: "cart".into(),
11709 para: "catalog".into(),
11710 // Hyphen-for-colon typo: `WitContract::target` returns
11711 // [`AplicacaoError::ContratoWitInvalid`] on this shape,
11712 // driving the [`WitContract::target_projected`] expect-panic.
11713 wit: "wasi-http/proxy".into(),
11714 endpoint: Some("/x".into()),
11715 subject: None,
11716 slot: None,
11717 };
11718 let _ = c.target_projected();
11719 }
11720
11721 #[test]
11722 fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
11723 // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
11724 // carries the exact byte-string the two prior open-coded
11725 // `.target().expect("validated by typed_view")` production
11726 // consumers threaded through inline before this lift converged
11727 // them onto [`WitContract::target_projected`] — the caixa-mesh
11728 // per-`(:de, :para)` CNP L7 introspection branch at
11729 // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
11730 // graph` per-`:contratos` payload-column printer at
11731 // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
11732 // byte-string load-bearing so a well-meaning const-side rebrand
11733 // that didn't carry a matched pin migration would surface here
11734 // at caixa-core build time rather than a silent per-consumer
11735 // panic-message drift at cluster-apply time. Peer of the
11736 // sibling [`WitTarget::CAPABILITY_LABEL`] /
11737 // [`WitTarget::CAPABILITY_EXPECTED`] /
11738 // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
11739 // the paired payload-less-arm scalar-const family.
11740 assert_eq!(
11741 WitContract::PROJECTED_INVARIANT_MSG,
11742 "validated by typed_view"
11743 );
11744 }
11745
11746 #[test]
11747 fn empty_wit_takes_precedence_over_invalid() {
11748 // Ordering pin: `EmptyWit` is the more self-locating
11749 // diagnostic on `""` and must lead — the value-shape gate is
11750 // only reached after the empty-check fires. Mirrors
11751 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11752 // the peer payload axis.
11753 let mut s = three_member_spec();
11754 s.contratos.push(WitContract {
11755 de: "payment".into(),
11756 para: "catalog".into(),
11757 wit: String::new(),
11758 endpoint: None,
11759 subject: None,
11760 slot: None,
11761 });
11762 let err = s.validate().unwrap_err();
11763 assert!(
11764 matches!(err, AplicacaoError::EmptyWit { .. }),
11765 "got {err:?}"
11766 );
11767 }
11768
11769 #[test]
11770 fn wit_invalid_fires_before_payload_shape_arm() {
11771 // Ordering pin: a malformed `:wit` surfaces *its own*
11772 // diagnostic (which names the offending wit verbatim) before
11773 // any payload-field check — a contrato whose wit is
11774 // structurally invalid AND carries a wrong target field
11775 // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
11776 // because the dispatch on the wit is what decides which
11777 // payload field is "right" in the first place. Without this
11778 // ordering, the author would see "wrong target field" for a
11779 // wit that hasn't even been parsed, which doesn't name the
11780 // root cause.
11781 let mut s = three_member_spec();
11782 s.contratos.push(WitContract {
11783 de: "payment".into(),
11784 para: "catalog".into(),
11785 // Hyphen-for-colon typo + endpoint set: pre-gate this
11786 // raised `ContratoWrongTarget { expected: "none" }` (the
11787 // Capability arm rejecting the endpoint), masking the
11788 // real authoring mistake (the wit isn't `wasi:http/proxy`).
11789 wit: "wasi-http/proxy".into(),
11790 endpoint: Some("/x".into()),
11791 subject: None,
11792 slot: None,
11793 });
11794 let err = s.validate().unwrap_err();
11795 assert!(
11796 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
11797 if wit == "wasi-http/proxy"),
11798 "got {err:?}"
11799 );
11800 }
11801
11802 #[test]
11803 fn wit_invalid_diagnostic_carries_offending_wit() {
11804 // Diagnostic-shape pin — the offending `:wit` + `:de` +
11805 // `:para` + a non-empty reason flow through verbatim so the
11806 // author can grep their caixa.lisp for the offending contrato
11807 // block and fix it in one edit. Same shape as
11808 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
11809 let err = contrato_wit_err("WASI:HTTP/proxy");
11810 match err {
11811 AplicacaoError::ContratoWitInvalid {
11812 de,
11813 para,
11814 wit,
11815 reason,
11816 } => {
11817 assert_eq!(de, "payment");
11818 assert_eq!(para, "catalog");
11819 assert_eq!(wit, "WASI:HTTP/proxy");
11820 assert!(!reason.is_empty(), "reason field must be non-empty");
11821 }
11822 other => panic!("expected ContratoWitInvalid, got {other:?}"),
11823 }
11824 }
11825
11826 // ── :contratos :subject value-shape gate ─────────────────────────────
11827 //
11828 // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
11829 // suites on the peer payload axes. Until this gate landed
11830 // `WitContract::target()` only refused the empty string; a
11831 // structurally invalid subject silently passed validate and the
11832 // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
11833 // Subject'` on publish / subscribe, or as a silent message drop,
11834 // far from the source caixa.lisp. Every authoring footgun the
11835 // NATS server's subject parser would catch on admission now
11836 // becomes a caixa-build-time `ContratoSubjectInvalid` with the
11837 // offending `:subject` + `:de` + `:para` named verbatim. Same
11838 // diagnostic shape as `ContratoEndpointInvalid` /
11839 // `ContratoWitInvalid` on the peer payload axes; same shared
11840 // predicate (`crate::render::is_nats_subject`) ensures drift
11841 // between any two axes' rule enforcement is a build error at the
11842 // predicate, not piecemeal across renderers.
11843
11844 fn contrato_subject_err(subject: &str) -> AplicacaoError {
11845 // Fresh spec per call so the new contract doesn't collide on
11846 // identity with `three_member_spec`'s pre-existing entries.
11847 // The new edge uses `(payment, catalog)` — a pair the fixture
11848 // doesn't already declare — with `:wit "nats:pub-sub"` and the
11849 // varying `:subject`, so the subject-shape gate fires cleanly
11850 // after the wit-shape gate (which `"nats:pub-sub"` passes).
11851 let mut s = three_member_spec();
11852 s.contratos.push(WitContract {
11853 de: "payment".into(),
11854 para: "catalog".into(),
11855 wit: "nats:pub-sub".into(),
11856 endpoint: None,
11857 subject: Some(subject.into()),
11858 slot: None,
11859 });
11860 s.validate().unwrap_err()
11861 }
11862
11863 #[test]
11864 fn rejects_pubsub_contrato_subject_with_whitespace() {
11865 // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
11866 // landed at the NATS server as a malformed subject the parser
11867 // rejects with `-ERR 'Invalid Subject'`. Now caught at the
11868 // source caixa.lisp.
11869 let err = contrato_subject_err("foo bar");
11870 assert!(
11871 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11872 if subject == "foo bar" && reason.contains("whitespace")),
11873 "got {err:?}"
11874 );
11875 }
11876
11877 #[test]
11878 fn rejects_pubsub_contrato_subject_with_control_char() {
11879 let err = contrato_subject_err("foo\x01bar");
11880 assert!(
11881 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11882 if subject == "foo\x01bar" && reason.contains("control character")),
11883 "got {err:?}"
11884 );
11885 }
11886
11887 #[test]
11888 fn rejects_pubsub_contrato_subject_with_non_ascii() {
11889 // Un-percent-encoded non-ASCII byte — the canonical "I copied
11890 // the subject from a doc with smart quotes / accented
11891 // characters" footgun.
11892 let err = contrato_subject_err("foo.caf\u{e9}");
11893 assert!(
11894 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11895 if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
11896 "got {err:?}"
11897 );
11898 }
11899
11900 #[test]
11901 fn rejects_pubsub_contrato_subject_with_leading_dot() {
11902 // Empty leading token — NATS rejects.
11903 let err = contrato_subject_err(".foo");
11904 assert!(
11905 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11906 if subject == ".foo" && reason.contains("must not start with `.`")),
11907 "got {err:?}"
11908 );
11909 }
11910
11911 #[test]
11912 fn rejects_pubsub_contrato_subject_with_trailing_dot() {
11913 // Empty trailing token — NATS rejects. The remediation
11914 // (use `>` instead) is in the reason string.
11915 let err = contrato_subject_err("foo.");
11916 assert!(
11917 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11918 if subject == "foo." && reason.contains("must not end with `.`")),
11919 "got {err:?}"
11920 );
11921 }
11922
11923 #[test]
11924 fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
11925 // The canonical "I forgot to fill in the middle segment"
11926 // typo — `"foo..bar"`. NATS rejects empty tokens.
11927 let err = contrato_subject_err("foo..bar");
11928 assert!(
11929 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11930 if subject == "foo..bar" && reason.contains("consecutive `.`")),
11931 "got {err:?}"
11932 );
11933 }
11934
11935 #[test]
11936 fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
11937 // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
11938 // as the final segment. Pre-gate this passed as a typed edge
11939 // and surfaced at runtime as a NATS subscribe rejection.
11940 let err = contrato_subject_err("foo.>.bar");
11941 assert!(
11942 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11943 if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
11944 "got {err:?}"
11945 );
11946 }
11947
11948 #[test]
11949 fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
11950 // `foo*.bar` — NATS wildcards are standalone tokens. The
11951 // remediation is in the reason string.
11952 let err = contrato_subject_err("foo*.bar");
11953 assert!(
11954 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11955 if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
11956 "got {err:?}"
11957 );
11958 }
11959
11960 #[test]
11961 fn rejects_pubsub_contrato_subject_with_invalid_char() {
11962 // `foo,bar` — comma is not a valid NATS subject character.
11963 // Pinned separately from the wildcard arms so the invalid-
11964 // character diagnostic is in force.
11965 let err = contrato_subject_err("foo,bar");
11966 assert!(
11967 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11968 if subject == "foo,bar" && reason.contains("invalid character")),
11969 "got {err:?}"
11970 );
11971 }
11972
11973 #[test]
11974 fn rejects_pubsub_contrato_subject_too_long() {
11975 // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
11976 // The legitimate-shape arms all pass (one all-`a` token, no
11977 // `.`, no wildcards); only the cap arm fires. Surfaces the
11978 // paste-from-binary / accidental-multi-line-blob landing
11979 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
11980 // on the peer axis.
11981 let big = "a".repeat(257);
11982 assert_eq!(big.len(), 257);
11983 let err = contrato_subject_err(&big);
11984 assert!(
11985 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11986 if subject == &big && reason.contains("max length of 256")),
11987 "got {err:?}"
11988 );
11989 }
11990
11991 #[test]
11992 fn pubsub_contrato_subject_max_length_validates() {
11993 // 256-byte subject — exactly the cap. Boundary pin: drift in
11994 // the cap surfaces here and at
11995 // `rejects_pubsub_contrato_subject_too_long` simultaneously,
11996 // mirroring `http_contrato_endpoint_max_length_validates` and
11997 // `wit_max_length_validates` on the peer axes.
11998 let big = "a".repeat(256);
11999 assert_eq!(big.len(), 256);
12000 let mut s = three_member_spec();
12001 s.contratos.push(WitContract {
12002 de: "payment".into(),
12003 para: "catalog".into(),
12004 wit: "nats:pub-sub".into(),
12005 endpoint: None,
12006 subject: Some(big),
12007 slot: None,
12008 });
12009 s.validate().unwrap();
12010 }
12011
12012 #[test]
12013 fn pubsub_contrato_subject_accepts_canonical_forms() {
12014 // Positive-set sweep: every canonical NATS subject shape the
12015 // substrate-side `is_nats_subject` predicate accepts (the
12016 // multi-dot `events.order.charged`, the snake_case / kebab-
12017 // case / mixed-case tokens, the digit-bearing tokens, the
12018 // single-token wildcard `*` at every segment position, and
12019 // the trailing `>` multi-token wildcard) must remain a valid
12020 // contrato subject too. Drift between this list and the
12021 // substrate-side `nats_subject_accepts_canonical_forms` sweep
12022 // surfaces at the shared predicate — one source of truth.
12023 // Uses a fresh `(payment, catalog)` edge so none of the swept
12024 // subjects collide with the pre-existing entries in
12025 // `three_member_spec`.
12026 for subject in [
12027 "checkout.events.charge.failed",
12028 "rio.events.order.charged",
12029 "orders",
12030 "orders.123",
12031 "snake_case.token",
12032 "kebab-case.token",
12033 "MixedCase.Token",
12034 "orders.*.charged",
12035 "*.events.*",
12036 "orders.>",
12037 ] {
12038 let mut s = three_member_spec();
12039 s.contratos.push(WitContract {
12040 de: "payment".into(),
12041 para: "catalog".into(),
12042 wit: "nats:pub-sub".into(),
12043 endpoint: None,
12044 subject: Some(subject.into()),
12045 slot: None,
12046 });
12047 s.validate()
12048 .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
12049 }
12050 }
12051
12052 #[test]
12053 fn contrato_subject_empty_takes_precedence_over_invalid() {
12054 // Ordering pin: `ContratoSubjectEmpty` is the more self-
12055 // locating diagnostic on `""` and must lead — the value-shape
12056 // gate is only reached after the empty-check fires. Mirrors
12057 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12058 // the peer payload axis.
12059 let mut s = three_member_spec();
12060 s.contratos.push(WitContract {
12061 de: "payment".into(),
12062 para: "catalog".into(),
12063 wit: "nats:pub-sub".into(),
12064 endpoint: None,
12065 subject: Some(String::new()),
12066 slot: None,
12067 });
12068 let err = s.validate().unwrap_err();
12069 assert!(
12070 matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
12071 "got {err:?}"
12072 );
12073 }
12074
12075 #[test]
12076 fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
12077 // Diagnostic-shape pin — the offending `:subject` + `:de` +
12078 // `:para` + a non-empty reason flow through verbatim so the
12079 // author can grep their caixa.lisp for the offending contrato
12080 // block and fix it in one edit. Same shape as
12081 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12082 // and `wit_invalid_diagnostic_carries_offending_wit`.
12083 let err = contrato_subject_err("foo..bar");
12084 match err {
12085 AplicacaoError::ContratoSubjectInvalid {
12086 de,
12087 para,
12088 subject,
12089 reason,
12090 } => {
12091 assert_eq!(de, "payment");
12092 assert_eq!(para, "catalog");
12093 assert_eq!(subject, "foo..bar");
12094 assert!(!reason.is_empty(), "reason field must be non-empty");
12095 }
12096 other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
12097 }
12098 }
12099
12100 #[test]
12101 fn target_view_pubsub_subject_passes_through_to_typed_view() {
12102 // The compounding theorem on the pub-sub axis: every
12103 // `WitTarget::PubSub { subject }` returned by `target()` carries
12104 // a NATS-server-accepted subject. Renderers downstream of
12105 // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
12106 // NATS Stream/Consumer CR emitter, the future `feira app graph`
12107 // view's subject labeller) can rely on this without re-checking
12108 // — the type system carries the proof. Mirrors
12109 // `target_view_payload_is_guaranteed_nonempty_after_target_call`
12110 // on the peer axes.
12111 let nats = WitContract {
12112 de: "a".into(),
12113 para: "b".into(),
12114 wit: "nats:pub-sub".into(),
12115 endpoint: None,
12116 subject: Some("orders.events.*.charged".into()),
12117 slot: None,
12118 };
12119 match nats.target().unwrap() {
12120 WitTarget::PubSub { subject } => {
12121 assert_eq!(subject, "orders.events.*.charged");
12122 }
12123 other => panic!("expected PubSub, got {other:?}"),
12124 }
12125 }
12126
12127 // ── :contratos :slot value-shape gate ────────────────────────────────
12128 //
12129 // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
12130 // (63e18a0) value-shape suites on the peer payload axes. Until this
12131 // gate landed `WitContract::target()` only refused the empty string
12132 // for the Store arm; a structurally invalid slot (raw whitespace,
12133 // control character, non-ASCII byte, paste-from-binary multi-line
12134 // blob) silently passed validate and surfaced at runtime as a
12135 // per-backend kv write rejection or a silent next-read corruption,
12136 // far from the source caixa.lisp with no field naming which
12137 // `:contratos` edge carried the typo. Every authoring footgun the
12138 // kv backend intersection-floor would catch on write now becomes a
12139 // caixa-build-time `ContratoSlotInvalid` with the offending
12140 // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
12141 // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
12142 // peer payload axes; same shared predicate
12143 // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
12144 // any two axes' rule enforcement is a build error at the
12145 // predicate, not piecemeal across renderers. Closes the typed
12146 // payload-axis value-shape trajectory across all three legs of the
12147 // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
12148
12149 fn contrato_slot_err(slot: &str) -> AplicacaoError {
12150 // Fresh spec per call so the new contract doesn't collide on
12151 // identity with `three_member_spec`'s pre-existing entries
12152 // and doesn't close a synchronous cycle the cycle detector
12153 // would reject before the slot-shape gate fires. The new edge
12154 // uses `(payment, catalog)` — a pair the fixture doesn't
12155 // already declare in either direction (the fixture carries
12156 // `cart -> catalog` and `cart -> payment`, so `payment ->
12157 // catalog` doesn't form a cycle on the sync subgraph) — with
12158 // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
12159 // slot-shape gate fires cleanly after the wit-shape gate
12160 // (which `"wasi:keyvalue/store"` passes). Same edge pair the
12161 // peer `contrato_subject_err` helper uses (63e18a0).
12162 let mut s = three_member_spec();
12163 s.contratos.push(WitContract {
12164 de: "payment".into(),
12165 para: "catalog".into(),
12166 wit: "wasi:keyvalue/store".into(),
12167 endpoint: None,
12168 subject: None,
12169 slot: Some(slot.into()),
12170 });
12171 s.validate().unwrap_err()
12172 }
12173
12174 #[test]
12175 fn rejects_store_contrato_slot_with_whitespace() {
12176 // Fail-before-pass-after pin — pre-gate `"check out/$order"`
12177 // silently landed at the kv backend with whitespace whose
12178 // runtime behavior varies unpredictably across backends (etcd
12179 // accepts, Redis accepts then breaks on next CLI op, DynamoDB
12180 // rejects on write). Now caught at the source caixa.lisp.
12181 let err = contrato_slot_err("check out/$order");
12182 assert!(
12183 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12184 if slot == "check out/$order" && reason.contains("whitespace")),
12185 "got {err:?}"
12186 );
12187 }
12188
12189 #[test]
12190 fn rejects_store_contrato_slot_with_tab() {
12191 // Tab byte arm-pinned separately from the space arm so a
12192 // future relaxation that admits one but not the other surfaces
12193 // here.
12194 let err = contrato_slot_err("check\tout");
12195 assert!(
12196 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12197 if slot == "check\tout" && reason.contains("whitespace")),
12198 "got {err:?}"
12199 );
12200 }
12201
12202 #[test]
12203 fn rejects_store_contrato_slot_with_control_char() {
12204 // SOH (0x01) — distinct from the whitespace arm. Redis admits
12205 // and corrupts on RESP protocol framing; DynamoDB rejects on
12206 // write.
12207 let err = contrato_slot_err("checkout/\x01order");
12208 assert!(
12209 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12210 if slot == "checkout/\x01order" && reason.contains("control character")),
12211 "got {err:?}"
12212 );
12213 }
12214
12215 #[test]
12216 fn rejects_store_contrato_slot_with_newline() {
12217 // Embedded newline — the canonical "the paste-from-binary slug
12218 // spans multiple lines" footgun. Distinct from the whitespace
12219 // arm because `\n` is a control character (0x0A).
12220 let err = contrato_slot_err("checkout\norder");
12221 assert!(
12222 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12223 if slot == "checkout\norder" && reason.contains("control character")),
12224 "got {err:?}"
12225 );
12226 }
12227
12228 #[test]
12229 fn rejects_store_contrato_slot_with_non_ascii() {
12230 // Un-percent-encoded non-ASCII byte — the canonical "I copied
12231 // the slot from a doc with accented characters" footgun. Each
12232 // kv backend re-encodes non-ASCII differently (etcd preserves
12233 // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
12234 // rejects), so the typed slot's value set is the intersection-
12235 // floor every backend admits identically (printable ASCII).
12236 let err = contrato_slot_err("ch\u{e9}ckout/$order");
12237 assert!(
12238 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12239 if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
12240 "got {err:?}"
12241 );
12242 }
12243
12244 #[test]
12245 fn rejects_store_contrato_slot_too_long() {
12246 // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
12247 // legitimate-shape arms all pass (a single all-`a` token, no
12248 // separators); only the cap arm fires. Surfaces the paste-
12249 // from-binary / accidental-multi-line-blob landing footgun.
12250 // Mirrors `rejects_pubsub_contrato_subject_too_long` and
12251 // `rejects_http_contrato_endpoint_too_long` on the peer
12252 // payload axes.
12253 let big = "a".repeat(513);
12254 assert_eq!(big.len(), 513);
12255 let err = contrato_slot_err(&big);
12256 assert!(
12257 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12258 if slot == &big && reason.contains("max length of 512")),
12259 "got {err:?}"
12260 );
12261 }
12262
12263 #[test]
12264 fn store_contrato_slot_max_length_validates() {
12265 // 512-byte slot — exactly the cap. Boundary pin: drift in the
12266 // cap surfaces here and at `rejects_store_contrato_slot_too_long`
12267 // simultaneously, mirroring
12268 // `pubsub_contrato_subject_max_length_validates` and
12269 // `http_contrato_endpoint_max_length_validates` on the peer
12270 // payload axes.
12271 let big = "a".repeat(512);
12272 assert_eq!(big.len(), 512);
12273 let mut s = three_member_spec();
12274 s.contratos.push(WitContract {
12275 de: "payment".into(),
12276 para: "catalog".into(),
12277 wit: "wasi:keyvalue/store".into(),
12278 endpoint: None,
12279 subject: None,
12280 slot: Some(big),
12281 });
12282 s.validate().unwrap();
12283 }
12284
12285 #[test]
12286 fn store_contrato_slot_accepts_canonical_forms() {
12287 // Positive-set sweep: every canonical kv slot template the
12288 // substrate-side `is_wasi_keyvalue_slot` predicate accepts
12289 // (single-token identifiers, path-namespaced `$`-templates,
12290 // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
12291 // snake_case / kebab-case / MixedCase tokens, digit-bearing
12292 // tokens, percent-encoded fragments) must remain valid
12293 // contrato slots too. Drift between this list and the
12294 // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
12295 // surfaces at the shared predicate — one source of truth.
12296 // Uses a fresh `(payment, catalog)` edge so none of the swept
12297 // slots collide with the pre-existing entries in
12298 // `three_member_spec`.
12299 for slot in [
12300 "checkout",
12301 "checkout/$orderId",
12302 "users:{tenant}/{id}",
12303 "session.<sid>",
12304 "session.tokens.<sid>",
12305 "snake_case_key",
12306 "kebab-case-key",
12307 "MixedCase",
12308 "shard0",
12309 "v2/key",
12310 "users/caf%C3%A9",
12311 ] {
12312 let mut s = three_member_spec();
12313 s.contratos.push(WitContract {
12314 de: "payment".into(),
12315 para: "catalog".into(),
12316 wit: "wasi:keyvalue/store".into(),
12317 endpoint: None,
12318 subject: None,
12319 slot: Some(slot.into()),
12320 });
12321 s.validate()
12322 .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
12323 }
12324 }
12325
12326 #[test]
12327 fn contrato_slot_empty_takes_precedence_over_invalid() {
12328 // Ordering pin: `ContratoSlotEmpty` is the more self-locating
12329 // diagnostic on `""` and must lead — the value-shape gate is
12330 // only reached after the empty-check fires. Mirrors
12331 // `contrato_subject_empty_takes_precedence_over_invalid` and
12332 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12333 // the peer payload axes.
12334 let mut s = three_member_spec();
12335 s.contratos.push(WitContract {
12336 de: "payment".into(),
12337 para: "catalog".into(),
12338 wit: "wasi:keyvalue/store".into(),
12339 endpoint: None,
12340 subject: None,
12341 slot: Some(String::new()),
12342 });
12343 let err = s.validate().unwrap_err();
12344 assert!(
12345 matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
12346 "got {err:?}"
12347 );
12348 }
12349
12350 #[test]
12351 fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
12352 // Diagnostic-shape pin — the offending `:slot` + `:de` +
12353 // `:para` + a non-empty reason flow through verbatim so the
12354 // author can grep their caixa.lisp for the offending contrato
12355 // block and fix it in one edit. Same shape as
12356 // `contrato_subject_invalid_diagnostic_carries_offending_subject`
12357 // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12358 // on the peer payload axes.
12359 let err = contrato_slot_err("check out/$order");
12360 match err {
12361 AplicacaoError::ContratoSlotInvalid {
12362 de,
12363 para,
12364 slot,
12365 reason,
12366 } => {
12367 assert_eq!(de, "payment");
12368 assert_eq!(para, "catalog");
12369 assert_eq!(slot, "check out/$order");
12370 assert!(!reason.is_empty(), "reason field must be non-empty");
12371 }
12372 other => panic!("expected ContratoSlotInvalid, got {other:?}"),
12373 }
12374 }
12375
12376 #[test]
12377 fn target_view_store_slot_passes_through_to_typed_view() {
12378 // The compounding theorem on the store axis: every
12379 // `WitTarget::Store { slot }` returned by `target()` carries a
12380 // kv-backend-accepted slot template. Renderers downstream of
12381 // `typed_view()` (the future per-Servico `:capabilities
12382 // wasi:keyvalue/store` axis emitter, the future `feira app
12383 // graph` view's slot labeller, the future kv-provider CR
12384 // materializer) can rely on this without re-checking — the
12385 // type system carries the proof. Mirrors
12386 // `target_view_pubsub_subject_passes_through_to_typed_view` on
12387 // the peer payload axis.
12388 let store = WitContract {
12389 de: "a".into(),
12390 para: "b".into(),
12391 wit: "wasi:keyvalue/store".into(),
12392 endpoint: None,
12393 subject: None,
12394 slot: Some("checkout/$orderId".into()),
12395 };
12396 match store.target().unwrap() {
12397 WitTarget::Store { slot } => {
12398 assert_eq!(slot, "checkout/$orderId");
12399 }
12400 other => panic!("expected Store, got {other:?}"),
12401 }
12402 }
12403
12404 #[test]
12405 fn rejects_self_loop_in_synchronous_contratos() {
12406 // A synchronous self-edge (`cart → cart` over HTTP) is now
12407 // rejected by the dedicated `ContratoSelfLoop` gate — a precise
12408 // "this edge is degenerate" diagnostic — rather than incidentally
12409 // by the cycle detector framing it as a `["cart", "cart"]`
12410 // multi-node deadlock.
12411 let mut s = three_member_spec();
12412 s.contratos.push(contract_http("cart", "cart", "/loop"));
12413 let err = s.validate().unwrap_err();
12414 match err {
12415 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12416 assert_eq!(caixa, "cart");
12417 assert_eq!(wit, "wasi:http/proxy");
12418 }
12419 other => panic!("expected ContratoSelfLoop, got {other:?}"),
12420 }
12421 }
12422
12423 #[test]
12424 fn rejects_self_loop_in_pubsub_contratos() {
12425 // The cycle detector excludes pub-sub edges (acyclic by
12426 // construction), so before the explicit gate a `nats:pub-sub`
12427 // self-edge silently validated and rendered a self-allow CNP.
12428 // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
12429 let mut s = three_member_spec();
12430 s.contratos.push(WitContract {
12431 de: "payment".into(),
12432 para: "payment".into(),
12433 wit: "nats:pub-sub".into(),
12434 endpoint: None,
12435 subject: Some("rio.events.payment".into()),
12436 slot: None,
12437 });
12438 let err = s.validate().unwrap_err();
12439 match err {
12440 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12441 assert_eq!(caixa, "payment");
12442 assert_eq!(wit, "nats:pub-sub");
12443 }
12444 other => panic!("expected ContratoSelfLoop, got {other:?}"),
12445 }
12446 }
12447
12448 #[test]
12449 fn self_loop_fires_before_payload_shape_check() {
12450 // The structural "this edge can't exist" error precedes the
12451 // narrower payload-shape diagnostics: a self-edge carrying an
12452 // otherwise-malformed endpoint still reports ContratoSelfLoop,
12453 // not ContratoEndpointInvalid.
12454 let mut s = three_member_spec();
12455 s.contratos.push(WitContract {
12456 de: "cart".into(),
12457 para: "cart".into(),
12458 wit: "wasi:http/proxy".into(),
12459 endpoint: Some("not-absolute".into()),
12460 subject: None,
12461 slot: None,
12462 });
12463 match s.validate().unwrap_err() {
12464 AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
12465 other => panic!("expected ContratoSelfLoop, got {other:?}"),
12466 }
12467 }
12468
12469 #[test]
12470 fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
12471 // A self-edge naming a non-member reports the more fundamental
12472 // ContratoMemberMissing first (the member doesn't exist), so the
12473 // self-loop gate is reached only once both endpoints resolve.
12474 let mut s = three_member_spec();
12475 s.contratos.push(contract_http("ghost", "ghost", "/loop"));
12476 match s.validate().unwrap_err() {
12477 AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
12478 other => panic!("expected ContratoMemberMissing, got {other:?}"),
12479 }
12480 }
12481
12482 #[test]
12483 fn rejects_two_node_synchronous_cycle() {
12484 let mut s = three_member_spec();
12485 // existing edges: cart → catalog, cart → payment
12486 // adding catalog → cart closes a 2-cycle on the HTTP subgraph
12487 s.contratos
12488 .push(contract_http("catalog", "cart", "/refresh"));
12489 let err = s.validate().unwrap_err();
12490 match err {
12491 AplicacaoError::ContratoCycle { cycle } => {
12492 // Cycle traversal should mention both endpoints, with
12493 // the back-edge target appearing as both first and last
12494 // element to close the loop.
12495 assert!(cycle.len() >= 3);
12496 assert_eq!(cycle.first(), cycle.last());
12497 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12498 assert!(body.contains("cart"));
12499 assert!(body.contains("catalog"));
12500 }
12501 other => panic!("expected ContratoCycle, got {other:?}"),
12502 }
12503 }
12504
12505 #[test]
12506 fn rejects_three_node_synchronous_cycle() {
12507 let mut s = three_member_spec();
12508 // Reset to a clean 3-cycle: catalog → cart → payment → catalog
12509 s.contratos = vec![
12510 contract_http("catalog", "cart", "/x"),
12511 contract_http("cart", "payment", "/y"),
12512 contract_http("payment", "catalog", "/z"),
12513 ];
12514 let err = s.validate().unwrap_err();
12515 match err {
12516 AplicacaoError::ContratoCycle { cycle } => {
12517 assert_eq!(cycle.first(), cycle.last());
12518 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12519 assert_eq!(body.len(), 3);
12520 assert!(body.contains("cart"));
12521 assert!(body.contains("catalog"));
12522 assert!(body.contains("payment"));
12523 }
12524 other => panic!("expected ContratoCycle, got {other:?}"),
12525 }
12526 }
12527
12528 #[test]
12529 fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
12530 // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
12531 // "acyclic by construction" — so a cycle whose closing edge
12532 // is pub-sub should NOT raise ContratoCycle.
12533 let mut s = three_member_spec();
12534 s.contratos = vec![
12535 contract_http("catalog", "cart", "/x"),
12536 contract_http("cart", "payment", "/y"),
12537 // Closing edge is pub-sub — async; not a sync deadlock.
12538 WitContract {
12539 de: "payment".into(),
12540 para: "catalog".into(),
12541 wit: "nats:pub-sub".into(),
12542 endpoint: None,
12543 subject: Some("checkout.events.charge.completed".into()),
12544 slot: None,
12545 },
12546 ];
12547 s.validate().expect("pub-sub edge breaks the sync cycle");
12548 }
12549
12550 #[test]
12551 fn store_edge_counts_as_synchronous_for_cycle_detection() {
12552 // wasi:keyvalue/store is request/response; a cycle through one
12553 // *is* a sync deadlock, just like HTTP.
12554 let mut s = three_member_spec();
12555 s.contratos = vec![
12556 contract_http("catalog", "cart", "/x"),
12557 WitContract {
12558 de: "cart".into(),
12559 para: "catalog".into(),
12560 wit: "wasi:keyvalue/store".into(),
12561 endpoint: None,
12562 subject: None,
12563 slot: Some("session/$id".into()),
12564 },
12565 ];
12566 let err = s.validate().unwrap_err();
12567 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12568 }
12569
12570 #[test]
12571 fn capability_edge_counts_as_synchronous_for_cycle_detection() {
12572 // Capability-only edges (unknown WIT shape, no payload) default
12573 // to synchronous — safer; authors with truly async capability
12574 // semantics can model them as pub-sub explicitly.
12575 let mut s = three_member_spec();
12576 s.contratos = vec![
12577 contract_http("catalog", "cart", "/x"),
12578 WitContract {
12579 de: "cart".into(),
12580 para: "catalog".into(),
12581 wit: "custom:exchange".into(),
12582 endpoint: None,
12583 subject: None,
12584 slot: None,
12585 },
12586 ];
12587 let err = s.validate().unwrap_err();
12588 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12589 }
12590
12591 #[test]
12592 fn long_acyclic_chain_validates() {
12593 // A long sync chain (no back-edges) must validate even when
12594 // every node is reachable from the first.
12595 let mut s = three_member_spec();
12596 s.membros = vec![
12597 membro("a", "^0.1"),
12598 membro("b", "^0.1"),
12599 membro("c", "^0.1"),
12600 membro("d", "^0.1"),
12601 membro("e", "^0.1"),
12602 ];
12603 s.contratos = vec![
12604 contract_http("a", "b", "/1"),
12605 contract_http("b", "c", "/2"),
12606 contract_http("c", "d", "/3"),
12607 contract_http("d", "e", "/4"),
12608 ];
12609 s.entrada.as_mut().unwrap().para = "a".into();
12610 s.validate().unwrap();
12611 }
12612
12613 #[test]
12614 fn diamond_acyclic_validates() {
12615 // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
12616 let mut s = three_member_spec();
12617 s.membros = vec![
12618 membro("a", "^0.1"),
12619 membro("b", "^0.1"),
12620 membro("c", "^0.1"),
12621 membro("d", "^0.1"),
12622 ];
12623 s.contratos = vec![
12624 contract_http("a", "b", "/1"),
12625 contract_http("a", "c", "/2"),
12626 contract_http("b", "d", "/3"),
12627 contract_http("c", "d", "/4"),
12628 ];
12629 s.entrada.as_mut().unwrap().para = "a".into();
12630 s.validate().unwrap();
12631 }
12632
12633 // ── duplicate-`:contratos` build-error gate ──────────────────────────
12634
12635 #[test]
12636 fn rejects_duplicate_http_contrato() {
12637 // Fail-before-pass-after pin: the fixture's `cart → catalog`
12638 // HTTP edge appears once. Push an identical entry — same
12639 // (de, para, wit, endpoint) — and validate() must reject it.
12640 // Until this gate landed the typed surface accepted the
12641 // duplicate silently and caixa-mesh's `cilium_network_policies`
12642 // emitted two ``CiliumNetworkPolicy`` objects with identical
12643 // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
12644 // admission rejects on `kubectl apply` far from the source.
12645 let mut s = three_member_spec();
12646 s.contratos
12647 .push(contract_http("cart", "catalog", "/products/:id"));
12648 let err = s.validate().unwrap_err();
12649 assert!(
12650 matches!(
12651 err,
12652 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12653 if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
12654 ),
12655 "got {err:?}"
12656 );
12657 }
12658
12659 #[test]
12660 fn rejects_duplicate_pubsub_contrato() {
12661 // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
12662 // edges with identical (de, para, subject) are degenerate;
12663 // pin that the typed surface refuses both at validate time.
12664 let mut s = three_member_spec();
12665 let pubsub = WitContract {
12666 de: "payment".into(),
12667 para: "cart".into(),
12668 wit: "nats:pub-sub".into(),
12669 endpoint: None,
12670 subject: Some("checkout.events.charge.failed".into()),
12671 slot: None,
12672 };
12673 s.contratos.push(pubsub.clone());
12674 s.contratos.push(pubsub);
12675 let err = s.validate().unwrap_err();
12676 assert!(
12677 matches!(
12678 err,
12679 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12680 if de == "payment" && para == "cart" && wit == "nats:pub-sub"
12681 ),
12682 "got {err:?}"
12683 );
12684 }
12685
12686 #[test]
12687 fn rejects_duplicate_store_contrato() {
12688 // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
12689 // edges with identical (de, para, slot) collapse to one mesh-
12690 // policy edge; pin the build error.
12691 let mut s = three_member_spec();
12692 let store = WitContract {
12693 de: "cart".into(),
12694 para: "payment".into(),
12695 wit: "wasi:keyvalue/store".into(),
12696 endpoint: None,
12697 subject: None,
12698 slot: Some("checkout/$orderId".into()),
12699 };
12700 // Drop the conflicting HTTP `cart → payment` edge from the
12701 // fixture so the duplicate-store pair is the only one
12702 // distinguishable on this pair.
12703 s.contratos
12704 .retain(|c| !(c.de == "cart" && c.para == "payment"));
12705 s.contratos.push(store.clone());
12706 s.contratos.push(store);
12707 let err = s.validate().unwrap_err();
12708 assert!(
12709 matches!(
12710 err,
12711 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12712 if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
12713 ),
12714 "got {err:?}"
12715 );
12716 }
12717
12718 #[test]
12719 fn rejects_duplicate_capability_contrato() {
12720 // Same gate on the pure-capability axis (no payload selector).
12721 // Two contracts with identical (de, para, wit) and no
12722 // endpoint/subject/slot are duplicate edges; pin so a future
12723 // `target_label` change can't accidentally collapse the
12724 // capability arm into a None-shaped key that compares equal
12725 // to a populated one.
12726 let mut s = three_member_spec();
12727 let capability = WitContract {
12728 de: "cart".into(),
12729 para: "catalog".into(),
12730 wit: "pleme:cap/audit".into(),
12731 endpoint: None,
12732 subject: None,
12733 slot: None,
12734 };
12735 s.contratos.push(capability.clone());
12736 s.contratos.push(capability);
12737 let err = s.validate().unwrap_err();
12738 match err {
12739 AplicacaoError::ContratoDuplicate {
12740 de,
12741 para,
12742 wit,
12743 target,
12744 } => {
12745 assert_eq!(de, "cart");
12746 assert_eq!(para, "catalog");
12747 assert_eq!(wit, "pleme:cap/audit");
12748 assert!(
12749 target.contains("capability"),
12750 "capability-edge duplicate diagnostic must surface the \
12751 no-payload shape (got target = {target:?})"
12752 );
12753 }
12754 other => panic!("expected ContratoDuplicate, got {other:?}"),
12755 }
12756 }
12757
12758 #[test]
12759 fn accepts_distinct_http_paths_between_same_pair() {
12760 // Negative pin: two HTTP contracts cart → catalog at distinct
12761 // endpoints (`/products/:id` and `/search`) are *not*
12762 // duplicates — they're distinct typed edges differing on the
12763 // payload axis. The duplicate-gate must not over-match here,
12764 // since the cart-calls-catalog-on-multiple-paths shape is the
12765 // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
12766 // example: cart calls catalog at /products/:id, payment at
12767 // /charge — same shape extends to two paths on one para).
12768 let mut s = three_member_spec();
12769 s.contratos
12770 .push(contract_http("cart", "catalog", "/search"));
12771 s.validate()
12772 .expect("distinct endpoints between same (de, para) must validate");
12773 }
12774
12775 #[test]
12776 fn accepts_same_endpoint_on_different_pairs() {
12777 // Negative pin: the same `/charge` endpoint reused on two
12778 // different (de, para) pairs is two distinct edges, not a
12779 // duplicate. Pinning this shape so the gate's identity key
12780 // includes both `de` and `para` (not just `(wit, endpoint)`).
12781 let mut s = three_member_spec();
12782 s.contratos
12783 .push(contract_http("payment", "catalog", "/charge"));
12784 s.validate()
12785 .expect("same endpoint reused on distinct (de, para) must validate");
12786 }
12787
12788 #[test]
12789 fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
12790 // Pin the diagnostic shape: the duplicate-edge error names
12791 // *which* target field carried the conflict, so the author
12792 // doesn't have to re-grep the source caixa.lisp to find it.
12793 // Same self-locating diagnostic discipline as
12794 // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
12795 let mut s = three_member_spec();
12796 s.contratos
12797 .push(contract_http("cart", "catalog", "/products/:id"));
12798 let err = s.validate().unwrap_err();
12799 let msg = format!("{err}");
12800 assert!(
12801 msg.contains("\"/products/:id\""),
12802 "duplicate-contrato diagnostic must name the offending \
12803 :endpoint payload (got: {msg:?})"
12804 );
12805 assert!(
12806 msg.contains("cart") && msg.contains("catalog"),
12807 "diagnostic must name both endpoints of the duplicate edge \
12808 (got: {msg:?})"
12809 );
12810 }
12811
12812 #[test]
12813 fn duplicate_contrato_gate_runs_after_membership_check() {
12814 // Order pin: a duplicate contract whose `:de` is *also* not in
12815 // `:membros` surfaces the membership error first — the
12816 // missing-member diagnostic is more locating than the
12817 // duplicate-edge one (the author has to fix the membership
12818 // before the duplicate is meaningful). Same ordering
12819 // discipline as `membros_validation_runs_before_contratos_membership_check`.
12820 let mut s = three_member_spec();
12821 s.contratos.push(contract_http("phantom", "catalog", "/x"));
12822 s.contratos.push(contract_http("phantom", "catalog", "/x"));
12823 let err = s.validate().unwrap_err();
12824 assert!(
12825 matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
12826 "membership-missing must fire before duplicate-edge (got {err:?})"
12827 );
12828 }
12829
12830 #[test]
12831 fn duplicate_contrato_gate_runs_after_target_shape_check() {
12832 // Order pin: a contract with a malformed target (e.g. an HTTP
12833 // wit world with an empty :endpoint) surfaces the target-shape
12834 // error first, not the duplicate one. Even when two such
12835 // malformed entries are identical, the per-contract `target()`
12836 // check fires inside the loop *before* the duplicate-key
12837 // insert, so the diagnostic remains the most-locating one.
12838 let mut s = three_member_spec();
12839 let malformed = WitContract {
12840 de: "cart".into(),
12841 para: "catalog".into(),
12842 wit: "wasi:http/proxy".into(),
12843 endpoint: Some(String::new()),
12844 subject: None,
12845 slot: None,
12846 };
12847 s.contratos.push(malformed.clone());
12848 s.contratos.push(malformed);
12849 let err = s.validate().unwrap_err();
12850 assert!(
12851 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
12852 "endpoint-empty must fire before duplicate-edge (got {err:?})"
12853 );
12854 }
12855
12856 #[test]
12857 fn wit_target_label_pins_per_variant_format() {
12858 // Label format is the single source of truth every duplicate-
12859 // `:contratos` diagnostic + every future `feira app graph`
12860 // consumer routes through. Pin the shape per variant so a
12861 // future edit to `WitTarget::label` (e.g. a JSON emitter that
12862 // strips the leading `:`, or a rename from `endpoint` →
12863 // `path`) surfaces as a red-red test rather than as a silent
12864 // downstream diagnostic drift. Together with the exhaustive
12865 // `match` on `WitTarget` inside `label()`, adding a future
12866 // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
12867 // peer, per-edge WIT registry variants) is a compile error at
12868 // the label site — not a fall-through into the `Capability`
12869 // "no payload" default the prior raw-field-probe helper
12870 // silently landed on.
12871 assert_eq!(
12872 WitTarget::Http {
12873 endpoint: "/charge",
12874 }
12875 .label(),
12876 "\
12877:endpoint \"/charge\""
12878 );
12879 assert_eq!(
12880 WitTarget::PubSub {
12881 subject: "events.checkout.paid",
12882 }
12883 .label(),
12884 "\
12885:subject \"events.checkout.paid\""
12886 );
12887 assert_eq!(
12888 WitTarget::Store {
12889 slot: "checkout/$order",
12890 }
12891 .label(),
12892 "\
12893:slot \"checkout/$order\""
12894 );
12895 assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
12896 // Capability-arm label routes through the lifted
12897 // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
12898 // declaration per arm, next to the variant" discipline the
12899 // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
12900 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12901 // consts already carry extends to the payload-less arm; the
12902 // byte-string equality pin below plus this label-routes-
12903 // through-the-const pin make a future rebrand on either the
12904 // const declaration or the `label()` template a build error
12905 // here rather than a downstream consumer surprise.
12906 assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
12907 assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
12908 }
12909
12910 #[test]
12911 fn wit_target_display_routes_through_label_helper() {
12912 // Fail-before-pass-after pin on the fourth (and only remaining)
12913 // typed-shape-discriminator axis to converge onto the
12914 // three-path-convergence discipline the sibling M3
12915 // [`PlacementStrategy`] (0a2f653) and M2
12916 // [`crate::supervisor::RestartStrategy`] /
12917 // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
12918 // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
12919 // through [`WitTarget::label`], so every consumer reaching for
12920 // `format!("{v}")` on a typed payload target lands on the same
12921 // stable author-facing byte-string [`WitTarget::label`] returns
12922 // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
12923 // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
12924 // `:contratos` gate seeds via [`WitTarget::label`] at
12925 // aplicacao.rs:5491 already threads through.
12926 //
12927 // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
12928 // through to the `Debug` derive's structural output
12929 // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
12930 // rather than the [`WitTarget::label`] helper's stable byte-
12931 // string (`:endpoint "/charge"` — the author-facing `:contratos`
12932 // keyword form). Every future consumer that reaches for
12933 // `format!("{target}")` — the canonical shape every user-facing
12934 // pretty-print site on the sibling typed-enum axes
12935 // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
12936 // [`crate::supervisor::RestartPolicy`]) already uses — would
12937 // silently land under a different byte-string than the
12938 // [`WitTarget::label`] callers that the duplicate-`:contratos`
12939 // diagnostic already threads through, with the mismatch
12940 // surfacing as a downstream diagnostic / graph / audit line
12941 // reading one spelling while the substrate's own gate emitted
12942 // another.
12943 //
12944 // Pin the routing here so a future
12945 // `impl std::fmt::Display for WitTarget<'_>` reimplementation
12946 // that hand-rolls the per-arm formatting instead of delegating
12947 // to [`WitTarget::label`] fails at caixa-core build time.
12948 for variant in [
12949 WitTarget::Http {
12950 endpoint: "/charge",
12951 },
12952 WitTarget::PubSub {
12953 subject: "events.checkout.paid",
12954 },
12955 WitTarget::Store {
12956 slot: "checkout/$order",
12957 },
12958 WitTarget::Capability,
12959 ] {
12960 assert_eq!(
12961 variant.to_string(),
12962 variant.label(),
12963 "WitTarget::{variant:?} Display must route through \
12964 WitTarget::label (single source of truth: the lifted \
12965 payload_pair 4-arm dispatch the label helper already \
12966 threads through)"
12967 );
12968 }
12969 }
12970
12971 #[test]
12972 fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
12973 // Consumer-side pin on the three-path convergence:
12974 // [`std::fmt::Display`] agrees byte-for-byte with the
12975 // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
12976 // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
12977 // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
12978 // Pre-lift the two paths were structurally independent — the
12979 // substrate-side gate reached for `target_view.label()` while a
12980 // future downstream diagnostic / graph / audit line reaching
12981 // for `format!("{target}")` would silently land on the `Debug`
12982 // derive's structural output. Pin the two paths byte-for-byte
12983 // here so any future variant addition (M4 `Rest`/`Grpc` split
12984 // of [`WitTarget::Http`], `Queue`-shaped peer of
12985 // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
12986 // match error at [`WitTarget::payload_pair`] rather than a
12987 // silent per-consumer dispatch miss.
12988 for variant in [
12989 WitTarget::Http {
12990 endpoint: "/charge",
12991 },
12992 WitTarget::PubSub {
12993 subject: "events.checkout.paid",
12994 },
12995 WitTarget::Store {
12996 slot: "checkout/$order",
12997 },
12998 WitTarget::Capability,
12999 ] {
13000 assert_eq!(
13001 format!("{variant}"),
13002 variant.label(),
13003 "WitTarget::{variant:?} Display byte-string must match \
13004 the AplicacaoError::ContratoDuplicate `target:` carrier \
13005 the AplicacaoSpec::validate duplicate-`:contratos` gate \
13006 seeds via WitTarget::label — three-path convergence: \
13007 Display + label + payload_pair all resolve to the same \
13008 per-arm byte-string"
13009 );
13010 }
13011 }
13012
13013 #[test]
13014 fn wit_target_payload_pair_pins_per_variant() {
13015 // Pin the per-arm `(field-name, payload)` pair single-sourced
13016 // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
13017 // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
13018 // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
13019 // and [`WitTarget::field_name`] (returns the first component)
13020 // route through. Until this lift landed [`WitTarget::label`]
13021 // dispatched on the same three arms with a per-arm
13022 // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
13023 // paired [`WitTarget::HTTP_FIELD_NAME`] /
13024 // [`WitTarget::PUBSUB_FIELD_NAME`] /
13025 // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
13026 // canonical "same shape, written N times" duplication
13027 // THEORY.md §I.3.5 promotes to a build-time concern. A future
13028 // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
13029 // [`WitTarget::Http`], `Queue`-shaped peer of
13030 // [`WitTarget::Store`]) is one match-arm edit at
13031 // [`WitTarget::payload_pair`], visible here as a compile-time
13032 // exhaustiveness error on both this pin and the label-format
13033 // pin above.
13034 assert_eq!(
13035 WitTarget::Http {
13036 endpoint: "/charge"
13037 }
13038 .payload_pair(),
13039 Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
13040 );
13041 assert_eq!(
13042 WitTarget::PubSub {
13043 subject: "events.x",
13044 }
13045 .payload_pair(),
13046 Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
13047 );
13048 assert_eq!(
13049 WitTarget::Store {
13050 slot: "checkout/$order",
13051 }
13052 .payload_pair(),
13053 Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
13054 );
13055 assert_eq!(WitTarget::Capability.payload_pair(), None);
13056 }
13057
13058 #[test]
13059 fn wit_target_field_name_pins_per_variant() {
13060 // Pin the per-arm author-facing `:contratos` payload field
13061 // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
13062 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13063 // + returned by [`WitTarget::field_name`]. Every downstream
13064 // consumer (the [`WitContract::target`] gate's `expected:`
13065 // scalar, the [`WitTarget::label`] template's keyword prefix,
13066 // the `feira app graph` verb's `endpoint=…` prefix) routes
13067 // through the same three peer consts, so a rename on the
13068 // author-surface `(defcaixa … :contratos ((:de … :para …
13069 // :wit … :endpoint …)))` field lands in exactly one place.
13070 assert_eq!(
13071 WitTarget::Http {
13072 endpoint: "/charge"
13073 }
13074 .field_name(),
13075 Some(WitTarget::HTTP_FIELD_NAME),
13076 );
13077 assert_eq!(
13078 WitTarget::PubSub {
13079 subject: "events.x",
13080 }
13081 .field_name(),
13082 Some(WitTarget::PUBSUB_FIELD_NAME),
13083 );
13084 assert_eq!(
13085 WitTarget::Store {
13086 slot: "checkout/$order",
13087 }
13088 .field_name(),
13089 Some(WitTarget::STORE_FIELD_NAME),
13090 );
13091 // Capability arm carries no payload field — the diagnostic
13092 // never reports `expected: "capability"` because the gate's
13093 // Capability arm accepts no payload at all (it fires the
13094 // "expected: none" WrongTarget error instead), so the field-
13095 // name method returns None here rather than a placeholder.
13096 assert_eq!(WitTarget::Capability.field_name(), None);
13097
13098 // Peer const scalar values pinned so a rename on either side
13099 // (author-surface field name in the `(defcaixa …)` DSL, or
13100 // the diagnostic's `expected:` scalar) can't drift without
13101 // failing here first.
13102 assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
13103 assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
13104 assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
13105 }
13106
13107 #[test]
13108 fn wit_target_payload_pins_per_variant() {
13109 // Pin the per-arm payload scalar single-sourced onto the
13110 // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
13111 // [`WitTarget::payload`] — the peer per-half projection to
13112 // [`WitTarget::field_name`] on the paired sub-selector axis. The
13113 // three payload-carrying arms round-trip their author-declared
13114 // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
13115 // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
13116 // the payload-less [`WitTarget::Capability`] arm returns `None`.
13117 // Same shape as the sibling `wit_target_field_name_pins_per_variant`
13118 // (c6ec2af) pin on the Component-0 projection axis, extended
13119 // onto the Component-1 projection axis so both per-half readers
13120 // on the paired dispatch carry their own byte-shape pin.
13121 assert_eq!(
13122 WitTarget::Http {
13123 endpoint: "/charge",
13124 }
13125 .payload(),
13126 Some("/charge"),
13127 );
13128 assert_eq!(
13129 WitTarget::PubSub {
13130 subject: "events.x",
13131 }
13132 .payload(),
13133 Some("events.x"),
13134 );
13135 assert_eq!(
13136 WitTarget::Store {
13137 slot: "checkout/$order",
13138 }
13139 .payload(),
13140 Some("checkout/$order"),
13141 );
13142 assert_eq!(WitTarget::Capability.payload(), None);
13143 }
13144
13145 #[test]
13146 fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
13147 // Per-variant equivalence pin: for every arm of [`WitTarget`],
13148 // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
13149 // byte-for-byte. Guards the drift surface where a future refactor
13150 // that split one accessor off the shared match onto its own
13151 // dispatch — a well-meaning "inline the pair back into per-half
13152 // fields for one crate-internal caller who only wanted one half"
13153 // or a scratch `impl` shadowing the derived projection — would
13154 // silently desynchronize [`WitTarget::payload`] from the
13155 // authoritative [`WitTarget::payload_pair`] dispatch, and every
13156 // downstream consumer that thinks "the payload half of the pair"
13157 // would drift from the diagnostic / graph consumers reading the
13158 // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
13159 // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
13160 // per-half projection pin (`gitrefspec_ref_pair_projects_
13161 // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
13162 // FluxCD source-controller `spec.ref.<field>` axis — same "one
13163 // paired dispatch, both per-half projections agree byte-for-
13164 // byte" discipline extended onto the M3 `:contratos` payload-
13165 // arm surface.
13166 for variant in [
13167 WitTarget::Http {
13168 endpoint: "/charge",
13169 },
13170 WitTarget::PubSub {
13171 subject: "events.checkout.paid",
13172 },
13173 WitTarget::Store {
13174 slot: "checkout/$order",
13175 },
13176 WitTarget::Capability,
13177 ] {
13178 let via_projection = variant.payload();
13179 let via_pair = variant.payload_pair().map(|(_, p)| p);
13180 assert_eq!(
13181 via_projection, via_pair,
13182 "WitTarget::{variant:?} payload() must equal \
13183 payload_pair().map(|(_, p)| p) byte-for-byte — a \
13184 regression that splits the two per-half projections off \
13185 their shared match would silently desynchronize the \
13186 payload accessor from the paired dispatch every \
13187 diagnostic / graph consumer reads through",
13188 );
13189 }
13190 }
13191
13192 #[test]
13193 fn wit_target_http_endpoint_pins_per_variant() {
13194 // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
13195 // [`WitTarget::http_endpoint`] 2-arm dispatch — the
13196 // substrate-primitive per-arm post-projection accessor every
13197 // L7-HTTP-facing consumer routes through, sibling to the peer
13198 // WitContract pre-projection [`WitContract::endpoint`] (7020470)
13199 // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
13200 // arm round-trips its author-declared endpoint verbatim as
13201 // `Some("/charge")`; the three sibling arms
13202 // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
13203 // [`WitTarget::Capability`]) each return `None` because they
13204 // carry no HTTP endpoint by definition. Same fail-before-pass-
13205 // after per-variant discipline as the sibling
13206 // `wit_target_payload_pins_per_variant` (5d6dc92) /
13207 // `wit_target_field_name_pins_per_variant` (c6ec2af) /
13208 // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
13209 // the peer pan-arm / per-half projection axes — extended onto
13210 // the per-arm HTTP-shape post-projection axis so a future
13211 // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
13212 // [`WitTarget::Http`], a `Queue`-shaped peer of
13213 // [`WitTarget::Store`]) trips a compile-time exhaustiveness
13214 // error on the sibling [`WitTarget::http_endpoint`] match arms
13215 // whose payload the L7-HTTP-shape accept-set is meant to bound.
13216 assert_eq!(
13217 WitTarget::Http {
13218 endpoint: "/charge",
13219 }
13220 .http_endpoint(),
13221 Some("/charge"),
13222 );
13223 assert_eq!(
13224 WitTarget::PubSub {
13225 subject: "events.checkout.paid",
13226 }
13227 .http_endpoint(),
13228 None,
13229 );
13230 assert_eq!(
13231 WitTarget::Store {
13232 slot: "checkout/$order",
13233 }
13234 .http_endpoint(),
13235 None,
13236 );
13237 assert_eq!(WitTarget::Capability.http_endpoint(), None);
13238 }
13239
13240 #[test]
13241 fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
13242 // Per-variant coherence pin: for every arm of [`WitTarget`],
13243 // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
13244 // arm (both project the same author-declared request-path
13245 // scalar), and returns `None` on every sibling arm regardless of
13246 // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
13247 // Store carry their own payload the pan-arm accessor surfaces,
13248 // but that payload is not an HTTP endpoint — the per-arm
13249 // accessor must not leak it through the HTTP-shape channel).
13250 // Guards the drift surface where a future refactor that
13251 // conflated the per-arm HTTP projection with the pan-arm
13252 // [`WitTarget::payload`] projection — a well-meaning "one
13253 // accessor for the L7 branch, one for the graph" collapse that
13254 // routes both through the same 4-arm dispatch — would silently
13255 // widen the L7-HTTP-shape accept-set onto pub-sub / store
13256 // payloads at the caixa-mesh L7 emit branch, admitting a
13257 // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
13258 // rule with the operator-side apply-time symptom (Cilium's
13259 // eBPF data-plane rejects every ingress edge whose L7 filter
13260 // doesn't match the wire-format HTTP request line) far from
13261 // the source refactor. Sibling to the peer
13262 // `wit_target_payload_matches_payload_pair_second_component_
13263 // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
13264 // extended onto the per-arm HTTP specialization axis so both
13265 // the pan-arm and the per-arm projections carry their own
13266 // byte-shape coherence witness against the substrate's typed
13267 // arm-family accept-set.
13268 for variant in [
13269 WitTarget::Http {
13270 endpoint: "/charge",
13271 },
13272 WitTarget::PubSub {
13273 subject: "events.checkout.paid",
13274 },
13275 WitTarget::Store {
13276 slot: "checkout/$order",
13277 },
13278 WitTarget::Capability,
13279 ] {
13280 let per_arm = variant.http_endpoint();
13281 let pan_arm = variant.payload();
13282 if variant.is_http() {
13283 assert_eq!(
13284 per_arm, pan_arm,
13285 "WitTarget::{variant:?} http_endpoint() must equal \
13286 payload() on the Http arm — a per-arm-vs-pan-arm \
13287 split would silently drift the L7 emit branch's \
13288 path-scalar source from the graph verb's payload \
13289 scalar source",
13290 );
13291 } else {
13292 assert_eq!(
13293 per_arm, None,
13294 "WitTarget::{variant:?} http_endpoint() must return \
13295 None on non-Http arms — a leak that surfaced a \
13296 pub-sub :subject or a key/value :slot through the \
13297 HTTP-endpoint accessor would silently widen the \
13298 Cilium L7 HTTP `path:` rule accept-set onto \
13299 protocol shapes Cilium's eBPF data-plane can't \
13300 introspect",
13301 );
13302 }
13303 }
13304 }
13305
13306 #[test]
13307 fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
13308 // Per-variant coherence pin: for every arm of [`WitTarget`],
13309 // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
13310 // drift surface where a future extension of the
13311 // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
13312 // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
13313 // accessor to cover both peers) landed without a paired
13314 // extension of the [`gen_platform::IsVariant`]-derived
13315 // `is_http()` predicate's accept-set, or vice versa — a
13316 // regression that split the "which arms count as HTTP-shaped
13317 // for L7-path emission?" answer between two dispatch surfaces
13318 // the substrate ships. Sibling to the peer
13319 // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
13320 // on the paired dispatch axis — extended onto the per-arm
13321 // predicate-vs-accessor coherence axis so the gen-platform
13322 // IsVariant predicate and the substrate-lifted per-arm
13323 // accessor carry one shared answer to "is this the HTTP arm?".
13324 for variant in [
13325 WitTarget::Http {
13326 endpoint: "/charge",
13327 },
13328 WitTarget::PubSub {
13329 subject: "events.checkout.paid",
13330 },
13331 WitTarget::Store {
13332 slot: "checkout/$order",
13333 },
13334 WitTarget::Capability,
13335 ] {
13336 assert_eq!(
13337 variant.http_endpoint().is_some(),
13338 variant.is_http(),
13339 "WitTarget::{variant:?} http_endpoint().is_some() must \
13340 equal is_http() — a drift would split the L7 emit \
13341 branch's arm-set gate from the substrate-derived \
13342 shape-discrimination predicate on the same axis",
13343 );
13344 }
13345 }
13346
13347 #[test]
13348 fn wit_target_pubsub_subject_pins_per_variant() {
13349 // Fail-before-pass-after pin: the substrate-canonical per-arm
13350 // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
13351 // is the single dispatch every future pub-sub-facing consumer
13352 // routes through, sibling to the peer [`WitContract::subject`]
13353 // (63e18a0) pre-projection scalar accessor on the raw-field
13354 // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
13355 // post-projection per-arm accessor on the sibling HTTP-shape
13356 // axis. The [`WitTarget::PubSub`] arm round-trips its
13357 // author-declared subject verbatim as
13358 // `Some("events.checkout.paid")`; the three sibling arms each
13359 // return `None` because they carry no NATS-shaped subject by
13360 // definition. Same fail-before-pass-after per-variant discipline
13361 // as the sibling `wit_target_http_endpoint_pins_per_variant`
13362 // pin on the peer per-arm axis — extended onto the per-arm
13363 // pub-sub-shape post-projection axis so a future [`WitTarget`]
13364 // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
13365 // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
13366 // compile-time exhaustiveness error on the sibling
13367 // [`WitTarget::pubsub_subject`] match arms whose payload the
13368 // pub-sub-shape accept-set is meant to bound.
13369 assert_eq!(
13370 WitTarget::PubSub {
13371 subject: "events.checkout.paid",
13372 }
13373 .pubsub_subject(),
13374 Some("events.checkout.paid"),
13375 );
13376 assert_eq!(
13377 WitTarget::Http {
13378 endpoint: "/charge",
13379 }
13380 .pubsub_subject(),
13381 None,
13382 );
13383 assert_eq!(
13384 WitTarget::Store {
13385 slot: "checkout/$order",
13386 }
13387 .pubsub_subject(),
13388 None,
13389 );
13390 assert_eq!(WitTarget::Capability.pubsub_subject(), None);
13391 }
13392
13393 #[test]
13394 fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
13395 // Per-variant coherence pin: for every arm of [`WitTarget`],
13396 // `.pubsub_subject()` equals `.payload()` on the
13397 // [`WitTarget::PubSub`] arm (both project the same
13398 // author-declared subject scalar), and returns `None` on every
13399 // sibling arm regardless of whether [`WitTarget::payload`]
13400 // itself returns `Some` (Http / Store carry their own payload
13401 // the pan-arm accessor surfaces, but that payload is not a
13402 // pub-sub subject — the per-arm accessor must not leak it
13403 // through the pub-sub-shape channel). Sibling to the peer
13404 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13405 // coherence pin on the per-arm HTTP-shape axis — extended onto
13406 // the per-arm pub-sub specialization axis so both per-arm
13407 // projections carry their own byte-shape coherence witness
13408 // against the substrate's typed arm-family accept-set.
13409 for variant in [
13410 WitTarget::Http {
13411 endpoint: "/charge",
13412 },
13413 WitTarget::PubSub {
13414 subject: "events.checkout.paid",
13415 },
13416 WitTarget::Store {
13417 slot: "checkout/$order",
13418 },
13419 WitTarget::Capability,
13420 ] {
13421 let per_arm = variant.pubsub_subject();
13422 let pan_arm = variant.payload();
13423 if variant.is_pubsub() {
13424 assert_eq!(
13425 per_arm, pan_arm,
13426 "WitTarget::{variant:?} pubsub_subject() must equal \
13427 payload() on the PubSub arm — a per-arm-vs-pan-arm \
13428 split would silently drift the pub-sub-shape emit \
13429 branch's subject-scalar source from the graph verb's \
13430 payload scalar source",
13431 );
13432 } else {
13433 assert_eq!(
13434 per_arm, None,
13435 "WitTarget::{variant:?} pubsub_subject() must return \
13436 None on non-PubSub arms — a leak that surfaced an \
13437 HTTP :endpoint or a key/value :slot through the \
13438 pub-sub-subject accessor would silently widen the \
13439 downstream NATS-shape accept-set onto protocol \
13440 shapes NATS servers can't route",
13441 );
13442 }
13443 }
13444 }
13445
13446 #[test]
13447 fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
13448 // Per-variant coherence pin: for every arm of [`WitTarget`],
13449 // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
13450 // drift surface where a future extension of the
13451 // [`WitTarget::pubsub_subject`] accessor's accept-set landed
13452 // without a paired extension of the [`gen_platform::IsVariant`]-
13453 // derived `is_pubsub()` predicate's accept-set, or vice versa
13454 // — a regression that split the "which arms count as pub-sub-
13455 // shaped for subject emission?" answer between two dispatch
13456 // surfaces the substrate ships. Sibling to the peer
13457 // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13458 // pin on the per-arm HTTP-shape axis — extended onto the
13459 // per-arm pub-sub predicate-vs-accessor coherence axis so the
13460 // gen-platform IsVariant predicate and the substrate-lifted
13461 // per-arm accessor carry one shared answer to "is this the
13462 // PubSub arm?".
13463 for variant in [
13464 WitTarget::Http {
13465 endpoint: "/charge",
13466 },
13467 WitTarget::PubSub {
13468 subject: "events.checkout.paid",
13469 },
13470 WitTarget::Store {
13471 slot: "checkout/$order",
13472 },
13473 WitTarget::Capability,
13474 ] {
13475 assert_eq!(
13476 variant.pubsub_subject().is_some(),
13477 variant.is_pubsub(),
13478 "WitTarget::{variant:?} pubsub_subject().is_some() must \
13479 equal is_pubsub() — a drift would split the pub-sub \
13480 emit branch's arm-set gate from the substrate-derived \
13481 shape-discrimination predicate on the same axis",
13482 );
13483 }
13484 }
13485
13486 #[test]
13487 fn wit_target_store_slot_pins_per_variant() {
13488 // Fail-before-pass-after pin: the substrate-canonical per-arm
13489 // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
13490 // is the single dispatch every future store-facing consumer
13491 // routes through, sibling to the peer [`WitContract::slot`]
13492 // pre-projection scalar accessor on the raw-field axis and to
13493 // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
13494 // [`WitTarget::pubsub_subject`] post-projection per-arm
13495 // accessors on the sibling per-payload-arm axes. The
13496 // [`WitTarget::Store`] arm round-trips its author-declared
13497 // slot verbatim as `Some("checkout/$order")`; the three
13498 // sibling arms each return `None` because they carry no
13499 // WASI-key/value slot by definition. Same fail-before-pass-
13500 // after per-variant discipline as the sibling
13501 // `wit_target_http_endpoint_pins_per_variant` +
13502 // `wit_target_pubsub_subject_pins_per_variant` pins on the
13503 // peer per-arm axes — extended onto the per-arm store-shape
13504 // post-projection axis so a future [`WitTarget`] variant
13505 // addition trips a compile-time exhaustiveness error on the
13506 // sibling [`WitTarget::store_slot`] match arms whose payload
13507 // the store-shape accept-set is meant to bound.
13508 assert_eq!(
13509 WitTarget::Store {
13510 slot: "checkout/$order",
13511 }
13512 .store_slot(),
13513 Some("checkout/$order"),
13514 );
13515 assert_eq!(
13516 WitTarget::Http {
13517 endpoint: "/charge",
13518 }
13519 .store_slot(),
13520 None,
13521 );
13522 assert_eq!(
13523 WitTarget::PubSub {
13524 subject: "events.checkout.paid",
13525 }
13526 .store_slot(),
13527 None,
13528 );
13529 assert_eq!(WitTarget::Capability.store_slot(), None);
13530 }
13531
13532 #[test]
13533 fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
13534 // Per-variant coherence pin: for every arm of [`WitTarget`],
13535 // `.store_slot()` equals `.payload()` on the
13536 // [`WitTarget::Store`] arm (both project the same
13537 // author-declared slot scalar), and returns `None` on every
13538 // sibling arm regardless of whether [`WitTarget::payload`]
13539 // itself returns `Some`. Sibling to the peer
13540 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13541 // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
13542 // pins on the per-arm HTTP and PubSub axes — closes the
13543 // per-arm-vs-pan-arm byte-shape coherence trio across all
13544 // three payload arms.
13545 for variant in [
13546 WitTarget::Http {
13547 endpoint: "/charge",
13548 },
13549 WitTarget::PubSub {
13550 subject: "events.checkout.paid",
13551 },
13552 WitTarget::Store {
13553 slot: "checkout/$order",
13554 },
13555 WitTarget::Capability,
13556 ] {
13557 let per_arm = variant.store_slot();
13558 let pan_arm = variant.payload();
13559 if variant.is_store() {
13560 assert_eq!(
13561 per_arm, pan_arm,
13562 "WitTarget::{variant:?} store_slot() must equal \
13563 payload() on the Store arm — a per-arm-vs-pan-arm \
13564 split would silently drift the store-shape emit \
13565 branch's slot-scalar source from the graph verb's \
13566 payload scalar source",
13567 );
13568 } else {
13569 assert_eq!(
13570 per_arm, None,
13571 "WitTarget::{variant:?} store_slot() must return \
13572 None on non-Store arms — a leak that surfaced an \
13573 HTTP :endpoint or a NATS :subject through the \
13574 key/value-slot accessor would silently widen the \
13575 downstream WASI-key/value slot accept-set onto \
13576 protocol shapes the kv backends can't route",
13577 );
13578 }
13579 }
13580 }
13581
13582 #[test]
13583 fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
13584 // Per-variant coherence pin: for every arm of [`WitTarget`],
13585 // `.store_slot().is_some()` iff `.is_store()`. Guards the
13586 // drift surface where a future extension of the
13587 // [`WitTarget::store_slot`] accessor's accept-set landed
13588 // without a paired extension of the [`gen_platform::IsVariant`]-
13589 // derived `is_store()` predicate's accept-set. Sibling to the
13590 // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13591 // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
13592 // pins — closes the per-arm predicate-vs-accessor coherence
13593 // trio across all three payload arms so the gen-platform
13594 // IsVariant predicate and the substrate-lifted per-arm
13595 // accessor carry one shared answer to "is this the Store arm?".
13596 for variant in [
13597 WitTarget::Http {
13598 endpoint: "/charge",
13599 },
13600 WitTarget::PubSub {
13601 subject: "events.checkout.paid",
13602 },
13603 WitTarget::Store {
13604 slot: "checkout/$order",
13605 },
13606 WitTarget::Capability,
13607 ] {
13608 assert_eq!(
13609 variant.store_slot().is_some(),
13610 variant.is_store(),
13611 "WitTarget::{variant:?} store_slot().is_some() must \
13612 equal is_store() — a drift would split the store-shape \
13613 emit branch's arm-set gate from the substrate-derived \
13614 shape-discrimination predicate on the same axis",
13615 );
13616 }
13617 }
13618
13619 #[test]
13620 fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
13621 // Fail-before-pass-after cross-axis pin on the trio
13622 // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
13623 // payload-carrying arm of [`WitTarget`], exactly one per-arm
13624 // accessor returns `Some(payload)` and the two peers return
13625 // `None`; and on the payload-less [`WitTarget::Capability`]
13626 // arm, all three return `None`. Guards the drift surface where
13627 // a future extension of one per-arm accessor's accept-set (e.g.
13628 // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
13629 // that widened `http_endpoint` to cover both peers without
13630 // narrowing the peer `pubsub_subject` / `store_slot` accept-
13631 // sets to keep the partition mutually exclusive) landed without
13632 // threading through the peer per-arm accessors — the resulting
13633 // silent overlap would land the same edge's payload on two
13634 // downstream per-shape emit branches at once, or leak a
13635 // pub-sub subject through the store-slot channel, at renderer
13636 // emit time far from the substrate primitive's arm-widening
13637 // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
13638 // 3-way pin on the payload-field-name axis — extended onto the
13639 // per-arm-accessor payload-projection axis so the substrate-
13640 // owned partition invariant is load-bearing at every per-arm
13641 // consumer's read site.
13642 let payload_variants = [
13643 (
13644 WitTarget::Http {
13645 endpoint: "/charge",
13646 },
13647 "http",
13648 ),
13649 (
13650 WitTarget::PubSub {
13651 subject: "events.checkout.paid",
13652 },
13653 "pubsub",
13654 ),
13655 (
13656 WitTarget::Store {
13657 slot: "checkout/$order",
13658 },
13659 "store",
13660 ),
13661 ];
13662 for (variant, own_arm_label) in payload_variants {
13663 let own_arm_hit = match own_arm_label {
13664 "http" => variant.is_http(),
13665 "pubsub" => variant.is_pubsub(),
13666 "store" => variant.is_store(),
13667 other => panic!("unknown own-arm label {other:?}"),
13668 };
13669 let per_arm_results = [
13670 ("http_endpoint", variant.http_endpoint()),
13671 ("pubsub_subject", variant.pubsub_subject()),
13672 ("store_slot", variant.store_slot()),
13673 ];
13674 let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
13675 assert_eq!(
13676 some_count, 1,
13677 "WitTarget::{variant:?} must land exactly one per-arm \
13678 post-projection accessor's Some result — the trio \
13679 (http_endpoint, pubsub_subject, store_slot) must \
13680 partition the payload arm-set; got {per_arm_results:?}",
13681 );
13682 assert!(
13683 own_arm_hit,
13684 "WitTarget::{variant:?} own-arm gen-platform predicate \
13685 must return true on its own arm — a partition failure \
13686 upstream of this pin",
13687 );
13688 assert!(
13689 variant.payload().is_some(),
13690 "WitTarget::{variant:?} pan-arm payload() must return \
13691 Some on every payload-carrying arm the trio partitions",
13692 );
13693 }
13694 // The payload-less Capability arm must return None on every
13695 // per-arm accessor — the partition's terminal-fallback shape.
13696 let cap = WitTarget::Capability;
13697 assert_eq!(cap.http_endpoint(), None);
13698 assert_eq!(cap.pubsub_subject(), None);
13699 assert_eq!(cap.store_slot(), None);
13700 assert_eq!(
13701 cap.payload(),
13702 None,
13703 "WitTarget::Capability pan-arm payload() must return None — \
13704 the trio's payload-less-arm coherence witness",
13705 );
13706 }
13707
13708 #[test]
13709 fn wit_target_field_names_are_pairwise_distinct() {
13710 // Distinctness pin: if any two of the three payload-field-name
13711 // scalars ever collapse (e.g. an accidental `endpoint` copy-
13712 // paste over the `subject` const), the [`WitContract::target`]
13713 // gate's diagnostic would point authors at the wrong field —
13714 // an "expected `:endpoint`" error on a pub-sub edge would
13715 // silently misroute the fix. Same cross-axis-distinctness
13716 // discipline as the peer M3 `:placement :estrategia` variant-
13717 // discriminator scalar-value pins (cc8f749) applied to the
13718 // payload-field-name axis.
13719 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
13720 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13721 assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13722 }
13723
13724 #[test]
13725 fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
13726 // Fail-before-pass-after pin: the graph-verb payload column's
13727 // per-arm `{field}={payload}` byte-string is derived through the
13728 // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
13729 // payload-carrying arms, not through a hand-rolled per-arm match
13730 // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
13731 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13732 // inline. A future variant addition — the M4-and-later per-edge
13733 // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
13734 // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
13735 // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
13736 // and both [`WitTarget::label`] (duplicate-`:contratos`
13737 // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
13738 // payload column) pick up the new arm from the same dispatch.
13739 // Prior to this lift the graph verb open-coded the 4-arm match
13740 // in caixa-feira, so a variant addition would have to be threaded
13741 // through both projections in lockstep or the graph verb would
13742 // silently drop the new arm to `(capability-only)`.
13743 for variant in [
13744 WitTarget::Http {
13745 endpoint: "/charge",
13746 },
13747 WitTarget::PubSub {
13748 subject: "events.checkout.paid",
13749 },
13750 WitTarget::Store {
13751 slot: "checkout/$order",
13752 },
13753 ] {
13754 let (field, payload) = variant
13755 .payload_pair()
13756 .expect("payload arm must expose (field, payload)");
13757 assert_eq!(
13758 variant.graph_label(),
13759 format!("{field}={payload}"),
13760 "WitTarget::{variant:?} graph_label must route the \
13761 `{{field}}={{payload}}` template through payload_pair — \
13762 a regression to a hand-rolled per-arm match at the graph \
13763 verb would silently disagree with a future variant \
13764 addition landed only at payload_pair"
13765 );
13766 }
13767 }
13768
13769 #[test]
13770 fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
13771 // Fail-before-pass-after pin on the payload-less arm: the graph
13772 // verb's `(capability-only)` byte-string routes through the
13773 // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
13774 // [`WitTarget::Capability`] arm, not through an inline
13775 // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
13776 // per-`:contratos` payload column. Peer of the sibling
13777 // [`wit_target_label_pins_per_variant_format`] Capability-arm
13778 // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
13779 // extended here onto the third payload-less-arm consumer axis
13780 // (graph verb, sibling to the duplicate-`:contratos` diagnostic
13781 // axis and the wrong-target diagnostic axis).
13782 assert_eq!(
13783 WitTarget::Capability.graph_label(),
13784 WitTarget::CAPABILITY_GRAPH_LABEL,
13785 );
13786 assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
13787 }
13788
13789 #[test]
13790 fn wit_target_capability_graph_label_distinct_from_capability_label() {
13791 // Cross-consumer-axis distinctness pin: the graph-verb
13792 // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
13793 // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
13794 // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
13795 // payload)`) surface the payload-less arm on two distinct
13796 // consumer axes; a collapse (an accidental rebrand that lands
13797 // one spelling on both consts, a copy-paste that unifies them
13798 // "for consistency") would silently merge the two byte-strings
13799 // and lose the vocabulary distinction the graph verb's
13800 // compact-column form and the diagnostic's descriptive-clause
13801 // form each carry on purpose. Peer of the sibling 4-way
13802 // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
13803 // pin on the `ContratoWrongTarget::expected` scalar-value axis —
13804 // extended here onto the cross-consumer-axis distinctness of the
13805 // two payload-less-arm consts.
13806 assert_ne!(
13807 WitTarget::CAPABILITY_GRAPH_LABEL,
13808 WitTarget::CAPABILITY_LABEL,
13809 "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
13810 and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
13811 diagnostic) must remain distinct — a collapse would silently \
13812 merge two consumer axes onto one spelling"
13813 );
13814 }
13815
13816 #[test]
13817 fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
13818 // 4-way distinctness pin extending the sibling
13819 // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
13820 // (which covers only the HTTP / PubSub / Store payload arms)
13821 // onto the fourth scalar the shared
13822 // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
13823 // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
13824 // (`"none"`), the payload-less Capability-arm rejection scalar.
13825 //
13826 // All four [`WitTarget::HTTP_FIELD_NAME`] /
13827 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13828 // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
13829 // dispatch surface [`WitContract::target`] writes onto the
13830 // `ContratoWrongTarget::expected` field — the same `&'static
13831 // str` axis authors read as "this WIT world's shape admits
13832 // (only|not) `:<field>`". Pairwise-distinctness is the invariant
13833 // downstream consumers rely on: an `expected: "endpoint"`
13834 // diagnostic on a Capability-shaped edge tells the author to
13835 // add a `:endpoint "…"` slot to a WIT world that admits none,
13836 // silently misrouting the fix. Until this pin landed the three
13837 // payload-arm consts were distinctness-guarded by the sibling
13838 // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
13839 // scalar (d4f54f2) sat unguarded — a rebrand collision (the
13840 // author-facing vocabulary shift from `"none"` to `"endpoint"`
13841 // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
13842 // into per-shape peers) would have silently landed one
13843 // Capability-arm rejection on a payload-arm's `expected:` byte-
13844 // string and desynchronized the diagnostic from the author's
13845 // typed shape.
13846 //
13847 // Same 4-way pairwise-distinctness pin discipline as the peer
13848 // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
13849 // (cc8f749) applies on the sibling M3 closed-set typed-enum
13850 // scalar-value dispatch axis; extends the pin trajectory the
13851 // sibling `wit_target_field_names_are_pairwise_distinct`
13852 // 3-way pin opened to cover the last unguarded corner on the
13853 // `ContratoWrongTarget::expected` scalar-value axis.
13854 //
13855 // Fail-before-pass-after locally verified by mutating
13856 // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
13857 // — this pin fires as expected; restoring passes.
13858 let all = [
13859 WitTarget::HTTP_FIELD_NAME,
13860 WitTarget::PUBSUB_FIELD_NAME,
13861 WitTarget::STORE_FIELD_NAME,
13862 WitTarget::CAPABILITY_EXPECTED,
13863 ];
13864 for (i, a) in all.iter().enumerate() {
13865 for (j, b) in all.iter().enumerate() {
13866 if i != j {
13867 assert_ne!(
13868 a, b,
13869 "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
13870 STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
13871 pairwise distinct — got duplicate {a:?} at indices \
13872 {i} and {j}; all four scalars thread through the \
13873 shared `AplicacaoError::ContratoWrongTarget::expected` \
13874 &'static str axis, so a collapse silently misdirects \
13875 the diagnostic on which typed shape the WIT world admits",
13876 );
13877 }
13878 }
13879 }
13880 }
13881
13882 #[test]
13883 fn wit_target_is_variant_predicates_partition_the_arm_set() {
13884 // Fail-before-pass-after pin on the
13885 // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
13886 // each of the four variants exactly one of the generated
13887 // `is_http` / `is_pubsub` / `is_store` / `is_capability`
13888 // predicates returns `true` and the other three return
13889 // `false`. Prior to this derive the only production
13890 // arm-discriminator on [`WitTarget`] — the sync-cycle
13891 // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
13892 // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
13893 // the variant that expressed no compile-time link back to
13894 // the closed-set typed dispatch a future fifth
13895 // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
13896 // split of [`WitTarget::PubSub`] into shape-specific peers,
13897 // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
13898 // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
13899 // to thread through in lockstep or the DFS exclusion would
13900 // silently disagree with the peer diagnostic templates on
13901 // which arms carry sync-versus-async semantics. Peer of the
13902 // sibling [`crate::CaixaKind`] (f5bba80),
13903 // [`PlacementStrategy`] (766ec63),
13904 // [`crate::supervisor::RestartStrategy`],
13905 // [`crate::supervisor::RestartPolicy`], and
13906 // [`crate::upgrade::UpgradeInstruction`] (915a934)
13907 // `IsVariant` derives on the sibling closed-set typed-enum
13908 // discriminator axes — extends the same one-typed-dispatch-
13909 // per-variant discipline onto the last unlifted closed-set
13910 // typed-enum discriminator on the caixa surface (the M3
13911 // mesh-slot per-`:contratos` target-arm axis), closing the
13912 // arm-discriminator convergence trajectory across every
13913 // closed-set typed enum in caixa-core.
13914 let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
13915 (
13916 WitTarget::Http { endpoint: "/x" },
13917 [true, false, false, false],
13918 ),
13919 (
13920 WitTarget::PubSub {
13921 subject: "events.x",
13922 },
13923 [false, true, false, false],
13924 ),
13925 (
13926 WitTarget::Store { slot: "kv/x" },
13927 [false, false, true, false],
13928 ),
13929 (WitTarget::Capability, [false, false, false, true]),
13930 ];
13931 for (variant, expected) in rows {
13932 let observed = [
13933 variant.is_http(),
13934 variant.is_pubsub(),
13935 variant.is_store(),
13936 variant.is_capability(),
13937 ];
13938 assert_eq!(
13939 observed, expected,
13940 "WitTarget::{variant:?} is_* predicates must partition \
13941 the arm set (http, pubsub, store, capability); got {observed:?}"
13942 );
13943 }
13944 }
13945
13946 #[test]
13947 fn wit_target_is_variant_predicates_are_const_fn() {
13948 // The [`gen_platform::IsVariant`] derive emits `const fn`
13949 // predicates on the peer [`crate::CaixaKind`] +
13950 // [`crate::upgrade::UpgradeInstruction`] +
13951 // [`crate::supervisor::RestartStrategy`] +
13952 // [`crate::supervisor::RestartPolicy`] +
13953 // [`PlacementStrategy`] closed-set typed enums — pin the
13954 // same posture on [`WitTarget`] so a future accidental
13955 // downgrade to non-`const` (an added runtime helper reachable
13956 // only from a non-`const` context, a manual hand-rolled
13957 // `impl` that shadows the derive-generated method) trips at
13958 // caixa-core build time rather than surfacing as a downstream
13959 // `const`-context regression far from the derive declaration.
13960 //
13961 // Unlike the peer unit-variant enums (`CaixaKind` /
13962 // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
13963 // whose `const` constructors need no arguments, the three
13964 // payload-carrying [`WitTarget`] arms are const-constructed
13965 // through `&'static str` payloads — the same `'static`
13966 // lifetime the closed-set typed enum's four-arm partition
13967 // pin above already threads through.
13968 const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
13969 const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
13970 const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
13971 const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
13972 const IS_HTTP: bool = HTTP.is_http();
13973 const IS_PUBSUB: bool = PUBSUB.is_pubsub();
13974 const IS_STORE: bool = STORE.is_store();
13975 const IS_CAPABILITY: bool = CAPABILITY.is_capability();
13976 assert!(IS_HTTP);
13977 assert!(IS_PUBSUB);
13978 assert!(IS_STORE);
13979 assert!(IS_CAPABILITY);
13980 }
13981
13982 #[test]
13983 fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
13984 // Consumer-side pin on the sole production converge site:
13985 // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
13986 // edges from the synchronous-subgraph DFS via the lifted
13987 // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
13988 // predicate (rebound from the prior raw
13989 // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
13990 // variant). Byte-equivalent today (`is_pubsub` is the
13991 // derive-generated `matches!(self, Self::PubSub { .. })` by
13992 // construction, the `#[is_variant(name = "pubsub")]` override
13993 // aliasing the auto-derived `is_pub_sub` back to the sibling
13994 // [`WitContract::is_pubsub`] name); pin the behavior so a
13995 // future accidental drift (a rebind onto a peer arm
13996 // predicate, a manual hand-rolled `impl` that shadows the
13997 // derive-generated method with different semantics, a peer
13998 // arm rename that shifts which variant carries sync-versus-
13999 // async semantics) trips at caixa-core test time rather than
14000 // at some downstream operator's runtime dispatch far from the
14001 // rebind commit.
14002 //
14003 // The fixture constructs a two-Servico Aplicacao with one
14004 // pub-sub edge that would close a sync-cycle if the DFS did
14005 // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
14006 // pub-sub exclusion means the DFS sees only the `b → a` HTTP
14007 // edge, which is not a cycle. A regression in the converge
14008 // (a rebind that reads the pub-sub arm as sync) would report
14009 // `AplicacaoError::ContratoCycle`.
14010 let s = AplicacaoSpec {
14011 membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
14012 contratos: vec![
14013 // Pub-sub edge: DFS must skip via is_pubsub().
14014 WitContract {
14015 de: "a".into(),
14016 para: "b".into(),
14017 wit: "nats:pub-sub".into(),
14018 endpoint: None,
14019 subject: Some("events.x".into()),
14020 slot: None,
14021 },
14022 // HTTP edge: DFS must include.
14023 WitContract {
14024 de: "b".into(),
14025 para: "a".into(),
14026 wit: "wasi:http/proxy".into(),
14027 endpoint: Some("/x".into()),
14028 subject: None,
14029 slot: None,
14030 },
14031 ],
14032 politicas: MeshPolicy::default(),
14033 placement: Placement {
14034 estrategia: PlacementStrategy::Replicated,
14035 clusters: vec!["rio".into()],
14036 affinity: None,
14037 shard_key: None,
14038 },
14039 entrada: None,
14040 };
14041 s.validate()
14042 .expect("pub-sub edge must be excluded from sync-cycle DFS");
14043 }
14044
14045 #[test]
14046 fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
14047 // Consumer-side pin: the same three peer consts thread through
14048 // both the [`WitTarget::label`] template (leading-`:` keyword
14049 // prefix in the duplicate-`:contratos` diagnostic) and the
14050 // [`WitContract::target`] gate's [`AplicacaoError::
14051 // ContratoMissingTarget`] `expected:` scalar (the field the
14052 // author needs to add). Pin both routes at once so a future
14053 // refactor can't accidentally split them onto separate string
14054 // literals — the "one place, everywhere reaches for it"
14055 // invariant the peer const set carries.
14056 let http_label = WitTarget::Http { endpoint: "/x" }.label();
14057 assert!(
14058 http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
14059 "label must lead with :{} keyword (got {http_label:?})",
14060 WitTarget::HTTP_FIELD_NAME,
14061 );
14062
14063 let mut s = three_member_spec();
14064 s.contratos.push(WitContract {
14065 de: "cart".into(),
14066 para: "catalog".into(),
14067 wit: "kafka:topic".into(),
14068 endpoint: None,
14069 subject: None,
14070 slot: None,
14071 });
14072 match s.validate().unwrap_err() {
14073 AplicacaoError::ContratoMissingTarget { expected, .. } => {
14074 assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
14075 }
14076 other => panic!("expected ContratoMissingTarget, got {other:?}"),
14077 }
14078 }
14079
14080 #[test]
14081 fn duplicate_pubsub_diagnostic_names_offending_subject() {
14082 // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
14083 // on the pub-sub target axis: the duplicate-edge diagnostic
14084 // must name the `:subject` payload verbatim (not just the
14085 // `(de, para, wit)` triple). Prior to lifting the label onto
14086 // [`WitTarget::label`] the diagnostic derived the label from
14087 // raw [`WitContract`] `Option<String>` probes — a future
14088 // `WitTarget` variant addition (M4 per-edge WIT registry)
14089 // would silently fall through to the `Capability` "no
14090 // payload" default without a compiler warning. Pinning the
14091 // pub-sub arm's format closes the second of three
14092 // payload-carrying `WitTarget` arms this diagnostic threads
14093 // through.
14094 let mut s = three_member_spec();
14095 let pubsub = WitContract {
14096 de: "payment".into(),
14097 para: "cart".into(),
14098 wit: "nats:pub-sub".into(),
14099 endpoint: None,
14100 subject: Some("events.checkout.paid".into()),
14101 slot: None,
14102 };
14103 s.contratos.push(pubsub.clone());
14104 s.contratos.push(pubsub);
14105 let err = s.validate().unwrap_err();
14106 let msg = format!("{err}");
14107 assert!(
14108 msg.contains(":subject \"events.checkout.paid\""),
14109 "duplicate-pubsub diagnostic must name the offending \
14110 :subject payload (got: {msg:?})"
14111 );
14112 }
14113
14114 #[test]
14115 fn duplicate_store_diagnostic_names_offending_slot() {
14116 // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
14117 // key-value target axis: the diagnostic must name the `:slot`
14118 // payload verbatim. Third of three payload-carrying
14119 // `WitTarget` arms this diagnostic threads through, closing
14120 // the per-arm label pin trilogy (`Http` — 6841,
14121 // `PubSub` + `Store` — this test + peer above).
14122 let mut s = three_member_spec();
14123 let store = WitContract {
14124 de: "cart".into(),
14125 para: "payment".into(),
14126 wit: "wasi:keyvalue/store".into(),
14127 endpoint: None,
14128 subject: None,
14129 slot: Some("checkout/$orderId".into()),
14130 };
14131 s.contratos
14132 .retain(|c| !(c.de == "cart" && c.para == "payment"));
14133 s.contratos.push(store.clone());
14134 s.contratos.push(store);
14135 let err = s.validate().unwrap_err();
14136 let msg = format!("{err}");
14137 assert!(
14138 msg.contains(":slot \"checkout/$orderId\""),
14139 "duplicate-store diagnostic must name the offending :slot \
14140 payload (got: {msg:?})"
14141 );
14142 }
14143
14144 #[test]
14145 fn rejects_entrada_path_without_leading_slash() {
14146 let mut s = three_member_spec();
14147 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
14148 let err = s.validate().unwrap_err();
14149 assert!(
14150 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
14151 "got {err:?}"
14152 );
14153 }
14154
14155 #[test]
14156 fn rejects_empty_entrada_path() {
14157 let mut s = three_member_spec();
14158 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
14159 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14160 }
14161
14162 #[test]
14163 fn rejects_duplicate_entrada_paths() {
14164 let mut s = three_member_spec();
14165 s.entrada.as_mut().unwrap().paths = vec![
14166 "/api/cart".into(),
14167 "/api/products".into(),
14168 "/api/cart".into(),
14169 ];
14170 let err = s.validate().unwrap_err();
14171 assert!(
14172 matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
14173 "got {err:?}"
14174 );
14175 }
14176
14177 #[test]
14178 fn rejects_zero_entrada_port() {
14179 let mut s = three_member_spec();
14180 s.entrada.as_mut().unwrap().port = 0;
14181 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
14182 }
14183
14184 // ── :entrada :paths value-shape gate ─────────────────────────────
14185 //
14186 // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
14187 // sibling `:paths` axis. Every authoring footgun the K8s Gateway
14188 // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
14189 // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
14190 // time now becomes a caixa-build-time `EntradaPathInvalid` with
14191 // the offending `:paths` entry named verbatim.
14192
14193 #[test]
14194 fn rejects_entrada_path_with_query() {
14195 // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
14196 // silently passed validate and the Gateway API webhook
14197 // rejected it at apply time with no source citation.
14198 let mut s = three_member_spec();
14199 s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
14200 let err = s.validate().unwrap_err();
14201 assert!(
14202 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14203 if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
14204 "got {err:?}"
14205 );
14206 }
14207
14208 #[test]
14209 fn rejects_entrada_path_with_fragment() {
14210 let mut s = three_member_spec();
14211 s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
14212 let err = s.validate().unwrap_err();
14213 assert!(
14214 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14215 if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
14216 "got {err:?}"
14217 );
14218 }
14219
14220 #[test]
14221 fn rejects_entrada_path_with_space() {
14222 let mut s = three_member_spec();
14223 s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
14224 let err = s.validate().unwrap_err();
14225 assert!(
14226 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14227 if path == "/api/my cart" && reason.contains("whitespace")),
14228 "got {err:?}"
14229 );
14230 }
14231
14232 #[test]
14233 fn rejects_entrada_path_with_tab() {
14234 let mut s = three_member_spec();
14235 s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
14236 let err = s.validate().unwrap_err();
14237 assert!(
14238 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14239 if path == "/api/\tcart" && reason.contains("whitespace")),
14240 "got {err:?}"
14241 );
14242 }
14243
14244 #[test]
14245 fn rejects_entrada_path_with_control_char() {
14246 // 0x01 (SOH) — a non-whitespace control char surfaces the
14247 // distinct "control character" reason arm, separate from
14248 // the whitespace arm. Pinned so a future refactor that
14249 // collapses the two arms can't accidentally drop the more
14250 // self-locating diagnostic.
14251 let mut s = three_member_spec();
14252 s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
14253 let err = s.validate().unwrap_err();
14254 assert!(
14255 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14256 if path == "/api/\x01cart" && reason.contains("control character")),
14257 "got {err:?}"
14258 );
14259 }
14260
14261 #[test]
14262 fn rejects_entrada_path_with_non_ascii() {
14263 // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
14264 // unreserved-set rule rejects. The Gateway API webhook
14265 // rejects literal non-ASCII bytes; percent-encoding is the
14266 // only way to author non-ASCII in a path.
14267 let mut s = three_member_spec();
14268 s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
14269 let err = s.validate().unwrap_err();
14270 assert!(
14271 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14272 if path == "/api/café" && reason.contains("non-ASCII")),
14273 "got {err:?}"
14274 );
14275 }
14276
14277 #[test]
14278 fn rejects_entrada_path_with_consecutive_slashes() {
14279 let mut s = three_member_spec();
14280 s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
14281 let err = s.validate().unwrap_err();
14282 assert!(
14283 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14284 if path == "/api//cart" && reason.contains("consecutive `/`")),
14285 "got {err:?}"
14286 );
14287 }
14288
14289 #[test]
14290 fn rejects_entrada_path_with_dot_segment() {
14291 let mut s = three_member_spec();
14292 s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
14293 let err = s.validate().unwrap_err();
14294 assert!(
14295 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14296 if path == "/api/./cart" && reason.contains("`.` segment")),
14297 "got {err:?}"
14298 );
14299 }
14300
14301 #[test]
14302 fn rejects_entrada_path_with_trailing_dot_segment() {
14303 // The bare `/.` and the trailing `/foo/.` are both rejected
14304 // by the Gateway API webhook; pinned separately so a future
14305 // narrowing that catches only the inner form surfaces here.
14306 let mut s = three_member_spec();
14307 s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
14308 let err = s.validate().unwrap_err();
14309 assert!(
14310 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14311 if path == "/api/." && reason.contains("`.` segment")),
14312 "got {err:?}"
14313 );
14314 }
14315
14316 #[test]
14317 fn rejects_entrada_path_with_parent_segment() {
14318 let mut s = three_member_spec();
14319 s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
14320 let err = s.validate().unwrap_err();
14321 assert!(
14322 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14323 if path == "/api/../etc" && reason.contains("`..` parent-segment")),
14324 "got {err:?}"
14325 );
14326 }
14327
14328 #[test]
14329 fn rejects_entrada_path_with_trailing_parent_segment() {
14330 // Trailing `/..` — symmetric arm of the parent-segment rule,
14331 // pinned separately so a future relaxation that only checks
14332 // the inner form (`/../`) surfaces here.
14333 let mut s = three_member_spec();
14334 s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
14335 let err = s.validate().unwrap_err();
14336 assert!(
14337 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14338 if path == "/api/.." && reason.contains("`..` parent-segment")),
14339 "got {err:?}"
14340 );
14341 }
14342
14343 #[test]
14344 fn rejects_entrada_path_too_long() {
14345 // 1025-byte path — one over the Gateway API HTTPPathMatch.value
14346 // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
14347 // ASCII-alphanumeric body so only the length rule fires.
14348 let mut s = three_member_spec();
14349 let big = format!("/api/{}", "a".repeat(1020));
14350 assert_eq!(big.len(), 1025);
14351 s.entrada.as_mut().unwrap().paths = vec![big.clone()];
14352 let err = s.validate().unwrap_err();
14353 assert!(
14354 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14355 if path == &big && reason.contains("max length of 1024")),
14356 "got {err:?}"
14357 );
14358 }
14359
14360 #[test]
14361 fn entrada_path_max_length_validates() {
14362 // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
14363 // maxLength cap. Boundary pin: drift in the cap surfaces here
14364 // and at `rejects_entrada_path_too_long` simultaneously.
14365 let mut s = three_member_spec();
14366 let big = format!("/api/{}", "a".repeat(1019));
14367 assert_eq!(big.len(), 1024);
14368 s.entrada.as_mut().unwrap().paths = vec![big];
14369 s.validate().unwrap();
14370 }
14371
14372 #[test]
14373 fn entrada_accepts_canonical_paths() {
14374 // Positive-control sweep — every form the Gateway API
14375 // apiserver accepts must round-trip through validate. Covers
14376 // the root catch-all, plain paths, dot-prefixed segments
14377 // (hidden-file-style, distinct from `.` and `..` segments
14378 // which are rejected), digit-bearing segments, the canonical
14379 // route-template `:param` form (`:` is RFC 3986 reserved-set
14380 // valid in paths), trailing-slash form, percent-encoded
14381 // segments, and an interior `..` *substring* (`/foo..bar` is
14382 // not the `..` segment and is allowed).
14383 for path in [
14384 "/",
14385 "/api/cart",
14386 "/healthz",
14387 "/api/.config",
14388 "/v1/products",
14389 "/products/:id",
14390 "/api/cart/",
14391 "/api/caf%C3%A9",
14392 "/foo..bar",
14393 "/...",
14394 ] {
14395 let mut s = three_member_spec();
14396 s.entrada.as_mut().unwrap().paths = vec![path.into()];
14397 s.validate()
14398 .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
14399 }
14400 }
14401
14402 #[test]
14403 fn entrada_path_empty_takes_precedence_over_invalid() {
14404 // Ordering pin: `EntradaPathEmpty` is the more self-locating
14405 // diagnostic on `""` and must lead — `validate_entrada_path`
14406 // is only reached after the empty-check fires at the call
14407 // site. (The predicate itself defends against direct
14408 // invocation by returning the same error on `""`.)
14409 let mut s = three_member_spec();
14410 s.entrada.as_mut().unwrap().paths = vec!["".into()];
14411 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14412 }
14413
14414 #[test]
14415 fn entrada_path_not_absolute_takes_precedence_over_invalid() {
14416 // Ordering pin: a path without a leading `/` surfaces the
14417 // narrower `EntradaPathNotAbsolute` diagnostic first; the
14418 // value-shape gate is only consulted on paths that already
14419 // satisfy the absolute-prefix invariant.
14420 let mut s = three_member_spec();
14421 // `bad path` would fire the whitespace rule under the
14422 // value-shape gate, but missing-leading-`/` is the more
14423 // self-locating diagnostic.
14424 s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
14425 let err = s.validate().unwrap_err();
14426 assert!(
14427 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
14428 "got {err:?}"
14429 );
14430 }
14431
14432 #[test]
14433 fn entrada_path_invalid_fires_before_duplicate_check() {
14434 // Ordering pin: a malformed path on the *first* entry of a
14435 // would-be duplicate pair fires the value-shape gate before
14436 // the duplicate gate, mirroring the
14437 // `placement_cluster_invalid_fires_before_duplicate_check`
14438 // (6cbb900) pattern on the peer axis.
14439 let mut s = three_member_spec();
14440 s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
14441 let err = s.validate().unwrap_err();
14442 assert!(
14443 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
14444 "got {err:?}"
14445 );
14446 }
14447
14448 #[test]
14449 fn entrada_path_diagnostic_carries_offending_path() {
14450 // Diagnostic-shape pin — the offending path + a non-empty
14451 // reason flow through verbatim so the author can grep their
14452 // caixa.lisp for `:paths` and fix it in one edit. Same shape
14453 // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
14454 let mut s = three_member_spec();
14455 s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
14456 let err = s.validate().unwrap_err();
14457 match err {
14458 AplicacaoError::EntradaPathInvalid { path, reason } => {
14459 assert_eq!(path, "/api?q=1");
14460 assert!(!reason.is_empty(), "reason field must be non-empty");
14461 }
14462 other => panic!("expected EntradaPathInvalid, got {other:?}"),
14463 }
14464 }
14465
14466 #[test]
14467 fn rejects_entrada_path_with_curly_brace_template_form() {
14468 // Per-axis pin on the shared `is_gateway_api_http_path`
14469 // reserved-byte arm: the canonical "I wrote an OpenAPI
14470 // path-template `{id}` instead of the Gateway API `:id` form"
14471 // footgun the K8s apiserver would otherwise catch at admission
14472 // time on every `HTTPRoute.spec.rules[].matches[].path.value`
14473 // landing site, far from the caixa.lisp. Surfaces as
14474 // `EntradaPathInvalid` carrying the offending path verbatim
14475 // plus the canonical `%7B`/`%7D` percent-encoding remediation
14476 // — the substrate-side `gateway_api_http_path_rejects_every_
14477 // reserved_printable_ascii_byte` predicate-level sweep pins the
14478 // full eleven-byte set; this per-axis pin confirms the
14479 // diagnostic flows through to the `EntradaPathInvalid` variant.
14480 let mut s = three_member_spec();
14481 s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
14482 let err = s.validate().unwrap_err();
14483 assert!(
14484 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14485 if path == "/api/cart/{id}"
14486 && reason.contains("reserved character")
14487 && reason.contains("'{'")
14488 && reason.contains("%7B")),
14489 "got {err:?}"
14490 );
14491 }
14492
14493 #[test]
14494 fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
14495 // Per-axis peer of `rejects_entrada_path_with_curly_brace_
14496 // template_form` on the sibling `:contratos :endpoint` axis.
14497 // Same shared `is_gateway_api_http_path` reserved-byte arm
14498 // fires through `ContratoEndpointInvalid`, with the offending
14499 // endpoint + `:de` + `:para` + reason flowing through verbatim.
14500 // Pins that the lifted predicate's tightening lands on both
14501 // caller axes simultaneously — one source of truth for the
14502 // Gateway API HTTPPathMatch.value accepted set.
14503 let err = contrato_endpoint_err("/api/cart/{id}");
14504 assert!(
14505 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14506 if endpoint == "/api/cart/{id}"
14507 && reason.contains("reserved character")
14508 && reason.contains("'{'")
14509 && reason.contains("%7B")),
14510 "got {err:?}"
14511 );
14512 }
14513
14514 // ── :entrada :host value-shape gate ──────────────────────────────
14515 //
14516 // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
14517 // the sibling `:host` axis. Every authoring footgun the K8s
14518 // Gateway API v1 apiserver would catch at admission time becomes
14519 // a caixa-build-time `EntradaHostInvalid` with the offending
14520 // `:host` named verbatim. Same diagnostic shape as
14521 // `MembroVersaoInvalid` (9888b13).
14522
14523 #[test]
14524 fn rejects_entrada_host_with_scheme() {
14525 // Fail-before-pass-after pin — pre-gate codebases silently
14526 // accepted `https://…` and the apiserver rejected it at apply
14527 // time with no source citation.
14528 let mut s = three_member_spec();
14529 s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
14530 let err = s.validate().unwrap_err();
14531 assert!(
14532 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14533 if host == "https://checkout.quero.cloud"),
14534 "got {err:?}"
14535 );
14536 }
14537
14538 #[test]
14539 fn rejects_entrada_host_with_port() {
14540 // The `:8080` port suffix is the canonical "I forgot the port
14541 // belongs in `:entrada :port`" footgun. The top-level `:` arm
14542 // (introduced after the per-label loop-only impl silently
14543 // surfaced a deep "label \"cloud:8080\" contains invalid
14544 // character ':'" leak) names the canonical fix verbatim — the
14545 // `:entrada :port` slot.
14546 let mut s = three_member_spec();
14547 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14548 let err = s.validate().unwrap_err();
14549 assert!(
14550 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14551 if host == "checkout.quero.cloud:8080"
14552 && reason.contains(":entrada :port")),
14553 "got {err:?}"
14554 );
14555 }
14556
14557 #[test]
14558 fn rejects_entrada_host_with_trailing_colon() {
14559 // Trailing `:` (e.g. an in-progress `:host "example.com:"`
14560 // edit) — the per-label loop would land it as a deep
14561 // "label \"com:\" must start and end with an alphanumeric"
14562 // / "contains invalid character ':'" leak. The top-level
14563 // `:` arm pre-empts with the canonical `:port` slot
14564 // diagnostic.
14565 let mut s = three_member_spec();
14566 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
14567 let err = s.validate().unwrap_err();
14568 assert!(
14569 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14570 if host == "checkout.quero.cloud:"
14571 && reason.contains(":entrada :port")),
14572 "got {err:?}"
14573 );
14574 }
14575
14576 #[test]
14577 fn rejects_entrada_host_unbracketed_ipv6_literal() {
14578 // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
14579 // literals across the board (peer with `rejects_entrada_host_
14580 // ipv4_literal` above for the four-label-all-digit IPv4 arm).
14581 // Before this top-level `:` arm landed the per-label loop
14582 // surfaced a single-label byte-class diagnostic that named the
14583 // `:` byte but not the IP-literal prohibition. The top-level
14584 // `:` arm names both the `:port` slot and the IP-literal
14585 // prohibition verbatim, so an author whose `:host "2001:..."`
14586 // value lands here gets a self-locating fix either way.
14587 let mut s = three_member_spec();
14588 s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
14589 let err = s.validate().unwrap_err();
14590 assert!(
14591 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14592 if host == "2001:db8::1"
14593 && reason.contains("IPv6")),
14594 "got {err:?}"
14595 );
14596 }
14597
14598 #[test]
14599 fn rejects_entrada_host_wildcard_with_port() {
14600 // Wildcard host with port suffix — the `*.` strip and the
14601 // per-label loop on `["foo", "quero", "cloud:8080"]` would
14602 // surface the deep byte-class leak. The top-level `:` arm sits
14603 // upstream of the `*.` strip, so it names the canonical `:port`
14604 // fix verbatim regardless of whether the host is wildcard-led.
14605 let mut s = three_member_spec();
14606 s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
14607 let err = s.validate().unwrap_err();
14608 assert!(
14609 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14610 if host == "*.quero.cloud:8080"
14611 && reason.contains(":entrada :port")),
14612 "got {err:?}"
14613 );
14614 }
14615
14616 #[test]
14617 fn rejects_entrada_host_with_path() {
14618 let mut s = three_member_spec();
14619 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
14620 let err = s.validate().unwrap_err();
14621 assert!(
14622 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14623 if host == "checkout.quero.cloud/api"),
14624 "got {err:?}"
14625 );
14626 }
14627
14628 #[test]
14629 fn rejects_entrada_host_with_uppercase() {
14630 // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
14631 // rejected, not silently lower-cased.
14632 let mut s = three_member_spec();
14633 s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
14634 let err = s.validate().unwrap_err();
14635 assert!(
14636 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14637 if reason.contains("uppercase")),
14638 "got {err:?}"
14639 );
14640 }
14641
14642 #[test]
14643 fn rejects_entrada_host_with_underscore() {
14644 // RFC 1123 allows `[a-z0-9-]` only; underscore is the
14645 // canonical "I'm thinking of HTTP cookies / SRV records" leak.
14646 let mut s = three_member_spec();
14647 s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
14648 let err = s.validate().unwrap_err();
14649 assert!(
14650 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14651 if reason.contains('_')),
14652 "got {err:?}"
14653 );
14654 }
14655
14656 #[test]
14657 fn rejects_entrada_host_ipv4_literal() {
14658 // Gateway API v1 explicitly forbids IP literals as Hostnames.
14659 let mut s = three_member_spec();
14660 s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
14661 let err = s.validate().unwrap_err();
14662 assert!(
14663 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14664 if reason.contains("IPv4")),
14665 "got {err:?}"
14666 );
14667 }
14668
14669 #[test]
14670 fn rejects_entrada_host_with_trailing_dot() {
14671 // The Gateway API regex anchors at end-of-string with no
14672 // trailing `.` allowance — the FQDN root-dot form is rejected.
14673 let mut s = three_member_spec();
14674 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
14675 let err = s.validate().unwrap_err();
14676 assert!(
14677 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14678 if host == "checkout.quero.cloud."),
14679 "got {err:?}"
14680 );
14681 }
14682
14683 #[test]
14684 fn rejects_entrada_host_with_leading_dot() {
14685 let mut s = three_member_spec();
14686 s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
14687 let err = s.validate().unwrap_err();
14688 assert!(
14689 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14690 if reason.contains("empty label")),
14691 "got {err:?}"
14692 );
14693 }
14694
14695 #[test]
14696 fn rejects_entrada_host_with_consecutive_dots() {
14697 let mut s = three_member_spec();
14698 s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
14699 let err = s.validate().unwrap_err();
14700 assert!(
14701 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14702 if reason.contains("empty label")),
14703 "got {err:?}"
14704 );
14705 }
14706
14707 #[test]
14708 fn rejects_entrada_host_with_leading_hyphen_label() {
14709 let mut s = three_member_spec();
14710 s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
14711 let err = s.validate().unwrap_err();
14712 assert!(
14713 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14714 if reason.contains("alphanumeric")),
14715 "got {err:?}"
14716 );
14717 }
14718
14719 #[test]
14720 fn rejects_entrada_host_with_trailing_hyphen_label() {
14721 let mut s = three_member_spec();
14722 s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
14723 let err = s.validate().unwrap_err();
14724 assert!(
14725 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14726 if reason.contains("alphanumeric")),
14727 "got {err:?}"
14728 );
14729 }
14730
14731 #[test]
14732 fn rejects_entrada_host_with_inner_wildcard() {
14733 // Gateway API allows `*` only as the first label (`*.foo`);
14734 // any inner or trailing `*` is rejected.
14735 let mut s = three_member_spec();
14736 s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
14737 let err = s.validate().unwrap_err();
14738 assert!(
14739 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14740 if reason.contains("wildcard")),
14741 "got {err:?}"
14742 );
14743 }
14744
14745 #[test]
14746 fn rejects_entrada_host_bare_wildcard() {
14747 // `*.` with no domain is meaningless; Gateway API rejects it.
14748 let mut s = three_member_spec();
14749 s.entrada.as_mut().unwrap().host = "*.".into();
14750 let err = s.validate().unwrap_err();
14751 assert!(
14752 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14753 if reason.contains("wildcard")),
14754 "got {err:?}"
14755 );
14756 }
14757
14758 #[test]
14759 fn rejects_entrada_host_with_whitespace() {
14760 let mut s = three_member_spec();
14761 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14762 let err = s.validate().unwrap_err();
14763 assert!(
14764 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14765 if reason.contains("whitespace")),
14766 "got {err:?}"
14767 );
14768 }
14769
14770 #[test]
14771 fn rejects_entrada_host_space_names_offending_byte() {
14772 // Embedded space in the `:entrada :host` axis surfaces the
14773 // byte-naming diagnostic through the lifted
14774 // `find_ascii_whitespace_byte` predicate. Peer with the
14775 // sibling `parse_rejects_leading_whitespace` pins on
14776 // `supervisor::duration_codec` (a7ae622) — same "the
14777 // diagnostic carries the offending byte's `0x{b:02x}` shape"
14778 // discipline extended from the shared duration codec to the
14779 // Gateway API v1 Hostname axis.
14780 let mut s = three_member_spec();
14781 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14782 let err = s.validate().unwrap_err();
14783 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14784 panic!("expected EntradaHostInvalid, got {err:?}");
14785 };
14786 assert!(
14787 reason.contains("ASCII whitespace byte"),
14788 "expected byte-naming diagnostic, got {reason:?}"
14789 );
14790 assert!(
14791 reason.contains("0x20"),
14792 "expected offending space byte 0x20, got {reason:?}"
14793 );
14794 }
14795
14796 #[test]
14797 fn rejects_entrada_host_tab_names_offending_byte() {
14798 // Embedded tab byte in the `:entrada :host` axis — the
14799 // canonical paste-from-YAML-block-scalar / paste-from-
14800 // indented-doc footgun. Pins that the lifted predicate covers
14801 // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
14802 // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
14803 // not just the leading-space case the pre-lift `.bytes().any`
14804 // arm's opaque "must not contain whitespace" reason already
14805 // covered. Peer with `parse_rejects_tab_byte` on
14806 // `supervisor::duration_codec` (a7ae622).
14807 let mut s = three_member_spec();
14808 s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
14809 let err = s.validate().unwrap_err();
14810 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14811 panic!("expected EntradaHostInvalid, got {err:?}");
14812 };
14813 assert!(
14814 reason.contains("ASCII whitespace byte"),
14815 "expected byte-naming diagnostic, got {reason:?}"
14816 );
14817 assert!(
14818 reason.contains("0x09"),
14819 "expected offending tab byte 0x09, got {reason:?}"
14820 );
14821 }
14822
14823 #[test]
14824 fn rejects_entrada_host_lf_names_offending_byte() {
14825 // Embedded LF byte in the `:entrada :host` axis — the
14826 // canonical paste-from-shell-heredoc / paste-from-multiline-
14827 // doc footgun the caixa-mesh YAML emitter would silently
14828 // reinterpret at the Gateway API v1 HTTPRoute admission
14829 // layer (an embedded LF byte in a YAML plain scalar either
14830 // truncates the value at the emitter or crashes the parser
14831 // on the k8s-apiserver side). Pins the third representative
14832 // of the full ASCII-whitespace set through the shared
14833 // predicate.
14834 let mut s = three_member_spec();
14835 s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
14836 let err = s.validate().unwrap_err();
14837 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14838 panic!("expected EntradaHostInvalid, got {err:?}");
14839 };
14840 assert!(
14841 reason.contains("ASCII whitespace byte"),
14842 "expected byte-naming diagnostic, got {reason:?}"
14843 );
14844 assert!(
14845 reason.contains("0x0a"),
14846 "expected offending LF byte 0x0a, got {reason:?}"
14847 );
14848 }
14849
14850 #[test]
14851 fn rejects_entrada_host_nbsp_names_offending_codepoint() {
14852 // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
14853 // axis — the canonical paste-from-typography /
14854 // paste-from-word-processor footgun. Before the non-ASCII
14855 // Unicode `White_Space` scan lifted through the shared
14856 // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
14857 // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
14858 // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
14859 // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
14860 // with the far-from-source `label "…" must start and end
14861 // with an alphanumeric` diagnostic — burying the
14862 // paste-from-typography origin under a label-shape leak.
14863 // Peer with the sibling non-ASCII-whitespace pins at
14864 // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
14865 // — 1b75b38), `limits::parse_duration`,
14866 // `limits::parse_millicores`, and the shared duration codec
14867 // — same "the diagnostic carries the offending Unicode
14868 // codepoint's `U+XXXX` shape" discipline extended from every
14869 // typed-magnitude codec to the Gateway API v1 Hostname axis.
14870 let mut s = three_member_spec();
14871 s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
14872 let err = s.validate().unwrap_err();
14873 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14874 panic!("expected EntradaHostInvalid, got {err:?}");
14875 };
14876 assert!(
14877 reason.contains("non-ASCII Unicode whitespace character"),
14878 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14879 );
14880 assert!(
14881 reason.contains("U+00A0"),
14882 "expected offending NBSP codepoint U+00A0, got {reason:?}"
14883 );
14884 }
14885
14886 #[test]
14887 fn rejects_entrada_host_line_separator_names_offending_codepoint() {
14888 // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
14889 // `:entrada :host` axis — the canonical paste-from-web-doc /
14890 // paste-from-published-HTML footgun. `char::is_whitespace`
14891 // returns true for `U+2028` per the Unicode `White_Space`
14892 // property, so `str::trim` at any downstream site would
14893 // silently strip it — same drift class as NBSP but on a
14894 // different codepoint region. Pins the second representative
14895 // (non-Latin-1 `char::is_whitespace` member) through the
14896 // shared predicate. Peer with
14897 // `parse_byte_size_rejects_internal_line_separator` on
14898 // `limits::parse_byte_size` (1b75b38).
14899 let mut s = three_member_spec();
14900 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
14901 let err = s.validate().unwrap_err();
14902 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14903 panic!("expected EntradaHostInvalid, got {err:?}");
14904 };
14905 assert!(
14906 reason.contains("non-ASCII Unicode whitespace character"),
14907 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14908 );
14909 assert!(
14910 reason.contains("U+2028"),
14911 "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
14912 );
14913 }
14914
14915 #[test]
14916 fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
14917 // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
14918 // labels in the `:entrada :host` axis — the canonical
14919 // paste-from-CJK-typography footgun (CJK IMEs default to
14920 // full-width whitespace when the space bar is pressed in
14921 // Japanese / Chinese input modes). Pins the third
14922 // representative of the non-ASCII Unicode `White_Space` set
14923 // through the shared predicate: the CJK block, distinct from
14924 // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
14925 // SEPARATOR `U+2028` — covering the same axis breadth the
14926 // sibling `parse_byte_size_rejects_trailing_ideographic_space`
14927 // (1b75b38) pins on `limits::parse_byte_size`.
14928 let mut s = three_member_spec();
14929 s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
14930 let err = s.validate().unwrap_err();
14931 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14932 panic!("expected EntradaHostInvalid, got {err:?}");
14933 };
14934 assert!(
14935 reason.contains("non-ASCII Unicode whitespace character"),
14936 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14937 );
14938 assert!(
14939 reason.contains("U+3000"),
14940 "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
14941 );
14942 }
14943
14944 #[test]
14945 fn rejects_entrada_host_too_long() {
14946 // Total length cap = 253; build a 254-byte host out of two
14947 // 63-byte labels + one 62-byte label + dots.
14948 let mut s = three_member_spec();
14949 let big = format!(
14950 "{}.{}.{}.{}",
14951 "a".repeat(63),
14952 "b".repeat(63),
14953 "c".repeat(63),
14954 "d".repeat(254 - 63 * 3 - 3)
14955 );
14956 assert_eq!(big.len(), 254);
14957 s.entrada.as_mut().unwrap().host = big;
14958 let err = s.validate().unwrap_err();
14959 assert!(
14960 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14961 if reason.contains("max length of 253")),
14962 "got {err:?}"
14963 );
14964 }
14965
14966 #[test]
14967 fn rejects_entrada_host_label_too_long() {
14968 let mut s = three_member_spec();
14969 // 64-byte label — one over the per-label cap.
14970 s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
14971 let err = s.validate().unwrap_err();
14972 assert!(
14973 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14974 if reason.contains("label max length of 63")),
14975 "got {err:?}"
14976 );
14977 }
14978
14979 #[test]
14980 fn entrada_host_diagnostic_carries_offending_host() {
14981 // Diagnostic-shape pin — the offending host + a non-empty
14982 // reason flow through verbatim so the author can grep their
14983 // caixa.lisp for `:host "<host>"` and fix it in one edit.
14984 let mut s = three_member_spec();
14985 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14986 let err = s.validate().unwrap_err();
14987 match err {
14988 AplicacaoError::EntradaHostInvalid { host, reason } => {
14989 assert_eq!(host, "checkout.quero.cloud:8080");
14990 assert!(!reason.is_empty(), "reason field must be non-empty");
14991 }
14992 other => panic!("expected EntradaHostInvalid, got {other:?}"),
14993 }
14994 }
14995
14996 #[test]
14997 fn entrada_host_empty_takes_precedence_over_invalid() {
14998 // Ordering pin: `EmptyEntradaHost` is the more self-locating
14999 // diagnostic on `""` and must lead — `validate_entrada_host`
15000 // is only reached after the empty-check fires at the call
15001 // site. (The predicate itself defends against direct
15002 // invocation by returning the same error on `""`.)
15003 let mut s = three_member_spec();
15004 s.entrada.as_mut().unwrap().host = String::new();
15005 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
15006 }
15007
15008 #[test]
15009 fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
15010 // Ordering pin: a missing :para member is the more
15011 // self-locating diagnostic and fires before the host gate.
15012 let mut s = three_member_spec();
15013 let e = s.entrada.as_mut().unwrap();
15014 e.para = "ghost".into();
15015 e.host = "BAD HOST".into();
15016 let err = s.validate().unwrap_err();
15017 assert!(
15018 matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
15019 "got {err:?}"
15020 );
15021 }
15022
15023 #[test]
15024 fn entrada_host_invalid_fires_before_port_zero() {
15025 // Ordering pin: the host gate fires before the port gate so
15026 // a malformed host is named even when the port is also wrong.
15027 let mut s = three_member_spec();
15028 let e = s.entrada.as_mut().unwrap();
15029 e.host = "Checkout.quero.cloud".into();
15030 e.port = 0;
15031 let err = s.validate().unwrap_err();
15032 assert!(
15033 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15034 if host == "Checkout.quero.cloud"),
15035 "got {err:?}"
15036 );
15037 }
15038
15039 #[test]
15040 fn entrada_accepts_canonical_hosts() {
15041 // Positive-control sweep — every form the Gateway API
15042 // apiserver accepts must round-trip through validate. Covers
15043 // a plain DNS subdomain, a leading wildcard, a single-label
15044 // host (cluster-internal), a max-length-edge label, a
15045 // hyphen-bearing label, and a Punycode IDN label.
15046 for host in [
15047 "checkout.quero.cloud",
15048 "*.quero.cloud",
15049 "checkout",
15050 // 63-byte label — exactly the per-label cap.
15051 "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
15052 "foo-bar.quero.cloud",
15053 // Punycode IDN — valid because the author pre-encoded.
15054 "xn--bcher-kva.example.com",
15055 ] {
15056 let mut s = three_member_spec();
15057 s.entrada.as_mut().unwrap().host = host.into();
15058 s.validate()
15059 .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
15060 }
15061 }
15062
15063 #[test]
15064 fn entrada_host_max_length_validates() {
15065 // 253-byte host is the cap exactly — must validate. Build a
15066 // 253-byte host out of three 63-byte labels + one 61-byte
15067 // label + 3 dots = 252 bytes, then pad one byte to 253.
15068 let mut s = three_member_spec();
15069 let host = format!(
15070 "{}.{}.{}.{}",
15071 "a".repeat(63),
15072 "b".repeat(63),
15073 "c".repeat(63),
15074 "d".repeat(253 - 63 * 3 - 3)
15075 );
15076 assert_eq!(host.len(), 253);
15077 s.entrada.as_mut().unwrap().host = host;
15078 s.validate().unwrap();
15079 }
15080
15081 #[test]
15082 fn entrada_host_total_length_cap_threads_lifted_render_const() {
15083 // Cross-crate-side pin: the aplicacao-side `:entrada :host`
15084 // total-length gate now reads the K8s Gateway API v1 Hostname
15085 // `maxLength: 253` cap from the lifted
15086 // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
15087 // of truth — the same constant every future Gateway-API-Hostname
15088 // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
15089 // materializer's per-host validator, the future per-`Certificate`
15090 // SAN emitter for cert-manager, the multi-`:entrada`
15091 // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
15092 // from. Before the lift, the aplicacao-side reader consumed a
15093 // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
15094 // 253-byte value as the peer render-side canonical bounds
15095 // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
15096 // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
15097 // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
15098 // module boundary — a future 253-byte drift on either side would
15099 // silently split into two axes' worth of admission-schema mismatch
15100 // without a build-time signal. Pin the cap through a fresh 254-
15101 // byte host that hits the total-length arm, then read the reason
15102 // for the exact byte count the shared constant carries: any future
15103 // regression on the lift (a private alias reintroduced, a hard-
15104 // coded literal at the arm, a mismatch between the aplicacao-side
15105 // and render-side canonicals) surfaces as this pin's diagnostic
15106 // failing to match, not as a per-cluster admission rejection far
15107 // from the caixa.lisp source line.
15108 let mut s = three_member_spec();
15109 let over_cap = format!(
15110 "{}.{}.{}.{}",
15111 "a".repeat(63),
15112 "b".repeat(63),
15113 "c".repeat(63),
15114 "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
15115 );
15116 assert_eq!(
15117 over_cap.len(),
15118 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
15119 );
15120 s.entrada.as_mut().unwrap().host = over_cap;
15121 let err = s.validate().unwrap_err();
15122 match err {
15123 AplicacaoError::EntradaHostInvalid { reason, .. } => {
15124 let needle = format!(
15125 "max length of {} bytes",
15126 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
15127 );
15128 assert!(
15129 reason.contains(&needle),
15130 "diagnostic must name the lifted \
15131 GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
15132 );
15133 }
15134 other => panic!("expected EntradaHostInvalid, got {other:?}"),
15135 }
15136 }
15137
15138 #[test]
15139 fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
15140 // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
15141 // on the per-label-cap axis. Before the lift, the aplicacao-side
15142 // per-label arm consumed a private const alias
15143 // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
15144 // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
15145 // split from it at the module boundary — every `.`-separated
15146 // label in a Gateway API v1 Hostname is a DNS-1123 label under
15147 // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
15148 // so the private alias's 63 and the canonical const's 63 were
15149 // pinning the same underlying rule twice. Pin the cap through a
15150 // 64-byte label that hits the per-label arm, then read the reason
15151 // for the exact byte count the shared constant carries: any
15152 // future drift on either side (a private alias reintroduced, a
15153 // hard-coded literal at the arm, a mismatch between the two
15154 // 63-byte pins) surfaces at this pin's diagnostic rather than at
15155 // a per-cluster admission rejection whose "field is invalid"
15156 // opacity misframes the root cause.
15157 let mut s = three_member_spec();
15158 let over_cap_label = format!(
15159 "{}.quero.cloud",
15160 "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
15161 );
15162 s.entrada.as_mut().unwrap().host = over_cap_label;
15163 let err = s.validate().unwrap_err();
15164 match err {
15165 AplicacaoError::EntradaHostInvalid { reason, .. } => {
15166 let needle = format!(
15167 "label max length of {} bytes",
15168 crate::render::DNS_1123_LABEL_MAX_LEN,
15169 );
15170 assert!(
15171 reason.contains(&needle),
15172 "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
15173 cap verbatim on the per-label arm, got: {reason:?}",
15174 );
15175 }
15176 other => panic!("expected EntradaHostInvalid, got {other:?}"),
15177 }
15178 }
15179
15180 #[test]
15181 fn entrada_with_empty_paths_validates() {
15182 // Empty `:paths` is the documented "match every path" form;
15183 // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
15184 let mut s = three_member_spec();
15185 s.entrada.as_mut().unwrap().paths = vec![];
15186 s.validate().unwrap();
15187 }
15188
15189 #[test]
15190 fn entrada_root_path_validates() {
15191 // The author-supplied bare-root `:entrada :paths` entry is the
15192 // same byte-shape the peer emit-side catch-all constant
15193 // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
15194 // the author's `:paths` list is empty — sweeping the test-side
15195 // probe literal onto the lifted const closes the two-axis pin
15196 // (author-side admit + emit-side canonical fallback) around
15197 // one `&'static str`, so a future rebrand of the catch-all
15198 // reaches both consumers by construction. Peer to
15199 // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
15200 // on the canonical-literal pin surface.
15201 let mut s = three_member_spec();
15202 s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
15203 s.validate().unwrap();
15204 }
15205
15206 #[test]
15207 fn placement_strategy_variants_round_trip() {
15208 for s in [
15209 PlacementStrategy::SingleNode,
15210 PlacementStrategy::Replicated,
15211 PlacementStrategy::Sharded,
15212 ] {
15213 let p = Placement {
15214 estrategia: s,
15215 clusters: vec!["rio".into()],
15216 affinity: None,
15217 // Route the paired `:shard-key` fixture-builder through the
15218 // typed cross-slot invariant predicate
15219 // [`PlacementStrategy::requires_shard_key`] rather than the
15220 // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
15221 // arm-identity predicate — the two answer the same
15222 // question under today's closed accept-set but a future
15223 // arm addition that consumed `:shard-key` under a
15224 // non-`Sharded` name would silently mis-attach the
15225 // fixture's `:shard-key` if the builder read through the
15226 // arm-identity predicate. The cross-slot-invariant
15227 // predicate migrates through one caixa-core edit on any
15228 // future arm addition; the fixture keeps producing a
15229 // `validate()`-passing round-trip by construction.
15230 shard_key: if s.requires_shard_key() {
15231 Some("$key".into())
15232 } else {
15233 None
15234 },
15235 };
15236 let json = serde_json::to_string(&p).unwrap();
15237 let back: Placement = serde_json::from_str(&json).unwrap();
15238 assert_eq!(back, p);
15239 }
15240 }
15241
15242 #[test]
15243 fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
15244 // The fail-before-pass-after pin: pre-lift there was no
15245 // single-source binding between the [`PlacementStrategy`]
15246 // variant name the `Serialize` derive emits and the byte-
15247 // string every downstream cluster-side dispatcher (the
15248 // `lareira-fleet-programs` aggregator's per-entry strategy
15249 // branch, the future `app-operator` reconciler, the M3
15250 // Adaptive compression pass's per-strategy weighting) probes
15251 // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
15252 // future `#[serde(rename_all = "kebab-case")]` attribute on
15253 // the enum — or a variant rename in the source — would
15254 // silently rebrand the emitted scalar under one spelling
15255 // while every downstream dispatcher still probed the other,
15256 // with the failure surfacing at the aggregator's dispatch
15257 // step or the operator's reconcile posture (workloads coming
15258 // up under the `default()` `Replicated` arm rather than the
15259 // typed slot's declared strategy) far from the source
15260 // rebrand commit and with no field naming the drift. Pinning
15261 // the two paths (the `Serialize` derive's serialized string
15262 // AND the [`PlacementStrategy::as_str`] helper) to the same
15263 // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
15264 // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15265 // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
15266 // makes any future drift on either endpoint fail here at
15267 // caixa-core build time.
15268 for (variant, expected) in [
15269 (
15270 PlacementStrategy::SingleNode,
15271 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15272 ),
15273 (
15274 PlacementStrategy::Replicated,
15275 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15276 ),
15277 (
15278 PlacementStrategy::Sharded,
15279 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15280 ),
15281 ] {
15282 let json = serde_json::to_string(&variant).unwrap();
15283 assert_eq!(
15284 json,
15285 format!("\"{expected}\""),
15286 "PlacementStrategy::{variant:?} must serialize to {expected:?}"
15287 );
15288 assert_eq!(
15289 variant.as_str(),
15290 expected,
15291 "PlacementStrategy::{variant:?}.as_str() must return the lifted \
15292 M3_PLACEMENT_ESTRATEGIA_* constant"
15293 );
15294 }
15295 }
15296
15297 #[test]
15298 fn m3_placement_estrategia_consts_are_pairwise_distinct() {
15299 // Cross-arm drift-detection pin on the M3
15300 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
15301 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15302 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
15303 // scalar-value pentad: a future collapse of two canonical
15304 // variant byte-strings onto the same value (an accidental
15305 // copy-paste flip of
15306 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
15307 // read `"SingleNode"`, a per-arm rebrand that lands one const
15308 // without touching its paired peer) would silently reroute
15309 // every downstream operator's per-strategy dispatch onto the
15310 // sibling arm's reconcile branch and pass every
15311 // propagation-probe test that expected only the stale arm's
15312 // value — a `Replicated`-declared Aplicacao would come up
15313 // under the `SingleNode` primary-and-standby reconcile
15314 // posture, so every-cluster active-active workload would
15315 // silently collapse onto one-cluster-runs-at-a-time takeover
15316 // semantics against its declared strategy, with no field
15317 // naming the strategy-value drift root cause. Peer of the
15318 // sibling
15319 // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
15320 // (09ffb2d) /
15321 // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
15322 // (ccdf955) /
15323 // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
15324 // (d739850) distinctness pins on the sibling OTP-shape /
15325 // caixa-kind closed-set typed-enum discriminator axes — the
15326 // fourth (and structurally the M3 mesh-primitive-defining)
15327 // closed-set typed-enum axis to converge on the same
15328 // "pairwise-distinct-by-construction" discipline.
15329 //
15330 // Fail-before-pass-after locally verified by mutating
15331 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
15332 // also read `"SingleNode"` — this pin fires as expected;
15333 // restoring passes.
15334 let all = [
15335 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15336 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15337 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15338 ];
15339 for (i, a) in all.iter().enumerate() {
15340 for (j, b) in all.iter().enumerate() {
15341 if i != j {
15342 assert_ne!(
15343 a, b,
15344 "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
15345 distinct — got duplicate {a:?} at indices {i} and {j}",
15346 );
15347 }
15348 }
15349 }
15350 }
15351
15352 #[test]
15353 fn placement_strategy_display_routes_through_as_str_helper() {
15354 // The fail-before-pass-after pin: pre-lift the sibling
15355 // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
15356 // / [`crate::supervisor::RestartPolicy`] both carried a stable
15357 // [`std::fmt::Display`] surface via their
15358 // `#[discriminant(also_display)]` gen-platform derive, but
15359 // [`PlacementStrategy`] did not — every consumer reaching for
15360 // a strategy byte-string past the wire format had to pick
15361 // between three paths ([`PlacementStrategy::as_str`], the
15362 // `Serialize` derive's serialized string, or `format!("{v:?}")`
15363 // on the `Debug` derive), any two of which a future variant
15364 // rename or `#[serde(rename_all = "kebab-case")]` attribute
15365 // would silently desynchronize. Wiring [`std::fmt::Display`]
15366 // through [`PlacementStrategy::as_str`] closes the third path:
15367 // every `format!("{v}")` call reaches the same lifted
15368 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15369 // and the [`PlacementStrategy::as_str`] helper already route
15370 // through, so a future variant rename lands at exactly one
15371 // place. Pin the routing here so a future
15372 // `impl std::fmt::Display for PlacementStrategy` reimplementation
15373 // that hand-rolls the arms instead of delegating to
15374 // [`PlacementStrategy::as_str`] fails at caixa-core build time.
15375 for variant in [
15376 PlacementStrategy::SingleNode,
15377 PlacementStrategy::Replicated,
15378 PlacementStrategy::Sharded,
15379 ] {
15380 assert_eq!(
15381 variant.to_string(),
15382 variant.as_str(),
15383 "PlacementStrategy::{variant:?} Display must route through \
15384 PlacementStrategy::as_str (single source of truth: the lifted \
15385 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
15386 );
15387 }
15388 }
15389
15390 #[test]
15391 fn placement_strategy_display_matches_serialized_wire_byte_string() {
15392 // The fail-before-pass-after pin on the second half of the
15393 // three-path convergence: `Display` (user-facing text) agrees
15394 // byte-for-byte with the `Serialize` derive's wire format
15395 // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
15396 // scalar) on every variant. Pre-lift the two paths were
15397 // structurally independent — a future
15398 // `#[serde(rename_all = "kebab-case")]` attribute on the enum
15399 // would silently rebrand the emitted wire scalar
15400 // (`single-node`, `replicated`, `sharded`) while every consumer
15401 // that pretty-prints the strategy (the M3 diagnostic templates,
15402 // the future `feira app graph` per-Aplicacao strategy line,
15403 // the future M4 CR materializer's admission-webhook rejection
15404 // body) would still emit the TitleCase form the `as_str` /
15405 // `Display` route returns, with the mismatch surfacing at
15406 // consumer parse time / operator dispatch time far from the
15407 // source rebrand commit. Pin the two paths byte-for-byte here
15408 // so any future serde-attribute or variant-rename drift is a
15409 // caixa-core-build-time test failure at this call, not a
15410 // silent per-consumer dispatch miss.
15411 for variant in [
15412 PlacementStrategy::SingleNode,
15413 PlacementStrategy::Replicated,
15414 PlacementStrategy::Sharded,
15415 ] {
15416 let wire = serde_json::to_string(&variant).unwrap();
15417 // Strip the outer `"…"` the JSON string form carries — the
15418 // wire scalar the K8s / YAML apiserver consumes is the
15419 // enclosed byte-string, not the quote wrapper.
15420 let unquoted = wire
15421 .strip_prefix('"')
15422 .and_then(|s| s.strip_suffix('"'))
15423 .expect("serialized PlacementStrategy is a JSON string");
15424 assert_eq!(
15425 variant.to_string(),
15426 unquoted,
15427 "PlacementStrategy::{variant:?} Display byte-string must match the \
15428 Serialize derive's wire byte-string (three-path convergence: \
15429 Display + as_str + Serialize all resolve to the same \
15430 M3_PLACEMENT_ESTRATEGIA_* const)"
15431 );
15432 }
15433 }
15434
15435 #[test]
15436 fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
15437 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
15438 // derive on [`PlacementStrategy`]: for each of the three variants
15439 // exactly one of the generated `is_single_node` / `is_replicated`
15440 // / `is_sharded` predicates returns `true` and the other two
15441 // return `false`. Prior to this derive the three per-arm
15442 // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
15443 // (the `placement_strategy_variants_round_trip` fixture, the
15444 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
15445 // fixture, and the
15446 // `validate_placement_reads_through_lifted_estrategia_accessor`
15447 // fixture) each open-coded a per-arm PartialEq compare against
15448 // the enum variant — three sites that expressed no compile-time
15449 // link back to the closed-set typed dispatch a future fourth
15450 // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
15451 // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
15452 // would have to thread through in lockstep or one fixture would
15453 // silently disagree with the others on which arms consume the
15454 // `:shard-key` axis. Peer of the sibling
15455 // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
15456 // / [`crate::supervisor::RestartPolicy`] /
15457 // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
15458 // the sibling closed-set typed-enum discriminator axes — extends
15459 // the same one-typed-dispatch-per-variant discipline onto the
15460 // fifth (and only remaining) closed-set typed-enum discriminator
15461 // on the caixa surface, closing the axis on the M3 mesh-slot
15462 // family.
15463 let rows: [(PlacementStrategy, [bool; 3]); 3] = [
15464 (PlacementStrategy::SingleNode, [true, false, false]),
15465 (PlacementStrategy::Replicated, [false, true, false]),
15466 (PlacementStrategy::Sharded, [false, false, true]),
15467 ];
15468 for (variant, expected) in rows {
15469 let observed = [
15470 variant.is_single_node(),
15471 variant.is_replicated(),
15472 variant.is_sharded(),
15473 ];
15474 assert_eq!(
15475 observed, expected,
15476 "PlacementStrategy::{variant:?} is_* predicates must partition \
15477 the arm set (single_node, replicated, sharded); got {observed:?}"
15478 );
15479 }
15480 }
15481
15482 #[test]
15483 fn placement_strategy_is_variant_predicates_are_const_fn() {
15484 // The [`gen_platform::IsVariant`] derive emits `const fn`
15485 // predicates on the peer [`crate::CaixaKind`] +
15486 // [`crate::upgrade::UpgradeInstruction`] +
15487 // [`crate::supervisor::RestartStrategy`] +
15488 // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
15489 // pin the same posture on [`PlacementStrategy`] so a future
15490 // accidental downgrade to non-`const` (an added runtime helper
15491 // reachable only from a non-`const` context, a manual hand-rolled
15492 // `impl` that shadows the derive-generated method) trips at
15493 // caixa-core build time rather than surfacing as a downstream
15494 // `const`-context regression far from the derive declaration.
15495 const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
15496 const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
15497 const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
15498 assert!(IS_SINGLE_NODE);
15499 assert!(IS_REPLICATED);
15500 assert!(IS_SHARDED);
15501 }
15502
15503 #[test]
15504 fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
15505 // Fail-before-pass-after pin on the substrate-lifted
15506 // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
15507 // per-arm predicate: for each variant in the closed accept-set the
15508 // predicate returns `true` iff the variant consumes the paired
15509 // [`Placement::shard_key`] axis under
15510 // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
15511 // partition. Today the accept-set is the singleton `{Sharded}` —
15512 // `Sharded` is the Akka-style hash-keyed distribution arm
15513 // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
15514 // §II.1) and `Replicated` (active-active) refuse the axis through
15515 // [`AplicacaoError::ShardKeyOnNonSharded`].
15516 //
15517 // Pins the per-arm truth-table so a future arm addition (an
15518 // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
15519 // roadmap names, a `WeightedShard` promotion the future M5
15520 // adaptive-placement engine acknowledges) that landed a variant
15521 // without extending this predicate's arm-set would surface as a
15522 // caixa-core build-time exhaustiveness error at the
15523 // `match self { … }` arm-fan below rather than a silent per-consumer
15524 // mis-classification at renderer emit time. The paired
15525 // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
15526 // predicate stays a distinct question — arm-identity (which the
15527 // sibling
15528 // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
15529 // pin already locks) is not cross-slot-invariant consumption; today
15530 // they trip on the same singleton but the pair migrates through
15531 // one caixa-core edit on any future arm addition.
15532 //
15533 // Peer of the sibling per-arm classifier pins
15534 // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
15535 // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
15536 // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
15537 // derived paired predicate on the post-projection typed-view axis
15538 // — same "per-arm semantic-classification predicate paired with
15539 // the arm-identity predicate the derive already emits" discipline
15540 // extended onto the M3 mesh-slot `:placement :estrategia` ↔
15541 // `:placement :shard-key` cross-slot-invariant axis.
15542 let rows: [(PlacementStrategy, bool); 3] = [
15543 (PlacementStrategy::SingleNode, false),
15544 (PlacementStrategy::Replicated, false),
15545 (PlacementStrategy::Sharded, true),
15546 ];
15547 for (variant, expected) in rows {
15548 assert_eq!(
15549 variant.requires_shard_key(),
15550 expected,
15551 "PlacementStrategy::{variant:?}.requires_shard_key() must \
15552 be {expected} (the substrate-canonical cross-slot invariant \
15553 on the :placement :shard-key axis; today `Sharded` is the \
15554 singleton consuming arm — MESH-COMPOSITION §II.4)",
15555 );
15556 }
15557 }
15558
15559 #[test]
15560 fn placement_strategy_requires_shard_key_is_const_fn() {
15561 // The [`PlacementStrategy::requires_shard_key`] cross-slot-
15562 // invariant per-arm predicate is declared `#[must_use] pub const
15563 // fn` — pin the `const`-eval posture here so a future accidental
15564 // downgrade to non-`const` (an added runtime helper reachable
15565 // only from a non-`const` context, a manual hand-rolled `impl`
15566 // that shadows the current three-arm `match self { … }` dispatch)
15567 // trips at caixa-core build time rather than surfacing as a
15568 // downstream `const`-context regression far from the declaration.
15569 // Same shape as the sibling
15570 // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
15571 // the peer [`gen_platform::IsVariant`]-derived arm-identity
15572 // predicate axis, but here the load-bearing assertions live in
15573 // module-scope `const _: () = assert!(…)` items so a violation
15574 // fails at compile time (const-eval trip) rather than test time —
15575 // strictly stronger than the runtime `assert!(CONST)` pattern the
15576 // sibling pin uses, and side-steps the
15577 // `clippy::assertions_on_constants` lint the runtime pattern
15578 // otherwise accumulates on the module baseline.
15579 //
15580 // The test body simply witnesses that the module-scope items
15581 // compiled and the runtime dispatch agrees with the const-eval
15582 // dispatch on every arm — the runtime read gives the test a
15583 // failure surface (rather than an empty test body clippy would
15584 // flag as a no-op).
15585 const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
15586 const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
15587 const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
15588 assert_eq!(
15589 [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
15590 [
15591 PlacementStrategy::SingleNode.requires_shard_key(),
15592 PlacementStrategy::Replicated.requires_shard_key(),
15593 PlacementStrategy::Sharded.requires_shard_key(),
15594 ],
15595 "runtime and const-eval dispatch on \
15596 PlacementStrategy::requires_shard_key must agree on every arm",
15597 );
15598 }
15599
15600 #[test]
15601 fn placement_estrategia_accessor_is_const_fn() {
15602 // The [`Placement::estrategia`] per-`:placement` distribution-
15603 // strategy `Copy`-return scalar accessor is declared
15604 // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
15605 // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
15606 // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
15607 // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
15608 // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
15609 // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
15610 // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
15611 // [`RateLimit`], every one a `pub const fn`). Pin the
15612 // `const`-eval posture here so a future accidental downgrade to
15613 // non-`const` (an added runtime helper reachable only from a
15614 // non-`const` context, a slot promotion to a non-`Copy` return
15615 // that would silently drop the `const` qualifier, a manual
15616 // hand-rolled shadow) trips at caixa-core build time rather
15617 // than surfacing as a downstream `const`-context regression far
15618 // from the declaration.
15619 //
15620 // Same shape as the sibling
15621 // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
15622 // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
15623 // predicate axis — the load-bearing witness lives in the
15624 // module-scope `const fn` wrapper `estrategia_via_const_fn`
15625 // below: a body that calls [`Placement::estrategia`] under a
15626 // `const fn` signature is well-formed only when the callee is
15627 // itself `const fn`, so any future accidental downgrade of
15628 // [`Placement::estrategia`] to non-`const` fails at caixa-core
15629 // build time (const-eval E0015 / E0658 depending on the arm),
15630 // strictly stronger than a runtime `assert!(CONST)` and
15631 // side-stepping the destructor-in-const restriction that
15632 // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
15633 // items on `Placement`'s `Vec<String>` / `Option<String>`
15634 // carriers.
15635 //
15636 // The runtime body witnesses that the const-eval-shaped
15637 // wrapper agrees with a direct call on every closed-set arm.
15638 const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
15639 p.estrategia()
15640 }
15641 for estrategia in [
15642 PlacementStrategy::SingleNode,
15643 PlacementStrategy::Replicated,
15644 PlacementStrategy::Sharded,
15645 ] {
15646 let placement = Placement {
15647 estrategia,
15648 clusters: Vec::new(),
15649 affinity: None,
15650 shard_key: None,
15651 };
15652 assert_eq!(
15653 estrategia_via_const_fn(&placement),
15654 placement.estrategia(),
15655 "const-fn-wrapped and direct dispatch on \
15656 Placement::estrategia must agree for {estrategia:?}",
15657 );
15658 }
15659 }
15660
15661 #[test]
15662 fn entrada_port_accessor_is_const_fn() {
15663 // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
15664 // scalar accessor is declared `#[must_use] pub const fn` —
15665 // matching the peer M3 mesh-slot `Copy`-return accessor family
15666 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
15667 // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
15668 // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
15669 // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
15670 // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
15671 // [`RateLimit::window`] on the sibling [`RateLimit`], the
15672 // sibling per-`:placement` [`Placement::estrategia`] pinned by
15673 // [`placement_estrategia_accessor_is_const_fn`] above — every
15674 // one a `pub const fn`). Pin the `const`-eval posture here so
15675 // a future accidental downgrade to non-`const` (an added
15676 // runtime helper reachable only from a non-`const` context, an
15677 // `Option<u16>`-shape migration once the substrate grows
15678 // per-`:membros` heterogeneous listener ports that would
15679 // silently drop the `const` qualifier, a manual hand-rolled
15680 // shadow) trips at caixa-core build time rather than surfacing
15681 // as a downstream `const`-context regression far from the
15682 // declaration.
15683 //
15684 // Same shape as the sibling
15685 // [`placement_estrategia_accessor_is_const_fn`] pin above — the
15686 // load-bearing witness lives in the module-scope `const fn`
15687 // wrapper `port_via_const_fn`: a body that calls
15688 // [`Entrada::port`] under a `const fn` signature is well-formed
15689 // only when the callee is itself `const fn`, side-stepping the
15690 // destructor-in-const restriction that would otherwise block a
15691 // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
15692 // `String` / `Vec<String>` carriers.
15693 //
15694 // The runtime body sweeps a representative port set spanning
15695 // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
15696 // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
15697 // ceiling — the const-fn-wrapped call must agree with a direct
15698 // call on every fixture (a violation trips the test) and every
15699 // returned scalar must byte-equal the input `port` (a violation
15700 // means the accessor stopped being a raw field-return copy).
15701 const fn port_via_const_fn(e: &Entrada) -> u16 {
15702 e.port()
15703 }
15704 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
15705 let entrada = Entrada {
15706 host: String::new(),
15707 para: String::new(),
15708 port,
15709 paths: Vec::new(),
15710 };
15711 assert_eq!(
15712 port_via_const_fn(&entrada),
15713 entrada.port(),
15714 "const-fn-wrapped and direct dispatch on Entrada::port \
15715 must agree for port={port}",
15716 );
15717 assert_eq!(
15718 entrada.port(),
15719 port,
15720 "Entrada::port must return the storage-side u16 verbatim \
15721 for port={port}",
15722 );
15723 }
15724 }
15725
15726 #[test]
15727 fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
15728 // Load-bearing cross-slot-partition pin closing the loop between
15729 // the substrate-lifted
15730 // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
15731 // the closed-set typed enum and the actual
15732 // [`AplicacaoSpec::validate_placement`] runtime behavior across
15733 // the paired `:placement :shard-key` axis: every validated
15734 // [`Placement`] past [`AplicacaoSpec::validate_placement`]
15735 // satisfies `placement.shard_key().is_some() ==
15736 // placement.estrategia().requires_shard_key()`. The four-cell
15737 // shape witness sweeps every combination of (variant in the
15738 // closed accept-set, `:shard-key` Some/None) and pins:
15739 //
15740 // * variant.requires_shard_key() && shard_key.is_some() →
15741 // validate() passes; the paired shape is the sole
15742 // `requires_shard_key` arm-family accepted shape.
15743 // * variant.requires_shard_key() && shard_key.is_none() →
15744 // validate() fails with [`AplicacaoError::ShardedWithoutKey`];
15745 // the paired shape is the refused missing-key shape on
15746 // Sharded-family arms.
15747 // * !variant.requires_shard_key() && shard_key.is_some() →
15748 // validate() fails with
15749 // [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
15750 // is the refused declared-but-inert shape on non-Sharded-
15751 // family arms.
15752 // * !variant.requires_shard_key() && shard_key.is_none() →
15753 // validate() passes; the paired shape is the sole
15754 // non-`requires_shard_key` arm-family accepted shape.
15755 //
15756 // The compile-time-exhaustive `match p.estrategia()` dispatch at
15757 // [`AplicacaoSpec::validate_placement`] preserves its structural
15758 // arm-fan (a future arm addition still surfaces a build-time
15759 // exhaustiveness error there); this pin closes the semantic loop
15760 // between the arm-fan's shape-gate cascades and the substrate-
15761 // canonical predicate every downstream consumer of the paired
15762 // shape reads through. Fail-before-pass-after locally verified by
15763 // mutating the predicate's `Sharded => true` arm to `false` — the
15764 // truthy `expects_ok` cell for `Sharded` + `Some` trips the
15765 // `validate() must pass` assertion; restoring passes. Same "close
15766 // the loop between the typed predicate and the runtime behavior"
15767 // discipline as the sibling
15768 // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
15769 // (7b97d26) cross-projection pin on the peer [`WitTarget`]
15770 // per-arm classifier axis.
15771 for variant in [
15772 PlacementStrategy::SingleNode,
15773 PlacementStrategy::Replicated,
15774 PlacementStrategy::Sharded,
15775 ] {
15776 for present in [false, true] {
15777 let mut spec = three_member_spec();
15778 spec.placement.estrategia = variant;
15779 spec.placement.shard_key = present.then(|| "tenantId".into());
15780 let expects_ok = variant.requires_shard_key() == present;
15781 let result = spec.validate();
15782 match (expects_ok, &result) {
15783 (true, Ok(())) => {}
15784 (false, Err(err)) => {
15785 // Cross-check the refusal diagnostic names the
15786 // right cell of the four-cell shape witness — the
15787 // `requires_shard_key && !present` cell must trip
15788 // [`AplicacaoError::ShardedWithoutKey`]; the
15789 // `!requires_shard_key && present` cell must trip
15790 // [`AplicacaoError::ShardKeyOnNonSharded`].
15791 match (variant.requires_shard_key(), present, err) {
15792 (true, false, AplicacaoError::ShardedWithoutKey) => {}
15793 (
15794 false,
15795 true,
15796 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
15797 ) => {
15798 assert_eq!(
15799 *e, variant,
15800 "ShardKeyOnNonSharded.estrategia must byte-equal \
15801 the paired PlacementStrategy",
15802 );
15803 }
15804 _ => panic!(
15805 "unexpected refusal for estrategia={variant:?} \
15806 present={present}: {err:?}"
15807 ),
15808 }
15809 }
15810 (true, Err(err)) => panic!(
15811 "validate() must pass for estrategia={variant:?} \
15812 present={present} (requires_shard_key={} == present={present}), \
15813 got {err:?}",
15814 variant.requires_shard_key(),
15815 ),
15816 (false, Ok(())) => panic!(
15817 "validate() must fail for estrategia={variant:?} \
15818 present={present} (requires_shard_key={} != present={present})",
15819 variant.requires_shard_key(),
15820 ),
15821 }
15822 }
15823 }
15824 }
15825
15826 #[test]
15827 fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
15828 // Pin the M3 diagnostic template routes through the typed
15829 // [`PlacementStrategy`] Display byte-string (rebound from the
15830 // prior `{estrategia:?}` `Debug` route). Pre-lift the two
15831 // routes emitted identical bytes (the `Debug` derive on a
15832 // unit variant emits the variant name verbatim, exactly what
15833 // `as_str` returns), but the two paths were structurally
15834 // independent — a future `#[serde(rename_all = "…")]`
15835 // attribute or variant rename would coordinate the wire /
15836 // `Display` / `as_str` triple through the lifted const but
15837 // leave the `Debug` route on the compiler-derived variant name,
15838 // silently desynchronizing the diagnostic byte-string from the
15839 // wire byte-string. Rebinding the template onto `Display`
15840 // ties the diagnostic to the same lifted
15841 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15842 // emits — drift becomes structurally impossible. Pin the
15843 // byte-string here so a future edit that reverts the template
15844 // to `{estrategia:?}` is caught at caixa-core test time, not
15845 // at consumer dispatch time.
15846 for (variant, expected_scalar) in [
15847 (
15848 PlacementStrategy::SingleNode,
15849 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15850 ),
15851 (
15852 PlacementStrategy::Replicated,
15853 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15854 ),
15855 (
15856 PlacementStrategy::Sharded,
15857 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15858 ),
15859 ] {
15860 let err = AplicacaoError::PlacementWithoutClusters {
15861 estrategia: variant,
15862 };
15863 let msg = err.to_string();
15864 assert!(
15865 msg.starts_with(&format!(":placement {expected_scalar} requires")),
15866 "PlacementWithoutClusters diagnostic for {variant:?} must open \
15867 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
15868 );
15869 }
15870 }
15871
15872 #[test]
15873 fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
15874 // Peer of
15875 // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
15876 // on the second M3 diagnostic that carries the typed
15877 // [`PlacementStrategy`] in its `#[error(…)]` template. Both
15878 // diagnostics now route the strategy scalar through the same
15879 // [`std::fmt::Display`] surface, tying the diagnostic
15880 // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
15881 // const set the wire format also emits. The two non-Sharded
15882 // arms are exercised here (the diagnostic exists to flag a
15883 // `:shard-key` slot the current strategy will never consume);
15884 // the peer `Sharded` arm never reaches this diagnostic (the
15885 // `Sharded` strategy consumes `:shard-key` — the
15886 // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
15887 // slot instead).
15888 for (variant, expected_scalar) in [
15889 (
15890 PlacementStrategy::SingleNode,
15891 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15892 ),
15893 (
15894 PlacementStrategy::Replicated,
15895 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15896 ),
15897 ] {
15898 let err = AplicacaoError::ShardKeyOnNonSharded {
15899 estrategia: variant,
15900 shard_key: "$tenantId".into(),
15901 };
15902 let msg = err.to_string();
15903 assert!(
15904 msg.starts_with(&format!(":placement {expected_scalar} carries")),
15905 "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
15906 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
15907 );
15908 }
15909 }
15910
15911 #[test]
15912 fn placement_strategy_all_enumerates_every_variant_once() {
15913 // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
15914 // exhaustive-iteration surface: every variant appears exactly
15915 // once, and the slice length matches the arm count of the
15916 // closed set. Every consumer that walks the accepted-strategy
15917 // set (a future `feira app placement --list` CLI-side surfacing,
15918 // a future M4 admission-webhook's rejection body naming the
15919 // accepted-strategy list, the [`PlacementStrategy::from_wire`]
15920 // reverse-projection consumers that iterate the accept-set for
15921 // a "did you mean" hint) reads through this slice, so a future
15922 // variant addition (an `Anycast` mesh-anycast arm the
15923 // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
15924 // grows the enum but forgets to grow [`Self::ALL`] silently
15925 // truncates every downstream consumer's accept-set at the same
15926 // pre-addition boundary — this pin fails at caixa-core build
15927 // time on the pairwise-distinct + arm-count invariants.
15928 //
15929 // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
15930 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
15931 // pins on the peer closed-set typed-enum axes.
15932 let all: &[PlacementStrategy] = PlacementStrategy::ALL;
15933 assert_eq!(
15934 all.len(),
15935 3,
15936 "PlacementStrategy::ALL must enumerate every variant of the \
15937 three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
15938 );
15939 for (i, a) in all.iter().enumerate() {
15940 for (j, b) in all.iter().enumerate() {
15941 if i != j {
15942 assert_ne!(
15943 a, b,
15944 "PlacementStrategy::ALL must carry every variant exactly \
15945 once — got duplicate {a:?} at indices {i} and {j}"
15946 );
15947 }
15948 }
15949 }
15950 for variant in [
15951 PlacementStrategy::SingleNode,
15952 PlacementStrategy::Replicated,
15953 PlacementStrategy::Sharded,
15954 ] {
15955 assert!(
15956 all.contains(&variant),
15957 "PlacementStrategy::ALL must contain {variant:?} — a future variant \
15958 addition that grows the enum but forgets to grow the ALL slice \
15959 silently truncates every downstream consumer's accept-set at the \
15960 pre-addition boundary"
15961 );
15962 }
15963 }
15964
15965 #[test]
15966 fn placement_strategy_from_wire_accepts_every_lifted_constant() {
15967 // Fail-before-pass-after pin on the forward accept-set of the
15968 // [`PlacementStrategy::from_wire`] reverse projection: every
15969 // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
15970 // constant the [`PlacementStrategy::as_str`] emitter walks
15971 // parses back to its paired variant. Any future arm addition
15972 // that grows the emitter's `as_str` match but forgets to grow
15973 // the parser's `from_str` match silently splits the two halves
15974 // of the round-trip — the wire byte-string one non-serde
15975 // consumer parses from the one the emitter wrote — with the
15976 // failure surfacing at parse time far from the rebrand commit.
15977 // Pinning the three-arm accept-set here catches the drift at
15978 // caixa-core build time.
15979 //
15980 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
15981 // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
15982 // closed-set typed-enum `str → Self` axes.
15983 for (wire, expected) in [
15984 (
15985 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15986 PlacementStrategy::SingleNode,
15987 ),
15988 (
15989 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15990 PlacementStrategy::Replicated,
15991 ),
15992 (
15993 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15994 PlacementStrategy::Sharded,
15995 ),
15996 ] {
15997 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15998 panic!(
15999 "PlacementStrategy::from_wire({wire:?}) must accept every \
16000 M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
16001 lifted canonical byte-string that PlacementStrategy::{expected:?} \
16002 serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
16003 )
16004 });
16005 assert_eq!(
16006 parsed, expected,
16007 "PlacementStrategy::from_wire({wire:?}) must return \
16008 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
16009 );
16010 }
16011 }
16012
16013 #[test]
16014 fn placement_strategy_from_wire_round_trips_through_as_str() {
16015 // Fail-before-pass-after pin on the closed round-trip between
16016 // the forward [`PlacementStrategy::as_str`] emitter and the
16017 // reverse [`PlacementStrategy::from_wire`] parser: for every
16018 // variant in [`PlacementStrategy::ALL`], parsing the emitter's
16019 // output must return exactly the same variant. Any per-arm
16020 // divergence — a future arm added to `as_str` but not
16021 // `from_str`, an accidental copy-paste flip in one but not the
16022 // other — silently splits the emit and parse halves and the
16023 // failure surfaces at consumer parse time far from the drift
16024 // site. The `ALL`-iterating shape means a future variant
16025 // addition picks up the coverage by construction.
16026 //
16027 // Peer of the sibling [`crate::kind::tests`] round-trip pin on
16028 // [`crate::CaixaKind::from_wire`] and the
16029 // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
16030 // sibling round-trip pin on [`RateLimitUnit`].
16031 for &variant in PlacementStrategy::ALL {
16032 let wire = variant.as_str();
16033 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16034 panic!(
16035 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16036 must be Some({variant:?}) — the two halves of the round-trip \
16037 dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
16038 got None on wire byte-string {wire:?}"
16039 )
16040 });
16041 assert_eq!(
16042 parsed, variant,
16043 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16044 must round-trip to the same variant; got {parsed:?}"
16045 );
16046 }
16047 }
16048
16049 #[test]
16050 fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
16051 // Fail-before-pass-after pin on the closed-set refusal
16052 // discipline of [`PlacementStrategy::from_wire`]: every
16053 // byte-string outside the three-arm accept-set returns `None`
16054 // rather than silently collapsing onto the [`Default`]
16055 // (`Replicated`) arm or an arbitrary neighbor. The refusal set
16056 // exercised here sweeps the load-bearing drift shapes: the
16057 // empty string (a stripped serde-attribute drift), an all-
16058 // whitespace string (the canonical text-editor accidental
16059 // padding shape), the lowercased kebab-case forms a future
16060 // `#[serde(rename_all = "kebab-case")]` attribute would emit
16061 // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
16062 // coincidentally match the accepted canonical scalars, so only
16063 // `"single-node"` fires as a refusal, but pinning the case-
16064 // sensitivity of the accepted arms via the peer [`SingleNode`]
16065 // assertion in the round-trip pin makes the discipline
16066 // structurally clear), the lowercased single-word forms
16067 // (`"singlenode"`), the padded canonical scalar
16068 // (`" Sharded "`), the trailing-comma / trailing-newline shapes
16069 // (`"Sharded\n"`), and a pointer-different `&'static str` that
16070 // happens to alias a canonical byte-string by content but not
16071 // by identity (validated implicitly by the emitter's routing
16072 // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
16073 // identity a paired [`crate::assert_str_reexport_identity`] pin
16074 // in caixa-core's per-const declaration surface would catch).
16075 //
16076 // Peer of the sibling
16077 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
16078 // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
16079 for bad in [
16080 "",
16081 " ",
16082 "\n",
16083 "\t",
16084 "single-node",
16085 "singlenode",
16086 "SingleNodes",
16087 "single_node",
16088 "single node",
16089 "SINGLENODE",
16090 "SingleNode ",
16091 " SingleNode",
16092 " Sharded ",
16093 "Sharded\n",
16094 "replicated ",
16095 "sharded",
16096 "REPLICATED",
16097 "Anycast",
16098 "Global",
16099 "?",
16100 ] {
16101 assert!(
16102 PlacementStrategy::from_wire(bad).is_none(),
16103 "PlacementStrategy::from_wire({bad:?}) must return None — the \
16104 parser's accept-set is exactly the three PlacementStrategy::as_str \
16105 outputs (SingleNode, Replicated, Sharded), and this byte-string \
16106 is outside that closed set"
16107 );
16108 }
16109 }
16110
16111 #[test]
16112 fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
16113 // Fail-before-pass-after pin on the third path of the four-path
16114 // convergence: `from_str` (the reverse projection) inverts the
16115 // `Serialize` derive's wire byte-string on every variant.
16116 // Together with the pre-existing three-path convergence
16117 // (`Display` + `as_str` + `Serialize` all resolve to the same
16118 // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
16119 // the peer
16120 // [`placement_strategy_display_matches_serialized_wire_byte_string`])
16121 // this closes the round-trip: the wire byte-string the
16122 // `Serialize` derive emits parses back to the same variant
16123 // through `from_str`, so any future serde-attribute or variant-
16124 // rename drift on the emit half now surfaces as a matched drift
16125 // on the parse half at caixa-core build time — the two halves
16126 // migrate as a unit through the lifted consts on any future
16127 // rename, and the round-trip cannot silently split.
16128 //
16129 // Peer of the sibling
16130 // [`placement_strategy_display_matches_serialized_wire_byte_string`]
16131 // wire-format pin — extends the three-path convergence
16132 // (`Display` + `as_str` + `Serialize`) onto the fourth path
16133 // (`from_str`), closing the `str ↔ Self` round-trip on the
16134 // M3 `:placement :estrategia` closed-set axis.
16135 for &variant in PlacementStrategy::ALL {
16136 let wire = serde_json::to_string(&variant).unwrap();
16137 let unquoted = wire
16138 .strip_prefix('"')
16139 .and_then(|s| s.strip_suffix('"'))
16140 .expect("serialized PlacementStrategy is a JSON string");
16141 let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
16142 panic!(
16143 "PlacementStrategy::from_wire({unquoted:?}) must accept the \
16144 Serialize derive's wire byte-string for \
16145 PlacementStrategy::{variant:?} — the four-path convergence \
16146 (Display + as_str + Serialize + from_str) resolves through \
16147 the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
16148 )
16149 });
16150 assert_eq!(
16151 parsed, variant,
16152 "PlacementStrategy::from_wire of the Serialize derive's wire \
16153 byte-string for PlacementStrategy::{variant:?} must round-trip \
16154 to the same variant; got {parsed:?}"
16155 );
16156 }
16157 }
16158
16159 #[test]
16160 fn rejects_zero_policy_timeout() {
16161 let mut s = three_member_spec();
16162 s.politicas.timeout = Some(Duration::ZERO);
16163 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16164 }
16165
16166 #[test]
16167 fn rejects_zero_policy_retries() {
16168 let mut s = three_member_spec();
16169 s.politicas.retries = Some(0);
16170 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
16171 }
16172
16173 #[test]
16174 fn rejects_policy_retries_above_cap() {
16175 // The fail-before-pass-after pin: `Some(11)` is structurally
16176 // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
16177 // passed validate on every pre-gate codebase because the
16178 // typed slot's only check was the zero-floor arm. The
16179 // thundering-herd amplification vector only surfaced at the
16180 // runtime substrate (Envoy / Cilium L7 retry overlay)
16181 // far from the source caixa.lisp with no field naming the
16182 // offending policy.
16183 let mut s = three_member_spec();
16184 s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
16185 assert_eq!(
16186 s.validate().unwrap_err(),
16187 AplicacaoError::PolicyRetriesExceedsCap {
16188 retries: POLICY_RETRIES_MAX + 1
16189 }
16190 );
16191 }
16192
16193 #[test]
16194 fn rejects_policy_retries_far_above_cap() {
16195 // The `u32::MAX` worst case — the four-billion-retry policy
16196 // a typo (`(:retries 4294967295)`) or struct-literal
16197 // copy-paste lands in the slot. Pin the cap arm's coverage
16198 // explicitly across the full `u32` overflow so a future
16199 // relaxation that drops the upper bound surfaces here.
16200 let mut s = three_member_spec();
16201 s.politicas.retries = Some(u32::MAX);
16202 assert_eq!(
16203 s.validate().unwrap_err(),
16204 AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
16205 );
16206 }
16207
16208 #[test]
16209 fn accepts_policy_retries_at_cap() {
16210 // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
16211 // must validate. The cap is inclusive on the top edge,
16212 // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16213 // discipline on the sibling [`crate::LimitsSpec::memory`]
16214 // axis. Pin the boundary explicitly so a future off-by-one
16215 // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
16216 // surfaces here as a test failure rather than a silent
16217 // contract narrowing.
16218 let mut s = three_member_spec();
16219 s.politicas.retries = Some(POLICY_RETRIES_MAX);
16220 s.validate()
16221 .expect("retries == POLICY_RETRIES_MAX must validate");
16222 }
16223
16224 #[test]
16225 fn accepts_policy_retries_typical_values() {
16226 // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
16227 // every value in the validated set must pass. The
16228 // Envoy / Istio production-playbook recommendation band
16229 // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
16230 // (`maxRetries ≤ 10`) both lie within this set.
16231 for r in 1..=POLICY_RETRIES_MAX {
16232 let mut s = three_member_spec();
16233 s.politicas.retries = Some(r);
16234 s.validate()
16235 .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
16236 }
16237 }
16238
16239 #[test]
16240 fn policy_retries_zero_takes_precedence_over_cap() {
16241 // The cross-arm ordering pin: `Some(0)` is structurally
16242 // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
16243 // (cap), but the zero-floor diagnostic is the more
16244 // self-locating one (it directly names the omit-axis
16245 // remediation), so the validate gate must fire on zero
16246 // first. Pin the order so a future refactor that reorders
16247 // the arms surfaces here as a test failure rather than a
16248 // silent diagnostic regression. Same shape every other
16249 // zero-then-shape ordering on this surface uses
16250 // ([`AplicacaoError::PolicyTimeoutZero`] then
16251 // [`AplicacaoError::PolicyTimeoutNotCanonical`];
16252 // [`AplicacaoError::PolicyBreakerZeroWindow`] then
16253 // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
16254 let mut s = three_member_spec();
16255 s.politicas.retries = Some(0);
16256 assert_eq!(
16257 s.validate().unwrap_err(),
16258 AplicacaoError::PolicyRetriesZero,
16259 "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
16260 );
16261 }
16262
16263 #[test]
16264 fn policy_retries_cap_diagnostic_carries_offending_value() {
16265 // The diagnostic-shape pin: the offending `u32` is carried
16266 // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
16267 // variant so the surfaced error message names the value the
16268 // author wrote (`":politicas :retries (47) exceeds the
16269 // mesh-policy ceiling …"`), not just the cap. Same
16270 // self-locating diagnostic shape every other typed-cap arm
16271 // on this surface carries
16272 // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16273 // offending byte count verbatim).
16274 let mut s = three_member_spec();
16275 s.politicas.retries = Some(47);
16276 let err = s.validate().unwrap_err();
16277 assert!(
16278 matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
16279 "got {err:?}"
16280 );
16281 let msg = err.to_string();
16282 assert!(
16283 msg.contains("47"),
16284 ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
16285 );
16286 }
16287
16288 #[test]
16289 fn policy_retries_cap_is_aws_app_mesh_aligned() {
16290 // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
16291 // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
16292 // schema cap — the only upstream mesh-policy schema that
16293 // documents an explicit hard cap. Pinning the literal value
16294 // here surfaces a future drift (a relaxation to 20, a
16295 // tightening to 5) as a deliberate test edit, not a silent
16296 // contract narrowing.
16297 assert_eq!(POLICY_RETRIES_MAX, 10);
16298 }
16299
16300 #[test]
16301 fn rejects_circuit_breaker_zero_max_failures() {
16302 let mut s = three_member_spec();
16303 s.politicas.circuit_breaker = Some(CircuitBreaker {
16304 max_failures: 0,
16305 window: Duration::from_secs(60),
16306 });
16307 assert_eq!(
16308 s.validate().unwrap_err(),
16309 AplicacaoError::PolicyBreakerZeroFailures
16310 );
16311 }
16312
16313 #[test]
16314 fn rejects_circuit_breaker_max_failures_above_cap() {
16315 // The fail-before-pass-after pin: `1001` is structurally one
16316 // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
16317 // silently passed validate on every pre-gate codebase
16318 // because the typed slot's only check was the zero-floor
16319 // arm. The breaker-no-op vector only surfaced at the runtime
16320 // substrate (Envoy / Cilium L7 outlier-detection overlay)
16321 // far from the source caixa.lisp with no field naming the
16322 // offending policy.
16323 let mut s = three_member_spec();
16324 s.politicas.circuit_breaker = Some(CircuitBreaker {
16325 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16326 window: Duration::from_secs(60),
16327 });
16328 assert_eq!(
16329 s.validate().unwrap_err(),
16330 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16331 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16332 }
16333 );
16334 }
16335
16336 #[test]
16337 fn rejects_circuit_breaker_max_failures_far_above_cap() {
16338 // The `u32::MAX` worst case — the four-billion-failure
16339 // threshold a typo (`(:max-failures 4294967295)`) or a
16340 // struct-literal copy-paste lands in the slot. Pin the cap
16341 // arm's coverage explicitly across the full `u32` overflow
16342 // so a future relaxation that drops the upper bound surfaces
16343 // here.
16344 let mut s = three_member_spec();
16345 s.politicas.circuit_breaker = Some(CircuitBreaker {
16346 max_failures: u32::MAX,
16347 window: Duration::from_secs(60),
16348 });
16349 assert_eq!(
16350 s.validate().unwrap_err(),
16351 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16352 max_failures: u32::MAX,
16353 }
16354 );
16355 }
16356
16357 #[test]
16358 fn accepts_circuit_breaker_max_failures_at_cap() {
16359 // The boundary value — exactly
16360 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
16361 // cap is inclusive on the top edge, matching the
16362 // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16363 // discipline on the sibling capped axes. Pin the boundary
16364 // explicitly so a future off-by-one tightening
16365 // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
16366 // surfaces here as a test failure rather than a silent
16367 // contract narrowing.
16368 let mut s = three_member_spec();
16369 s.politicas.circuit_breaker = Some(CircuitBreaker {
16370 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
16371 window: Duration::from_secs(60),
16372 });
16373 s.validate()
16374 .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
16375 }
16376
16377 #[test]
16378 fn accepts_circuit_breaker_max_failures_typical_values() {
16379 // The documented production-playbook band positive-control
16380 // sweep — every value Hystrix / Istio / Envoy / Polly /
16381 // Resilience4j recommend (5..=50) must pass, plus a sweep
16382 // through the hyperscale band (100, 500, 1000) the cap
16383 // accepts. Pin the inclusive validated set explicitly so a
16384 // future tightening of the ceiling surfaces here.
16385 for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
16386 let mut s = three_member_spec();
16387 s.politicas.circuit_breaker = Some(CircuitBreaker {
16388 max_failures: n,
16389 window: Duration::from_secs(60),
16390 });
16391 s.validate()
16392 .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
16393 }
16394 }
16395
16396 #[test]
16397 fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
16398 // The cross-arm ordering pin: `0` is structurally outside
16399 // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
16400 // (cap), but the zero-floor diagnostic is the more
16401 // self-locating one (it directly names the omit-axis
16402 // remediation), so the validate gate must fire on zero
16403 // first. Same shape every other zero-then-shape ordering on
16404 // this surface uses
16405 // ([`AplicacaoError::PolicyRetriesZero`] then
16406 // [`AplicacaoError::PolicyRetriesExceedsCap`];
16407 // [`AplicacaoError::PolicyTimeoutZero`] then
16408 // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
16409 let mut s = three_member_spec();
16410 s.politicas.circuit_breaker = Some(CircuitBreaker {
16411 max_failures: 0,
16412 window: Duration::from_secs(60),
16413 });
16414 assert_eq!(
16415 s.validate().unwrap_err(),
16416 AplicacaoError::PolicyBreakerZeroFailures,
16417 "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16418 );
16419 }
16420
16421 #[test]
16422 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
16423 // The cross-arm ordering pin between the cap and the
16424 // sibling `:window` gates (zero-window, canonical-window).
16425 // A breaker carrying both an over-cap `max_failures` AND a
16426 // structurally invalid window (zero, sub-ms) must surface
16427 // the cap diagnostic first — the cap arm is wired
16428 // immediately after the zero-failure arm and strictly
16429 // before the window arms, so the offending value the
16430 // diagnostic names matches the order the author would
16431 // discover the gates by reading top-to-bottom through
16432 // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
16433 // future refactor that reorders the arms surfaces here as a
16434 // test failure rather than a silent diagnostic regression.
16435 let mut s = three_member_spec();
16436 s.politicas.circuit_breaker = Some(CircuitBreaker {
16437 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16438 window: Duration::ZERO,
16439 });
16440 assert_eq!(
16441 s.validate().unwrap_err(),
16442 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16443 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16444 },
16445 "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
16446 );
16447 }
16448
16449 #[test]
16450 fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
16451 // The diagnostic-shape pin: the offending `u32` is carried
16452 // verbatim into the
16453 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
16454 // variant so the surfaced error message names the value the
16455 // author wrote (`":politicas :circuit-breaker :max-failures
16456 // (50000) exceeds the mesh-policy ceiling …"`), not just
16457 // the cap. Same self-locating diagnostic shape every other
16458 // typed-cap arm on this surface carries
16459 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
16460 // offending retry count verbatim,
16461 // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16462 // offending byte count verbatim).
16463 let mut s = three_member_spec();
16464 s.politicas.circuit_breaker = Some(CircuitBreaker {
16465 max_failures: 50_000,
16466 window: Duration::from_secs(60),
16467 });
16468 let err = s.validate().unwrap_err();
16469 assert!(
16470 matches!(
16471 err,
16472 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16473 max_failures: 50_000
16474 }
16475 ),
16476 "got {err:?}"
16477 );
16478 let msg = err.to_string();
16479 assert!(
16480 msg.contains("50000"),
16481 ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
16482 );
16483 }
16484
16485 #[test]
16486 fn policy_breaker_max_failures_cap_pins_canonical_value() {
16487 // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
16488 // value at 1000 — an order of magnitude above every
16489 // documented production-playbook recommendation band
16490 // (Hystrix `requestVolumeThreshold` default 20, Istio
16491 // `outlierDetection.consecutive5xxErrors` default 5, Envoy
16492 // `outlier_detection.consecutive_5xx` default 5, Polly /
16493 // Resilience4j typical 5..=50) and below the
16494 // clearly-pathological "effectively no protection" floor
16495 // (10_000, 100_000, u32::MAX). Pinning the literal value
16496 // here surfaces a future drift (a relaxation to 10_000, a
16497 // tightening to 100) as a deliberate test edit, not a
16498 // silent contract narrowing.
16499 assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
16500 }
16501
16502 #[test]
16503 fn rejects_circuit_breaker_zero_window() {
16504 let mut s = three_member_spec();
16505 s.politicas.circuit_breaker = Some(CircuitBreaker {
16506 max_failures: 5,
16507 window: Duration::ZERO,
16508 });
16509 assert_eq!(
16510 s.validate().unwrap_err(),
16511 AplicacaoError::PolicyBreakerZeroWindow
16512 );
16513 }
16514
16515 #[test]
16516 fn rejects_zero_rate_limit() {
16517 let mut s = three_member_spec();
16518 s.politicas.rate_limit = Some(RateLimit {
16519 rate: 0,
16520 window: Duration::from_secs(1),
16521 });
16522 assert_eq!(
16523 s.validate().unwrap_err(),
16524 AplicacaoError::PolicyRateLimitZero
16525 );
16526 }
16527
16528 #[test]
16529 fn rejects_rate_limit_zero_window() {
16530 // `RateLimit { rate: 100, window: Duration::ZERO }` is
16531 // constructible programmatically (the typed `Duration` field
16532 // imposes no nonzero invariant) but renders through
16533 // `rate_limit_codec::render` as `"100/0s"` — a fragment the
16534 // codec's `parse` rejects as `unknown rate-limit window unit
16535 // "0s"`. Until this validate-time gate landed the typed slot
16536 // accepted the value silently and the round-trip break only
16537 // surfaced at deserialize time (potentially in a downstream
16538 // consumer that never re-validates). Pin the rejection at
16539 // `AplicacaoSpec::validate` so the typed slot's valid set
16540 // matches the codec's round-trippable set structurally.
16541 let mut s = three_member_spec();
16542 s.politicas.rate_limit = Some(RateLimit {
16543 rate: 100,
16544 window: Duration::ZERO,
16545 });
16546 assert_eq!(
16547 s.validate().unwrap_err(),
16548 AplicacaoError::PolicyRateLimitWindowNotCanonical {
16549 window: Duration::ZERO
16550 }
16551 );
16552 }
16553
16554 #[test]
16555 fn rejects_rate_limit_arbitrary_seconds_window() {
16556 // 45 seconds is a valid `Duration` but not one of the three
16557 // canonical rate-limit windows the codec round-trips
16558 // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
16559 // refuses on round-trip — same round-trip-break shape the
16560 // zero-window arm above pins, with a non-zero magnitude to
16561 // guard against a future "reject only zero" half-measure.
16562 let mut s = three_member_spec();
16563 let window = Duration::from_secs(45);
16564 s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
16565 assert_eq!(
16566 s.validate().unwrap_err(),
16567 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16568 );
16569 }
16570
16571 #[test]
16572 fn rejects_rate_limit_two_minute_window() {
16573 // 120 seconds = 2 minutes is a "looks-canonical" but
16574 // not-canonical window: it's a clean integer multiple of the
16575 // minute unit, but the codec only round-trips the
16576 // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
16577 // A `Duration::from_secs(120)` window renders as `"100/120s"`
16578 // which the parser rejects. Pinning this case rules out a
16579 // future "accept any clean multiple of s/m/h" relaxation
16580 // that would silently break the codec contract.
16581 let mut s = three_member_spec();
16582 let window = Duration::from_secs(120);
16583 s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
16584 assert_eq!(
16585 s.validate().unwrap_err(),
16586 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16587 );
16588 }
16589
16590 #[test]
16591 fn rejects_rate_limit_subsecond_window() {
16592 // A sub-second window (e.g. 500ms) is a valid `Duration` but
16593 // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
16594 // Pin the rejection so a future relaxation can't silently
16595 // admit fractional-second windows that the codec can't
16596 // round-trip.
16597 let mut s = three_member_spec();
16598 let window = Duration::from_millis(500);
16599 s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
16600 assert_eq!(
16601 s.validate().unwrap_err(),
16602 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16603 );
16604 }
16605
16606 #[test]
16607 fn rejects_policy_rate_limit_above_cap() {
16608 // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
16609 // is structurally one past the cap and silently passed
16610 // validate on every pre-gate codebase because the typed slot's
16611 // only `rate` check was the zero-floor arm. The no-op-limiter
16612 // shape only surfaced at the runtime substrate (Envoy's
16613 // `local_rate_limit.token_bucket.max_tokens`, the future
16614 // Cilium L7 rate-limit overlay) far from the source caixa.lisp
16615 // with no field naming the offending policy.
16616 let mut s = three_member_spec();
16617 s.politicas.rate_limit = Some(RateLimit {
16618 rate: POLICY_RATE_LIMIT_MAX + 1,
16619 window: Duration::from_secs(1),
16620 });
16621 assert_eq!(
16622 s.validate().unwrap_err(),
16623 AplicacaoError::PolicyRateLimitExceedsCap {
16624 rate: POLICY_RATE_LIMIT_MAX + 1
16625 }
16626 );
16627 }
16628
16629 #[test]
16630 fn rejects_policy_rate_limit_far_above_cap() {
16631 // The `u32::MAX` worst case — the four-billion-token rate-limit
16632 // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
16633 // copy-paste lands in the slot. Pin the cap arm's coverage
16634 // explicitly across the full `u32` overflow so a future
16635 // relaxation that drops the upper bound surfaces here. Peer to
16636 // `rejects_policy_retries_far_above_cap` on the sibling
16637 // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
16638 // on the sibling `:max-failures` axis.
16639 let mut s = three_member_spec();
16640 s.politicas.rate_limit = Some(RateLimit {
16641 rate: u32::MAX,
16642 window: Duration::from_secs(1),
16643 });
16644 assert_eq!(
16645 s.validate().unwrap_err(),
16646 AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
16647 );
16648 }
16649
16650 #[test]
16651 fn accepts_policy_rate_limit_at_cap() {
16652 // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
16653 // must validate. The cap is inclusive on the top edge, matching
16654 // every other typed upper bound in this crate
16655 // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
16656 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
16657 // across all three canonical windows so a future off-by-one
16658 // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
16659 // window-conditional cap surfaces here as a test failure rather
16660 // than a silent contract narrowing.
16661 for secs in [1u64, 60, 3600] {
16662 let mut s = three_member_spec();
16663 s.politicas.rate_limit = Some(RateLimit {
16664 rate: POLICY_RATE_LIMIT_MAX,
16665 window: Duration::from_secs(secs),
16666 });
16667 s.validate().unwrap_or_else(|e| {
16668 panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
16669 });
16670 }
16671 }
16672
16673 #[test]
16674 fn accepts_policy_rate_limit_typical_values() {
16675 // The documented production-playbook recommendation band —
16676 // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
16677 // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
16678 // Enterprise ~1M per-hour. Every value in the validated set
16679 // must pass; pin the band explicitly so a future tightening
16680 // surfaces here.
16681 for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
16682 for secs in [1u64, 60, 3600] {
16683 let mut s = three_member_spec();
16684 s.politicas.rate_limit = Some(RateLimit {
16685 rate,
16686 window: Duration::from_secs(secs),
16687 });
16688 s.validate().unwrap_or_else(|e| {
16689 panic!("rate={rate} window={secs}s must validate; got {e:?}")
16690 });
16691 }
16692 }
16693 }
16694
16695 #[test]
16696 fn policy_rate_limit_zero_takes_precedence_over_cap() {
16697 // The cross-arm ordering pin: `rate == 0` is structurally
16698 // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
16699 // (cap), but the zero-floor diagnostic is the more
16700 // self-locating one (it directly names the omit-axis
16701 // remediation). Pin the order so a future refactor that
16702 // reorders the arms surfaces here as a test failure rather
16703 // than a silent diagnostic regression. Same shape every other
16704 // zero-then-cap ordering on this surface uses
16705 // ([`AplicacaoError::PolicyRetriesZero`] then
16706 // [`AplicacaoError::PolicyRetriesExceedsCap`];
16707 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
16708 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
16709 let mut s = three_member_spec();
16710 s.politicas.rate_limit = Some(RateLimit {
16711 rate: 0,
16712 window: Duration::from_secs(1),
16713 });
16714 assert_eq!(
16715 s.validate().unwrap_err(),
16716 AplicacaoError::PolicyRateLimitZero,
16717 "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16718 );
16719 }
16720
16721 #[test]
16722 fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
16723 // Two-axis-bad pin: rate above cap *and* window non-canonical.
16724 // The validate gate must fire on the rate cap first — the
16725 // amplification-shape (no-op limiter) diagnostic is the more
16726 // fundamental one; the window-canonical diagnostic is the
16727 // narrower codec-round-trip shape. Pin the ordering so a future
16728 // refactor that reorders the rate-then-window check arms
16729 // surfaces here as a test failure rather than a silent
16730 // diagnostic regression.
16731 let mut s = three_member_spec();
16732 s.politicas.rate_limit = Some(RateLimit {
16733 rate: POLICY_RATE_LIMIT_MAX + 1,
16734 window: Duration::from_secs(45),
16735 });
16736 assert_eq!(
16737 s.validate().unwrap_err(),
16738 AplicacaoError::PolicyRateLimitExceedsCap {
16739 rate: POLICY_RATE_LIMIT_MAX + 1
16740 },
16741 "above-cap rate must surface the cap diagnostic, not the window diagnostic"
16742 );
16743 }
16744
16745 #[test]
16746 fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
16747 // The diagnostic-shape pin: the offending `u32` is carried
16748 // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
16749 // variant so the surfaced error message names the value the
16750 // author wrote (`":politicas :rate-limit rate (5000000) exceeds
16751 // the mesh-policy ceiling …"`), not just the cap. Same
16752 // self-locating diagnostic shape every other typed-cap arm on
16753 // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
16754 // carries the offending retries count verbatim,
16755 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
16756 // the offending failure count verbatim).
16757 let mut s = three_member_spec();
16758 s.politicas.rate_limit = Some(RateLimit {
16759 rate: 5_000_000,
16760 window: Duration::from_secs(1),
16761 });
16762 let err = s.validate().unwrap_err();
16763 assert!(
16764 matches!(
16765 err,
16766 AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
16767 ),
16768 "got {err:?}"
16769 );
16770 let msg = err.to_string();
16771 assert!(
16772 msg.contains("5000000"),
16773 ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
16774 );
16775 }
16776
16777 #[test]
16778 fn policy_rate_limit_cap_pins_canonical_value() {
16779 // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
16780 // 1_000_000 — two-to-three orders of magnitude above every
16781 // documented production-playbook recommendation band (Envoy /
16782 // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
16783 // Gateway 10_000..=100_000 per-minute) and below the
16784 // clearly-pathological "paste-from-binary blob" floor
16785 // (100_000_000, u32::MAX). Pinning the literal value here
16786 // surfaces a future drift (a relaxation to 10_000_000, a
16787 // tightening to 100_000) as a deliberate test edit, not a
16788 // silent contract narrowing.
16789 assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
16790 }
16791
16792 #[test]
16793 fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
16794 // Both axes are invalid here: rate == 0 *and* window is
16795 // non-canonical. The validate gate must fire on rate first
16796 // (matching the existing `rejects_zero_rate_limit` ordering),
16797 // so the existing diagnostic continues to lead with the
16798 // simpler "zero rate" framing. Pinning the order of checks
16799 // so a future refactor that reorders the arms surfaces here
16800 // as a test failure rather than a silent diagnostic
16801 // regression.
16802 let mut s = three_member_spec();
16803 s.politicas.rate_limit = Some(RateLimit {
16804 rate: 0,
16805 window: Duration::from_secs(45),
16806 });
16807 assert_eq!(
16808 s.validate().unwrap_err(),
16809 AplicacaoError::PolicyRateLimitZero
16810 );
16811 }
16812
16813 #[test]
16814 fn rate_limit_canonical_windows_validate() {
16815 // The three canonical windows the codec round-trips
16816 // losslessly — 1s / 60s / 3600s — must all pass `validate()`
16817 // unchanged. Pin the full canonical set as a positive case
16818 // (the existing `rate_limit_round_trip_seconds` /
16819 // `rate_limit_round_trip_minutes` tests pin the
16820 // serialize-then-deserialize property at the codec layer; this
16821 // test pins the validate-side complement so a future tightening
16822 // of the canonical set — e.g. dropping `:hour` — surfaces here
16823 // as a test failure rather than a silent contract narrowing).
16824 for secs in [1u64, 60, 3600] {
16825 let mut s = three_member_spec();
16826 s.politicas.rate_limit = Some(RateLimit {
16827 rate: 100,
16828 window: Duration::from_secs(secs),
16829 });
16830 s.validate().expect("canonical window must validate");
16831 }
16832 }
16833
16834 #[test]
16835 fn rate_limit_validated_value_round_trips_through_codec() {
16836 // The structural property the validate gate enforces:
16837 // every `RateLimit` past `AplicacaoSpec::validate` round-trips
16838 // losslessly through the `rate_limit_codec` (serialize → string
16839 // → deserialize → equal value). Pin this end-to-end so a future
16840 // change to either side (the validate gate's accepted window
16841 // set, the codec's parse/render unit set) that breaks the
16842 // alignment surfaces here. The previous-state shape (typed
16843 // slot accepts arbitrary `Duration`, codec only round-trips
16844 // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
16845 // window — the validate gate now forecloses that.
16846 for secs in [1u64, 60, 3600] {
16847 let mut s = three_member_spec();
16848 s.politicas.rate_limit = Some(RateLimit {
16849 rate: 250,
16850 window: Duration::from_secs(secs),
16851 });
16852 s.validate().unwrap();
16853 let json = serde_json::to_string(&s.politicas).unwrap();
16854 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16855 assert_eq!(
16856 back.rate_limit, s.politicas.rate_limit,
16857 "every validated :rate-limit must round-trip losslessly through the codec"
16858 );
16859 }
16860 }
16861
16862 #[test]
16863 fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
16864 // The hour-window canonical form (`"<n>/h"`) was missing from
16865 // the prior `rate_limit_round_trip_seconds` / `_minutes` test
16866 // pair. Now that the validate gate pins 3600s as part of the
16867 // canonical set, pin its serialize-side render shape too so
16868 // the third leg of the s/m/h tripod is explicitly tested.
16869 let policy = MeshPolicy {
16870 rate_limit: Some(RateLimit {
16871 rate: 10000,
16872 window: Duration::from_secs(3600),
16873 }),
16874 ..Default::default()
16875 };
16876 let json = serde_json::to_string(&policy).unwrap();
16877 assert!(
16878 json.contains("\"10000/h\""),
16879 "hour-window canonical form must render with `h` suffix (got: {json})"
16880 );
16881 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16882 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
16883 }
16884
16885 #[test]
16886 fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
16887 // Pin the substrate-primitive [`RateLimit::canonical_unit`]
16888 // typed accessor's accepted-window set against the codec's
16889 // accepted set explicitly. A future addition to the codec
16890 // (e.g. accepting `:day`/`:week` as authoring units) must be
16891 // accompanied by a parallel addition here, and a regression
16892 // that drops one of the three canonical units from either
16893 // side surfaces as a test failure. The accessor is the
16894 // single source of truth for the canonical-window set —
16895 // [`AplicacaoSpec::validate_politicas`]'s canonical-window
16896 // gate and [`rate_limit_codec::render`]'s canonical arm both
16897 // read through it — this test enshrines that its
16898 // `Duration → Option<RateLimitUnit>` projection matches the
16899 // codec's parse / render arms' accepted-window set exactly.
16900 //
16901 // Predecessor: this pin previously read the module-private
16902 // free helper `is_canonical_rate_limit_window` — a delegate
16903 // that composed [`RateLimitUnit::from_window`] with `.is_some()`
16904 // — but the helper had no production consumers left after the
16905 // validate-gate migration onto [`RateLimit::canonical_unit`]
16906 // and was deleted; the closed-set arm-window bijection now
16907 // lives on exactly one typed dispatch on the substrate
16908 // primitive.
16909 let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
16910 RateLimit { rate: 1, window }.canonical_unit()
16911 };
16912 assert!(canonical_unit(Duration::from_secs(1)).is_some());
16913 assert!(canonical_unit(Duration::from_secs(60)).is_some());
16914 assert!(canonical_unit(Duration::from_secs(3600)).is_some());
16915 // Non-canonical windows the accessor rejects.
16916 assert!(canonical_unit(Duration::ZERO).is_none());
16917 assert!(canonical_unit(Duration::from_secs(2)).is_none());
16918 assert!(canonical_unit(Duration::from_secs(30)).is_none());
16919 assert!(canonical_unit(Duration::from_secs(120)).is_none());
16920 assert!(canonical_unit(Duration::from_secs(86400)).is_none());
16921 // Sub-second windows: even `Duration::from_millis(1000)` is
16922 // exactly 1s and accepted; `Duration::from_millis(500)` is
16923 // sub-second and rejected.
16924 assert!(canonical_unit(Duration::from_millis(1000)).is_some());
16925 assert!(canonical_unit(Duration::from_millis(500)).is_none());
16926 assert!(canonical_unit(Duration::from_millis(1500)).is_none());
16927 }
16928
16929 #[test]
16930 fn rate_limit_unit_table_projections_are_mutual_inverses() {
16931 // Bidirection pin against the closed-set typed enum
16932 // [`RateLimitUnit`] arm-table (the canonical
16933 // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
16934 // of the rate-limit unit surface reads from). The two
16935 // projection directions [`RateLimitUnit::from_suffix`] /
16936 // [`RateLimitUnit::window`] (str → Duration, exposed as one
16937 // typed dispatch through [`RateLimitUnit::window_from_suffix`])
16938 // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
16939 // (Duration → str, exposed as one typed dispatch through
16940 // [`RateLimit::canonical_unit`] composed with
16941 // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
16942 // codec's parse arm ([`rate_limit_codec::parse`] via
16943 // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
16944 // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
16945 // and the validate gate ([`AplicacaoSpec::validate_politicas`]
16946 // via [`RateLimit::canonical_unit`]) all key off. A future
16947 // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
16948 // sub-second window) is one variant + one arm per method on the
16949 // closed-set enum; the compiler-enforced exhaustiveness on
16950 // every consumer's `match self` arms picks it up by
16951 // construction. This pin enshrines that both projection
16952 // directions agree on every canonical arm row and neither
16953 // leaks a spurious entry the other doesn't recognize.
16954 //
16955 // Predecessor: this test previously read the two vestigial
16956 // module-private free helpers `rate_limit_window_unit` and
16957 // `rate_limit_window_from_unit` on the `Duration → &str` and
16958 // `&str → Duration` axes; the former was deleted after its
16959 // sole production consumer ([`rate_limit_codec::render`])
16960 // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
16961 // the latter is folded here into the substrate primitive
16962 // [`RateLimitUnit::window_from_suffix`] so both projection
16963 // directions live on the closed-set enum's arm-table.
16964 for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
16965 let window = super::RateLimitUnit::window_from_suffix(unit)
16966 .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
16967 assert_eq!(
16968 window,
16969 Duration::from_secs(secs),
16970 "unit {unit:?} must resolve to {secs}s"
16971 );
16972 let projected_suffix = RateLimit { rate: 1, window }
16973 .canonical_unit()
16974 .map(super::RateLimitUnit::as_suffix);
16975 assert_eq!(
16976 projected_suffix,
16977 Some(unit),
16978 "Duration({secs}s) must render as {unit:?} \
16979 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
16980 );
16981 }
16982 // Non-table units yield None on the `unit → Duration`
16983 // projection — a future `"d"` addition to the table would
16984 // flip this arm; today it pins the current three-row table's
16985 // rejection semantics.
16986 assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
16987 assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
16988 assert!(super::RateLimitUnit::window_from_suffix("").is_none());
16989 // Non-table Durations yield None on the `Duration → unit`
16990 // projection — pins that the two projections agree on the
16991 // "not in the table" semantic too, so a drift where the
16992 // parse-side accepts a value the render-side can't emit is
16993 // a build error at the two-arm pair, not a silent codec
16994 // round-trip break.
16995 let projected_suffix = |window: Duration| -> Option<&'static str> {
16996 RateLimit { rate: 1, window }
16997 .canonical_unit()
16998 .map(super::RateLimitUnit::as_suffix)
16999 };
17000 assert!(projected_suffix(Duration::from_secs(2)).is_none());
17001 assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
17002 assert!(projected_suffix(Duration::from_millis(1500)).is_none());
17003 }
17004
17005 #[test]
17006 fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
17007 // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
17008 // substrate-primitive `&str → Duration` associated method the
17009 // codec's parse arm ([`rate_limit_codec::parse`]) now routes
17010 // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
17011 // to the same [`Duration`] the two-step composition
17012 // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
17013 // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
17014 // `"MIN"`) must project to [`None`] on both paths. A future
17015 // implementation of `window_from_suffix` that took a shortcut
17016 // through a per-suffix `match` table (bypassing the arm-table's
17017 // `Self::from_suffix` scan and the arm-table's `Self::window`
17018 // dispatch) would silently split the accept-set — the parse
17019 // arm would accept a suffix the enum's arm-table doesn't know,
17020 // or reject a suffix the enum's arm-table does; this pin
17021 // surfaces that drift at caixa-core build time rather than at a
17022 // downstream serde round-trip audit on a live `MeshPolicy`.
17023 //
17024 // Same byte-parity discipline the sibling
17025 // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
17026 // pin carries on the peer `Duration → RateLimitUnit` axis via
17027 // [`RateLimit::canonical_unit`], and the peer
17028 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17029 // carries on the bidirectional arm-table axis — extended here
17030 // onto the fifth (and last unlifted) projection axis on the
17031 // closed-set enum's arm-table.
17032 let composition = |suffix: &str| -> Option<Duration> {
17033 super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
17034 };
17035 for suffix in ["s", "m", "h"] {
17036 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17037 let via_composition = composition(suffix);
17038 assert_eq!(
17039 via_method, via_composition,
17040 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17041 from_suffix({suffix:?}).map(window) — the substrate-primitive \
17042 method must delegate to the arm-table's two typed dispatches, \
17043 not shortcut through a per-suffix match table"
17044 );
17045 assert!(
17046 via_method.is_some(),
17047 "canonical suffix {suffix:?} must resolve to Some(Duration) via \
17048 RateLimitUnit::window_from_suffix"
17049 );
17050 }
17051 for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
17052 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17053 let via_composition = composition(suffix);
17054 assert_eq!(
17055 via_method, via_composition,
17056 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17057 from_suffix({suffix:?}).map(window) on the non-arm rejection \
17058 axis too"
17059 );
17060 assert!(
17061 via_method.is_none(),
17062 "non-arm suffix {suffix:?} must project to None via \
17063 RateLimitUnit::window_from_suffix — a future extension that \
17064 accepted this suffix without a corresponding arm on the enum \
17065 would split the codec's parse-accepted set from the enum's \
17066 arm-table"
17067 );
17068 }
17069 // And the codec's parse arm now reads through this method: a
17070 // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
17071 // the same `Duration` the method returns for its unit, closing
17072 // the two-consumer drift surface (the codec's parse arm and the
17073 // enum's arm-table) with one typed dispatch on the substrate
17074 // primitive.
17075 for suffix in ["s", "m", "h"] {
17076 let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
17077 let mp: MeshPolicy = serde_json::from_str(&wire)
17078 .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
17079 let parsed = mp.rate_limit().expect("rate_limit payload present");
17080 let via_method = super::RateLimitUnit::window_from_suffix(suffix)
17081 .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
17082 assert_eq!(
17083 parsed.window(),
17084 via_method,
17085 "codec parse arm on {wire:?} must resolve the window through \
17086 RateLimitUnit::window_from_suffix, not a divergent path"
17087 );
17088 }
17089 }
17090
17091 #[test]
17092 fn rate_limit_unit_all_enumerates_every_arm_once() {
17093 // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
17094 // enumerate every arm of the closed-set enum exactly once, in
17095 // the canonical shortest-to-longest window order (Second before
17096 // Minute before Hour) — the same order the sibling
17097 // [`crate::supervisor::RestartStrategy`] /
17098 // [`crate::supervisor::RestartPolicy`] /
17099 // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
17100 // typed enums carry (the arm declared first is the arm listed
17101 // first). A future variant addition that extends the enum
17102 // without appending to [`RateLimitUnit::ALL`] leaves the
17103 // exhaustive iteration surface silently short one arm — the
17104 // codec's parse arm would then reject the new suffix even
17105 // though the enum knows it. This pin closes the drift.
17106 assert_eq!(
17107 super::RateLimitUnit::ALL,
17108 &[
17109 super::RateLimitUnit::Second,
17110 super::RateLimitUnit::Minute,
17111 super::RateLimitUnit::Hour,
17112 ],
17113 "RateLimitUnit::ALL must enumerate every arm exactly once, \
17114 in canonical shortest-to-longest window order"
17115 );
17116 }
17117
17118 #[test]
17119 fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
17120 // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
17121 // every arm's [`RateLimitUnit::as_suffix`] output must parse
17122 // back through [`RateLimitUnit::from_suffix`] to the same
17123 // variant. A future arm addition that lands `as_suffix` but
17124 // forgets `from_suffix` (`from_suffix` iterates
17125 // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
17126 // is the load-bearing carrier of the round-trip; the sibling
17127 // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
17128 // the `ALL` half) trips here at caixa-core build time rather
17129 // than surfacing as a codec round-trip miss (a `render` emit
17130 // that lands a suffix the paired `parse` cannot decode).
17131 for unit in super::RateLimitUnit::ALL {
17132 let suffix = unit.as_suffix();
17133 let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
17134 panic!(
17135 "RateLimitUnit::from_suffix({suffix:?}) must accept every \
17136 RateLimitUnit::as_suffix output — got None for {unit:?}"
17137 )
17138 });
17139 assert_eq!(
17140 parsed, *unit,
17141 "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
17142 must return RateLimitUnit::{unit:?}"
17143 );
17144 }
17145 }
17146
17147 #[test]
17148 fn rate_limit_unit_from_window_and_window_round_trip() {
17149 // Total round-trip pin on the `(from_window, window)` pair:
17150 // every arm's [`RateLimitUnit::window`] output must parse back
17151 // through [`RateLimitUnit::from_window`] to the same variant.
17152 // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
17153 // on the peer `Duration` axis — the two round-trip pins
17154 // together enshrine that both projections of the typed
17155 // canonical-unit bijection are total on the arm-set.
17156 for unit in super::RateLimitUnit::ALL {
17157 let window = unit.window();
17158 let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
17159 panic!(
17160 "RateLimitUnit::from_window({window:?}) must accept every \
17161 RateLimitUnit::window output — got None for {unit:?}"
17162 )
17163 });
17164 assert_eq!(
17165 parsed, *unit,
17166 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17167 must return RateLimitUnit::{unit:?}"
17168 );
17169 }
17170 }
17171
17172 #[test]
17173 fn rate_limit_unit_from_window_accessor_is_const_fn() {
17174 // Fail-before-pass-after pin: witnesses the
17175 // [`RateLimitUnit::from_window`] `const`-eval posture via a
17176 // `const fn` wrapper `from_window_via_const_fn(window: Duration)
17177 // -> Option<RateLimitUnit>` whose body calls
17178 // `RateLimitUnit::from_window(window)`, well-formed only when
17179 // the callee is itself `const fn` (any future downgrade to
17180 // non-`const` fails at caixa-core build time with E0015 `cannot
17181 // call non-const function`, strictly stronger than a runtime
17182 // `assert!`, side-stepping the destructor-in-const restriction
17183 // that blocks direct `const _: Option<RateLimitUnit> =
17184 // RateLimitUnit::from_window(...)` items on `Duration`'s
17185 // carrier). The runtime body sweeps every closed-set
17186 // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
17187 // rejection sample (`Duration::from_millis(500)` sub-second
17188 // residue) and asserts the wrapped and direct dispatches agree
17189 // — a violation means the wrapper stopped compiling under a
17190 // future `const`-posture downgrade, or the reverse resolver's
17191 // arm-set silently split from the peer `Self::window` emitter's
17192 // arm-set. Peer of the sibling
17193 // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
17194 // (152c868) /
17195 // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
17196 // (152c868) /
17197 // [`entrada_port_accessor_is_const_fn`] (bafa004) /
17198 // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
17199 // `const`-eval-surface pins on the peer M2 / M3 substrate-
17200 // primitive `Copy`-return accessor axes, extended onto the
17201 // reverse `Duration → RateLimitUnit` projection axis on the
17202 // M3 mesh-slot rate-limit closed-set typed enum.
17203 const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
17204 super::RateLimitUnit::from_window(window)
17205 }
17206 for unit in super::RateLimitUnit::ALL {
17207 let window = unit.window();
17208 let via_wrapper = from_window_via_const_fn(window);
17209 let direct = super::RateLimitUnit::from_window(window);
17210 assert_eq!(
17211 via_wrapper, direct,
17212 "RateLimitUnit::from_window({window:?}) via const fn \
17213 wrapper must agree with direct dispatch for {unit:?}"
17214 );
17215 assert_eq!(
17216 via_wrapper,
17217 Some(*unit),
17218 "RateLimitUnit::from_window({window:?}) via const fn \
17219 wrapper must return Some({unit:?}) for the peer \
17220 window() output"
17221 );
17222 }
17223 assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
17224 assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
17225 }
17226
17227 #[test]
17228 fn rate_limit_unit_from_window_composes_through_window_accessor() {
17229 // Composition-witness pin on the routing-through-peer discipline:
17230 // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
17231 // through the peer `pub const fn` [`RateLimitUnit::window`]
17232 // canonical-`Duration` projection rather than a hand-authored
17233 // per-arm second-magnitude literal — a future arm-magnitude edit
17234 // on the sibling `window()` accessor (a `Second → 2s` typo, a
17235 // `Hour → 3599s` off-by-one) must therefore reach this reverse
17236 // resolver by construction. A pin that hard-coded the three
17237 // second-magnitudes here would silently split from the peer
17238 // emitter on any such edit; instead, this pin asserts the
17239 // composition invariant `from_window(u.window()) == Some(u)`
17240 // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
17241 // arm — a violation means either the peer `Self::window`
17242 // accessor drifted (breaking every downstream consumer that
17243 // reads through it), or the reverse resolver stopped routing
17244 // through the peer (introducing a hand-authored literal that
17245 // silently disagrees with the emitter). Either failure is a
17246 // caixa-core-build-time surface, not a downstream renderer
17247 // round-trip regression.
17248 //
17249 // Peer of the sibling
17250 // [`crate::render::assert_str_reexport_identity`] discipline on
17251 // the substrate-primitive `&'static str` re-export axis and the
17252 // [`rate_limit_unit_from_window_and_window_round_trip`]
17253 // round-trip pin on the peer projection direction; extends the
17254 // one-canonical-dispatch-per-projection discipline onto the
17255 // reverse-resolver's per-arm probe axis.
17256 for unit in super::RateLimitUnit::ALL {
17257 let window_via_peer = unit.window();
17258 let resolved = super::RateLimitUnit::from_window(window_via_peer);
17259 assert_eq!(
17260 resolved,
17261 Some(*unit),
17262 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17263 must return Some({unit:?}) — the reverse resolver's per-arm \
17264 probes must route through the peer `Self::window` accessor \
17265 so any future arm-magnitude edit reaches both projection \
17266 directions by construction"
17267 );
17268 }
17269 }
17270
17271 #[test]
17272 fn rate_limit_canonical_unit_accessor_is_const_fn() {
17273 // Fail-before-pass-after pin: witnesses the
17274 // [`RateLimit::canonical_unit`] `const`-eval posture via a
17275 // `const fn` wrapper
17276 // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
17277 // whose body calls `rl.canonical_unit()`, well-formed only when
17278 // the callee is itself `const fn` (any future downgrade to
17279 // non-`const` fails at caixa-core build time with E0015 `cannot
17280 // call non-const method`). The runtime body sweeps every
17281 // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
17282 // constructs a typed [`RateLimit`] with the peer `Self::window`
17283 // canonical `Duration`, then asserts both the wrapper and the
17284 // direct dispatch agree and both return `Some(unit)`. Composes
17285 // with the sibling
17286 // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
17287 // typed [`RateLimit`] projection layer's `const`-posture is
17288 // load-bearing on the reverse resolver's `const`-posture, and
17289 // both must migrate together (a downgrade of either surface
17290 // splits the paired `const`-eval-surface pass on the M3
17291 // mesh-slot rate-limit `Duration ↔ Self` bijection).
17292 const fn canonical_unit_via_const_fn(
17293 rl: &super::RateLimit,
17294 ) -> Option<super::RateLimitUnit> {
17295 rl.canonical_unit()
17296 }
17297 for unit in super::RateLimitUnit::ALL {
17298 let rl = super::RateLimit {
17299 rate: 1,
17300 window: unit.window(),
17301 };
17302 let via_wrapper = canonical_unit_via_const_fn(&rl);
17303 let direct = rl.canonical_unit();
17304 assert_eq!(
17305 via_wrapper, direct,
17306 "RateLimit::canonical_unit() via const fn wrapper must \
17307 agree with direct dispatch for {unit:?}"
17308 );
17309 assert_eq!(
17310 via_wrapper,
17311 Some(*unit),
17312 "RateLimit::canonical_unit() via const fn wrapper must \
17313 return Some({unit:?}) for a RateLimit whose window is \
17314 the peer RateLimitUnit::{unit:?}.window() output"
17315 );
17316 }
17317 }
17318
17319 #[test]
17320 fn rate_limit_unit_projections_are_pairwise_distinct() {
17321 // Distinctness pin: [`RateLimitUnit::as_suffix`] and
17322 // [`RateLimitUnit::window`] outputs must be pairwise distinct
17323 // across every arm — an accidental copy-paste flip that
17324 // reroutes one arm's suffix or window to also match another
17325 // silently collapses two arms onto one, so
17326 // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
17327 // (both using `find` on `Self::ALL`) would return whichever
17328 // arm the linear scan lands on first — a match-arm-ordering-
17329 // dependent outcome the closed-set typed-enum shape is meant
17330 // to rule out structurally. Peer of the sibling
17331 // `caixa_kind_wire_consts_are_pairwise_distinct` /
17332 // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
17333 // other closed-set typed-enum discriminator axes.
17334 let all = super::RateLimitUnit::ALL;
17335 for (i, a) in all.iter().enumerate() {
17336 for (j, b) in all.iter().enumerate() {
17337 if i != j {
17338 assert_ne!(
17339 a.as_suffix(),
17340 b.as_suffix(),
17341 "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
17342 must be distinct — a collision silently collapses two \
17343 arms onto one under from_suffix's linear scan"
17344 );
17345 assert_ne!(
17346 a.window(),
17347 b.window(),
17348 "RateLimitUnit::{a:?}.window() and {b:?}.window() \
17349 must be distinct — a collision silently collapses two \
17350 arms onto one under from_window's linear scan"
17351 );
17352 }
17353 }
17354 }
17355 }
17356
17357 #[test]
17358 fn rate_limit_unit_display_routes_through_as_suffix() {
17359 // Route pin: [`std::fmt::Display`] must byte-equal
17360 // [`RateLimitUnit::as_suffix`] on every arm — the single
17361 // source of truth for the canonical suffix. A future
17362 // reimplementation that hand-rolls the arms instead of
17363 // delegating to [`RateLimitUnit::as_suffix`] would silently
17364 // desynchronize `format!("{u}")` from the codec's parse arm
17365 // (which uses `as_suffix` to compare suffixes). Peer of the
17366 // sibling `caixa_kind_display_routes_through_as_str_helper` /
17367 // `placement_strategy_display_routes_through_as_str_helper`
17368 // pins on the peer closed-set typed-enum Display axes.
17369 for unit in super::RateLimitUnit::ALL {
17370 assert_eq!(
17371 unit.to_string(),
17372 unit.as_suffix(),
17373 "RateLimitUnit::{unit:?} Display must route through \
17374 as_suffix (single source of truth: the canonical suffix \
17375 the codec parses and renders)"
17376 );
17377 }
17378 }
17379
17380 #[test]
17381 fn rate_limit_unit_from_window_rejects_non_canonical() {
17382 // Rejection pin on the parser's accept-set: any Duration
17383 // outside the three-arm [`RateLimitUnit::window`] output set
17384 // (sub-second residue, or a second-magnitude outside `{1, 60,
17385 // 3600}`) must return `None`. A future accidental widening of
17386 // the accept-set (rounding down sub-second residue to the
17387 // nearest arm, admitting `Duration::from_secs(30)` as a
17388 // half-minute unit) would silently drift the parser's accept-
17389 // set from the emitter's — a validated slot with a
17390 // non-canonical window would then round-trip through the
17391 // codec to a canonical form the author never wrote.
17392 assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
17393 assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
17394 assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
17395 assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
17396 assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
17397 assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
17398 assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
17399 }
17400
17401 #[test]
17402 fn rate_limit_unit_from_suffix_rejects_unknown() {
17403 // Rejection pin on the suffix parser's accept-set: any string
17404 // outside the three-arm [`RateLimitUnit::as_suffix`] output
17405 // set must return `None`. Peer of the sibling
17406 // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
17407 // the [`crate::CaixaKind`] `from_wire` accept-set.
17408 for bad in [
17409 "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
17410 " s",
17411 ] {
17412 assert!(
17413 super::RateLimitUnit::from_suffix(bad).is_none(),
17414 "RateLimitUnit::from_suffix({bad:?}) must return None — the \
17415 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
17416 outputs"
17417 );
17418 }
17419 }
17420
17421 #[test]
17422 fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
17423 // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
17424 // every canonical `:window` magnitude the validate gate
17425 // accepts must map to the paired [`RateLimitUnit`] arm through
17426 // this accessor. A future validate-gate rebrand that widened
17427 // the accepted-window set without extending [`RateLimitUnit`]
17428 // would silently split the accessor's `Some`-return set from
17429 // the validate gate's accept-set — a slot that satisfies
17430 // validate would land at the accessor with `None`, so a
17431 // consumer past validate that pattern-matches on the returned
17432 // `Some` would silently miss the newly-accepted magnitude.
17433 for (window_secs, expected) in [
17434 (1u64, super::RateLimitUnit::Second),
17435 (60, super::RateLimitUnit::Minute),
17436 (3600, super::RateLimitUnit::Hour),
17437 ] {
17438 let rl = RateLimit {
17439 rate: 100,
17440 window: Duration::from_secs(window_secs),
17441 };
17442 assert_eq!(
17443 rl.canonical_unit(),
17444 Some(expected),
17445 "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
17446 must return Some({expected:?})"
17447 );
17448 }
17449 // Non-canonical windows the validate gate rejects also return
17450 // None here — the accessor is the typed-enum projection of
17451 // the sibling `is_canonical_rate_limit_window` predicate.
17452 let bad = RateLimit {
17453 rate: 100,
17454 window: Duration::from_secs(30),
17455 };
17456 assert!(
17457 bad.canonical_unit().is_none(),
17458 "RateLimit with a non-canonical window must return None from \
17459 canonical_unit — the validate gate rejects the same set"
17460 );
17461 }
17462
17463 #[test]
17464 fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
17465 // Fail-before-pass-after byte-parity pin: for every canonical
17466 // window the [`rate_limit_codec::render`] arm's emitted string
17467 // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
17468 // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
17469 // the vestigial free helper [`rate_limit_window_unit`] (a
17470 // `find_map`-walked `Duration → &'static str` delegate) onto the
17471 // substrate primitive [`RateLimit::canonical_unit`] typed method
17472 // (a closed-set `match self.window` arm on
17473 // [`RateLimitUnit::from_window`], projected through
17474 // [`RateLimitUnit::as_suffix`] via the enum's
17475 // [`std::fmt::Display`] impl). A future re-routing of the render
17476 // arm through a differently-computed unit projection would break
17477 // this pin at build time rather than as a silent per-consumer
17478 // codec round-trip drift far from the substrate primitive edit.
17479 //
17480 // Sibling to the peer
17481 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17482 // on the free-helper axis: that pin locks the two projections
17483 // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
17484 // on the closed-set arm table; this pin locks the codec's render
17485 // arm reads through the typed accessor rather than the free
17486 // helper. Two production consumers of the canonical-unit axis
17487 // now key off one typed dispatch on the substrate primitive.
17488 for (window_secs, unit) in [
17489 (1u64, super::RateLimitUnit::Second),
17490 (60, super::RateLimitUnit::Minute),
17491 (3600, super::RateLimitUnit::Hour),
17492 ] {
17493 let rl = RateLimit {
17494 rate: 42,
17495 window: Duration::from_secs(window_secs),
17496 };
17497 let policy = MeshPolicy {
17498 rate_limit: Some(rl),
17499 ..Default::default()
17500 };
17501 let json = serde_json::to_string(&policy).unwrap();
17502 let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
17503 assert!(
17504 json.contains(&expected),
17505 "rate_limit_codec::render must emit {expected} (via \
17506 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
17507 for a {window_secs}s window; serialized MeshPolicy was: {json}"
17508 );
17509 // And the accessor route resolves to the same typed unit
17510 // the render arm's Display formatting is asked to produce —
17511 // so a future edit that split the two paths (one through
17512 // the accessor, one through a re-introduced free helper)
17513 // trips this pin.
17514 assert_eq!(
17515 rl.canonical_unit(),
17516 Some(unit),
17517 "RateLimit::canonical_unit must return Some({unit:?}) for a \
17518 {window_secs}s window; the codec render arm reads the same \
17519 typed unit through this accessor"
17520 );
17521 }
17522 }
17523
17524 #[test]
17525 fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
17526 // Fail-before-pass-after byte-parity pin on the validate gate's
17527 // canonical-window shape probe: every non-canonical `:window`
17528 // the free-helper predicate [`is_canonical_rate_limit_window`]
17529 // rejects is also rejected by the substrate primitive
17530 // [`RateLimit::canonical_unit`] `.is_none()` route the validate
17531 // gate now reads through, and vice versa on the accepted set
17532 // (the three canonical windows). Locks the migration from the
17533 // free helper onto the substrate primitive: a future re-routing
17534 // of one of the two paths through a differently-computed unit
17535 // projection would silently split the codec's accepted set from
17536 // the validate gate's accepted set — a two-consumer drift the
17537 // codec-round-trip pin
17538 // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
17539 // above closes on the render arm and this pin closes on the
17540 // validate arm.
17541 for canonical_window_secs in [1u64, 60, 3600] {
17542 let mut s = three_member_spec();
17543 let rl = RateLimit {
17544 rate: 100,
17545 window: Duration::from_secs(canonical_window_secs),
17546 };
17547 s.politicas.rate_limit = Some(rl);
17548 assert!(
17549 s.validate().is_ok(),
17550 "canonical {canonical_window_secs}s window must pass \
17551 validate_politicas — the validate gate now reads \
17552 RateLimit::canonical_unit().is_none() and the accessor \
17553 returns Some on every canonical arm"
17554 );
17555 assert!(
17556 rl.canonical_unit().is_some(),
17557 "canonical {canonical_window_secs}s window must resolve to \
17558 Some on RateLimit::canonical_unit — the validate gate reads \
17559 this accessor directly"
17560 );
17561 }
17562 for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
17563 let mut s = three_member_spec();
17564 let rl = RateLimit {
17565 rate: 100,
17566 window: Duration::from_secs(non_canonical_window_secs),
17567 };
17568 s.politicas.rate_limit = Some(rl);
17569 assert_eq!(
17570 s.validate().unwrap_err(),
17571 AplicacaoError::PolicyRateLimitWindowNotCanonical {
17572 window: rl.window(),
17573 },
17574 "non-canonical {non_canonical_window_secs}s window must be \
17575 rejected by validate_politicas — the validate gate now \
17576 keys off RateLimit::canonical_unit().is_none()"
17577 );
17578 assert!(
17579 rl.canonical_unit().is_none(),
17580 "non-canonical {non_canonical_window_secs}s window must \
17581 resolve to None on RateLimit::canonical_unit — the two \
17582 paths (the free helper the validate gate previously read \
17583 and the substrate primitive the validate gate now reads) \
17584 must agree on the same rejected set"
17585 );
17586 }
17587 // And the substrate-primitive [`RateLimit::canonical_unit`]
17588 // accessor's accepted-window set matches the codec's parse arm's
17589 // accepted-suffix set on every canonical / non-canonical shape,
17590 // so a future silent drift between the codec's accepted set and
17591 // the validate gate's accepted set is a build error at test time
17592 // (both consumers key off the same closed-set enum's `match self`
17593 // arms). The predecessor free helper `is_canonical_rate_limit_window`
17594 // — a delegate that composed [`RateLimitUnit::from_window`] with
17595 // `.is_some()` — was deleted after this migration; the
17596 // canonical-window set now lives on exactly one typed dispatch
17597 // on the substrate primitive.
17598 for (secs, expected) in [
17599 (1u64, true),
17600 (60, true),
17601 (3600, true),
17602 (2, false),
17603 (30, false),
17604 (86_400, false),
17605 ] {
17606 let window = Duration::from_secs(secs);
17607 let rl = RateLimit { rate: 1, window };
17608 assert_eq!(
17609 rl.canonical_unit().is_some(),
17610 expected,
17611 "RateLimit::canonical_unit().is_some() must agree with the \
17612 codec-accepted canonical-window set on {secs}s"
17613 );
17614 let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
17615 1 => "s",
17616 60 => "m",
17617 3600 => "h",
17618 _ => return,
17619 })
17620 .is_some_and(|d| d == window);
17621 if expected {
17622 assert!(
17623 suffix_from_axis,
17624 "the codec's `&str → Duration` axis \
17625 ({secs}s) must round-trip to the same Duration the \
17626 substrate primitive's accessor returns Some on"
17627 );
17628 }
17629 }
17630 }
17631
17632 #[test]
17633 fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
17634 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
17635 // derive: for each of the three variants, exactly one of the
17636 // generated `is_second` / `is_minute` / `is_hour` predicates
17637 // returns `true` and the other two return `false`. Peer of
17638 // the sibling
17639 // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
17640 // sibling `IsVariant`-derived closed-set typed-enum pins.
17641 let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
17642 (super::RateLimitUnit::Second, [true, false, false]),
17643 (super::RateLimitUnit::Minute, [false, true, false]),
17644 (super::RateLimitUnit::Hour, [false, false, true]),
17645 ];
17646 for (variant, expected) in rows {
17647 let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
17648 assert_eq!(
17649 observed, expected,
17650 "RateLimitUnit::{variant:?} is_* predicates must partition \
17651 the arm set (second, minute, hour); got {observed:?}"
17652 );
17653 }
17654 }
17655
17656 #[test]
17657 fn rejects_policy_timeout_sub_millisecond() {
17658 // A purely sub-millisecond `Duration` (`from_micros(500)` =
17659 // 500_000 ns) is not the zero `Duration` — the `is_zero()`
17660 // arm passes — but `as_millis() == 0`, so the shared codec's
17661 // `render` arm returns the literal `"0s"`, which the
17662 // codec's `parse` arm then deserializes as `Duration::ZERO`
17663 // and the `PolicyTimeoutZero` zero-floor gate would reject
17664 // on re-validate. Pin the rejection at the typed slot's
17665 // canonical-floor gate so the round-trip break surfaces at
17666 // validate time, naming the offending `Duration`, rather
17667 // than at the next serialize → deserialize round-trip far
17668 // from the source `caixa.lisp`.
17669 let mut s = three_member_spec();
17670 let timeout = Duration::from_micros(500);
17671 s.politicas.timeout = Some(timeout);
17672 assert_eq!(
17673 s.validate().unwrap_err(),
17674 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17675 );
17676 }
17677
17678 #[test]
17679 fn rejects_policy_timeout_non_integer_millisecond() {
17680 // A `Duration` with non-integer-millisecond residue
17681 // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
17682 // through the shared codec's `render` arm as `"1ms"` (the
17683 // `as_millis()` floor truncates), which the codec's `parse`
17684 // arm then deserializes as `Duration::from_millis(1)` =
17685 // 1_000_000 ns — silently *different* from the original.
17686 // Pin the rejection so this round-trip break surfaces at
17687 // validate time, where the offending `Duration` is named,
17688 // rather than as a silent value-laundered round-trip on the
17689 // next codec round-trip.
17690 let mut s = three_member_spec();
17691 let timeout = Duration::from_micros(1500);
17692 s.politicas.timeout = Some(timeout);
17693 assert_eq!(
17694 s.validate().unwrap_err(),
17695 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17696 );
17697 }
17698
17699 #[test]
17700 fn accepts_policy_timeout_integer_millisecond_forms() {
17701 // The codec's accepted set — integer multiples of 1ms — is
17702 // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
17703 // `1h` all pass the canonical gate. Pin the canonical-forms
17704 // sweep so a future tightening of the codec's grammar (e.g.
17705 // dropping `:ms`) surfaces here as a test failure rather
17706 // than a silent contract narrowing on the typed slot.
17707 for timeout in [
17708 Duration::from_millis(1),
17709 Duration::from_millis(500),
17710 Duration::from_millis(1500),
17711 Duration::from_secs(30),
17712 Duration::from_secs(120),
17713 Duration::from_secs(3600),
17714 ] {
17715 let mut s = three_member_spec();
17716 s.politicas.timeout = Some(timeout);
17717 s.validate()
17718 .expect("integer-millisecond :timeout must validate");
17719 }
17720 }
17721
17722 #[test]
17723 fn policy_timeout_zero_takes_precedence_over_canonical() {
17724 // `Duration::ZERO` carries `subsec_nanos() == 0` and would
17725 // pass the canonical-millisecond gate; the more self-locating
17726 // `PolicyTimeoutZero` arm (which names the omit-axis
17727 // remediation directly) must fire first. Pin the ordering so
17728 // a future refactor that reorders the arms surfaces here as a
17729 // test failure rather than a silent diagnostic regression.
17730 let mut s = three_member_spec();
17731 s.politicas.timeout = Some(Duration::ZERO);
17732 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
17733 }
17734
17735 #[test]
17736 fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
17737 // The diagnostic envelope carries the offending `Duration`
17738 // verbatim so the author can grep their `caixa.lisp` for
17739 // `:timeout "<value>"` and fix it in one edit. Same
17740 // diagnostic shape every other typed-slot canonical-form
17741 // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
17742 // peer `:rate-limit :window` axis.
17743 let mut s = three_member_spec();
17744 let timeout = Duration::from_nanos(1_000_001);
17745 s.politicas.timeout = Some(timeout);
17746 match s.validate().unwrap_err() {
17747 AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
17748 assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
17749 }
17750 other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
17751 }
17752 }
17753
17754 #[test]
17755 fn rejects_policy_timeout_above_cap() {
17756 // The fail-before-pass-after pin: 3601s = 1h + 1s is
17757 // structurally one canonical-tick past the
17758 // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
17759 // integer-millisecond magnitude the canonical-form arm above
17760 // accepts cleanly, that the codec round-trips losslessly as
17761 // `"3601s"`, and that silently passed validate on every
17762 // pre-gate codebase because the typed slot's only checks were
17763 // the zero-floor and canonical-form arms. The mesh-level
17764 // deadline degenerates only at the runtime substrate (Envoy
17765 // / Cilium L7 timeout overlay) far from the source
17766 // `caixa.lisp` with no field naming the offending policy.
17767 let mut s = three_member_spec();
17768 let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
17769 s.politicas.timeout = Some(timeout);
17770 assert_eq!(
17771 s.validate().unwrap_err(),
17772 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17773 );
17774 }
17775
17776 #[test]
17777 fn rejects_policy_timeout_one_millisecond_above_cap() {
17778 // Boundary case: exactly 1ms past the cap (the granularity
17779 // the canonical-form gate enforces). Catches a future
17780 // "strictly less than" half-measure and pins the diagnostic
17781 // to name the offending `Duration` verbatim. Peer of
17782 // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
17783 // boundary pin on the sibling `:limits :memory` top edge.
17784 let mut s = three_member_spec();
17785 let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
17786 s.politicas.timeout = Some(timeout);
17787 assert_eq!(
17788 s.validate().unwrap_err(),
17789 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17790 );
17791 }
17792
17793 #[test]
17794 fn rejects_policy_timeout_far_above_cap() {
17795 // The "obvious authoring footgun" case: a `(:timeout "24h")`
17796 // or `(:timeout "86400s")` — values the canonical-form arm
17797 // accepts as integer-millisecond magnitudes, the codec
17798 // round-trips losslessly through serde, but the mesh-level
17799 // policy cannot honor (a 24-hour synchronous-`:contratos`
17800 // deadline is operationally indistinguishable from
17801 // omit-the-axis). Until this gate landed validate accepted
17802 // it. Pin both common above-cap values (24h, 7d) so a future
17803 // relaxation that drops the upper bound surfaces here.
17804 for timeout in [
17805 Duration::from_secs(86_400), // 24h
17806 Duration::from_secs(604_800), // 7d
17807 Duration::from_secs(1_000_000), // ~11.5 days
17808 ] {
17809 let mut s = three_member_spec();
17810 s.politicas.timeout = Some(timeout);
17811 assert_eq!(
17812 s.validate().unwrap_err(),
17813 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17814 );
17815 }
17816 }
17817
17818 #[test]
17819 fn accepts_policy_timeout_at_cap() {
17820 // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
17821 // must validate. The cap is inclusive on the top edge,
17822 // matching the [`POLICY_RETRIES_MAX`] /
17823 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
17824 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
17825 // sibling capped axes. Pin the boundary explicitly so a
17826 // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
17827 // instead of `>`) surfaces here as a test failure rather
17828 // than a silent contract narrowing.
17829 let mut s = three_member_spec();
17830 s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
17831 s.validate()
17832 .expect("timeout == POLICY_TIMEOUT_MAX must validate");
17833 }
17834
17835 #[test]
17836 fn accepts_policy_timeout_typical_values() {
17837 // The documented production-playbook band positive-control
17838 // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
17839 // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
17840 // plus a sweep through the long-running-workflow band
17841 // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
17842 // validated set explicitly so a future tightening of the
17843 // ceiling surfaces here as a deliberate test edit, not a
17844 // silent contract narrowing.
17845 for timeout in [
17846 Duration::from_millis(1),
17847 Duration::from_millis(500),
17848 Duration::from_secs(1),
17849 Duration::from_secs(10),
17850 Duration::from_secs(15), // Envoy default
17851 Duration::from_secs(30),
17852 Duration::from_secs(60), // AWS App Mesh typical
17853 Duration::from_secs(300),
17854 Duration::from_secs(900),
17855 Duration::from_secs(1800),
17856 Duration::from_secs(3600), // exactly 1h, the cap
17857 ] {
17858 let mut s = three_member_spec();
17859 s.politicas.timeout = Some(timeout);
17860 s.validate()
17861 .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
17862 }
17863 }
17864
17865 #[test]
17866 fn policy_timeout_zero_takes_precedence_over_cap() {
17867 // The cross-arm ordering pin: `Duration::ZERO` is
17868 // structurally outside both `>= 1ms` (zero-floor) and
17869 // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
17870 // diagnostic is the more self-locating one (it directly
17871 // names the omit-axis remediation), so the validate gate
17872 // must fire on zero first. Same shape every other
17873 // zero-then-shape ordering on this surface uses
17874 // ([`AplicacaoError::PolicyRetriesZero`] then
17875 // [`AplicacaoError::PolicyRetriesExceedsCap`];
17876 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17877 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17878 let mut s = three_member_spec();
17879 s.politicas.timeout = Some(Duration::ZERO);
17880 assert_eq!(
17881 s.validate().unwrap_err(),
17882 AplicacaoError::PolicyTimeoutZero,
17883 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
17884 );
17885 }
17886
17887 #[test]
17888 fn policy_timeout_canonical_takes_precedence_over_cap() {
17889 // The cross-arm ordering pin: a `Duration` that is *both*
17890 // sub-millisecond (non-canonical-form) and structurally
17891 // above the cap surfaces the canonical-form diagnostic
17892 // first, because the round-trip-shape break is the more
17893 // fundamental issue (the value can't even round-trip
17894 // through the codec, so the cap diagnostic naming
17895 // `1ms..=1h` would be misleading — there's no integer-ms
17896 // form of the offending value). Pin the order so a future
17897 // refactor that reorders the arms surfaces here as a test
17898 // failure rather than a silent diagnostic regression.
17899 let mut s = three_member_spec();
17900 // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
17901 // *and* total magnitude above the 1h cap.
17902 let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
17903 s.politicas.timeout = Some(timeout);
17904 assert_eq!(
17905 s.validate().unwrap_err(),
17906 AplicacaoError::PolicyTimeoutNotCanonical { timeout },
17907 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
17908 );
17909 }
17910
17911 #[test]
17912 fn policy_timeout_cap_diagnostic_carries_offending_value() {
17913 // The diagnostic-shape pin: the offending `Duration` is
17914 // carried verbatim into the
17915 // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
17916 // surfaced error message names the value the author wrote
17917 // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
17918 // exceeds the mesh-policy ceiling …"`), not just the cap.
17919 // Same self-locating diagnostic shape every other typed-cap
17920 // arm on this surface carries
17921 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
17922 // offending retry count verbatim).
17923 let mut s = three_member_spec();
17924 let timeout = Duration::from_secs(7200); // 2h
17925 s.politicas.timeout = Some(timeout);
17926 let err = s.validate().unwrap_err();
17927 assert!(
17928 matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
17929 "got {err:?}"
17930 );
17931 let msg = err.to_string();
17932 assert!(
17933 msg.contains("7200"),
17934 ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
17935 );
17936 }
17937
17938 #[test]
17939 fn policy_timeout_cap_pins_canonical_value() {
17940 // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
17941 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
17942 // the shared duration codec emits as a clean canonical
17943 // string (`"<n>h"`). Pinning the literal value here surfaces
17944 // a future drift (a relaxation to 24h, a tightening to 5m)
17945 // as a deliberate test edit, not a silent contract
17946 // narrowing. Same shape every other typed-cap value pin on
17947 // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
17948 assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
17949 assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
17950 }
17951
17952 #[test]
17953 fn policy_timeout_cap_value_round_trips_through_codec() {
17954 // The codec round-trip property the cap arm preserves: the
17955 // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
17956 // the shared duration codec — every value at the cap renders
17957 // to a clean canonical string (`"1h"`) and parses back to
17958 // the same `Duration`. Pin this so a future drift between
17959 // the cap constant and the codec's largest emitted unit
17960 // surfaces here. Same shape every other typed boundary pin
17961 // on this surface uses
17962 // (`wasm32_memory_cap_matches_parsed_4_gib`).
17963 let policy = MeshPolicy {
17964 timeout: Some(POLICY_TIMEOUT_MAX),
17965 ..Default::default()
17966 };
17967 let json = serde_json::to_string(&policy).unwrap();
17968 // The codec emits `"1h"` for the canonical 1-hour magnitude.
17969 assert!(
17970 json.contains("\"1h\""),
17971 "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
17972 );
17973 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17974 assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
17975 }
17976
17977 #[test]
17978 fn rejects_circuit_breaker_window_sub_millisecond() {
17979 // Peer of the `:timeout` sub-millisecond arm on the second
17980 // typed-`Duration` `:politicas` axis: a purely sub-ms
17981 // `Duration` (`from_micros(500)`) renders through the shared
17982 // codec as `"0s"`, which the codec parses back to
17983 // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
17984 // zero-floor gate then rejects on re-validate.
17985 let mut s = three_member_spec();
17986 let window = Duration::from_micros(500);
17987 s.politicas.circuit_breaker = Some(CircuitBreaker {
17988 max_failures: 5,
17989 window,
17990 });
17991 assert_eq!(
17992 s.validate().unwrap_err(),
17993 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
17994 );
17995 }
17996
17997 #[test]
17998 fn rejects_circuit_breaker_window_non_integer_millisecond() {
17999 // Peer of the `:timeout` non-integer-ms arm: a `Duration`
18000 // with non-integer-millisecond residue renders through the
18001 // shared codec as the truncated `"<n>ms"` form, parsing back
18002 // to a *different* `Duration` on the next round-trip.
18003 let mut s = three_member_spec();
18004 let window = Duration::from_micros(1500);
18005 s.politicas.circuit_breaker = Some(CircuitBreaker {
18006 max_failures: 5,
18007 window,
18008 });
18009 assert_eq!(
18010 s.validate().unwrap_err(),
18011 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18012 );
18013 }
18014
18015 #[test]
18016 fn accepts_circuit_breaker_window_integer_millisecond_forms() {
18017 // The canonical-forms sweep on the breaker axis: every
18018 // integer-ms multiple the codec round-trips losslessly
18019 // passes the canonical gate.
18020 for window in [
18021 Duration::from_millis(1),
18022 Duration::from_millis(500),
18023 Duration::from_millis(1500),
18024 Duration::from_secs(30),
18025 Duration::from_secs(60),
18026 Duration::from_secs(3600),
18027 ] {
18028 let mut s = three_member_spec();
18029 s.politicas.circuit_breaker = Some(CircuitBreaker {
18030 max_failures: 5,
18031 window,
18032 });
18033 s.validate()
18034 .expect("integer-millisecond :circuit-breaker :window must validate");
18035 }
18036 }
18037
18038 #[test]
18039 fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
18040 // `Duration::ZERO` would pass the canonical-ms gate (the
18041 // sub-ns residue is zero) but must surface the narrower
18042 // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
18043 // remediation.
18044 let mut s = three_member_spec();
18045 s.politicas.circuit_breaker = Some(CircuitBreaker {
18046 max_failures: 5,
18047 window: Duration::ZERO,
18048 });
18049 assert_eq!(
18050 s.validate().unwrap_err(),
18051 AplicacaoError::PolicyBreakerZeroWindow
18052 );
18053 }
18054
18055 #[test]
18056 fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
18057 // Both axes invalid: max_failures == 0 *and* window is
18058 // sub-ms. The validate gate must fire on max_failures first
18059 // (matching the existing ordering pin
18060 // `rejects_circuit_breaker_zero_max_failures` enshrines), so
18061 // the existing diagnostic continues to lead with the simpler
18062 // "zero threshold" framing.
18063 let mut s = three_member_spec();
18064 s.politicas.circuit_breaker = Some(CircuitBreaker {
18065 max_failures: 0,
18066 window: Duration::from_micros(500),
18067 });
18068 assert_eq!(
18069 s.validate().unwrap_err(),
18070 AplicacaoError::PolicyBreakerZeroFailures
18071 );
18072 }
18073
18074 #[test]
18075 fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
18076 let mut s = three_member_spec();
18077 let window = Duration::from_nanos(60_000_000_001);
18078 s.politicas.circuit_breaker = Some(CircuitBreaker {
18079 max_failures: 5,
18080 window,
18081 });
18082 match s.validate().unwrap_err() {
18083 AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
18084 assert_eq!(w, window, "diagnostic must carry the offending Duration");
18085 }
18086 other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
18087 }
18088 }
18089
18090 #[test]
18091 fn rejects_circuit_breaker_window_above_cap() {
18092 // The fail-before-pass-after pin: 3601s = 1h + 1s is
18093 // structurally one canonical-tick past the
18094 // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
18095 // integer-millisecond magnitude the canonical-form arm above
18096 // accepts cleanly, that the codec round-trips losslessly as
18097 // `"3601s"`, and that silently passed validate on every
18098 // pre-gate codebase because the typed slot's only checks were
18099 // the zero-floor and canonical-form arms. The
18100 // rolling-window-to-lifetime-counter degeneration surfaces
18101 // only at the runtime substrate (Envoy's outlier_detection
18102 // interval, the future CiliumClusterwideEnvoyConfig overlay)
18103 // far from the source `caixa.lisp` with no field naming the
18104 // offending policy.
18105 let mut s = three_member_spec();
18106 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18107 s.politicas.circuit_breaker = Some(CircuitBreaker {
18108 max_failures: 5,
18109 window,
18110 });
18111 assert_eq!(
18112 s.validate().unwrap_err(),
18113 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18114 );
18115 }
18116
18117 #[test]
18118 fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
18119 // Boundary case: exactly 1ms past the cap (the granularity the
18120 // canonical-form gate enforces). Catches a future "strictly
18121 // less than" half-measure and pins the diagnostic to name the
18122 // offending `Duration` verbatim. Peer of
18123 // `rejects_policy_timeout_one_millisecond_above_cap` on the
18124 // sibling duration-typed `:politicas :timeout` top edge.
18125 let mut s = three_member_spec();
18126 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
18127 s.politicas.circuit_breaker = Some(CircuitBreaker {
18128 max_failures: 5,
18129 window,
18130 });
18131 assert_eq!(
18132 s.validate().unwrap_err(),
18133 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18134 );
18135 }
18136
18137 #[test]
18138 fn rejects_circuit_breaker_window_far_above_cap() {
18139 // The "obvious authoring footgun" case: a `(:window "24h")` or
18140 // `(:window "86400s")` — values the canonical-form arm
18141 // accepts as integer-millisecond magnitudes, the codec
18142 // round-trips losslessly through serde, but the
18143 // rolling-window breaker contract cannot honor (a 24-hour
18144 // rolling failure window is operationally a lifetime counter).
18145 // Until this gate landed validate accepted it. Pin both common
18146 // above-cap values (24h, 7d) so a future relaxation that
18147 // drops the upper bound surfaces here.
18148 for window in [
18149 Duration::from_secs(86_400), // 24h
18150 Duration::from_secs(604_800), // 7d
18151 Duration::from_secs(1_000_000), // ~11.5 days
18152 ] {
18153 let mut s = three_member_spec();
18154 s.politicas.circuit_breaker = Some(CircuitBreaker {
18155 max_failures: 5,
18156 window,
18157 });
18158 assert_eq!(
18159 s.validate().unwrap_err(),
18160 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18161 );
18162 }
18163 }
18164
18165 #[test]
18166 fn accepts_circuit_breaker_window_at_cap() {
18167 // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
18168 // (1h) — must validate. The cap is inclusive on the top edge,
18169 // matching the [`POLICY_TIMEOUT_MAX`] /
18170 // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
18171 // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18172 // sibling capped axes. Pin the boundary explicitly so a
18173 // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
18174 // instead of `>`) surfaces here as a test failure rather than
18175 // a silent contract narrowing.
18176 let mut s = three_member_spec();
18177 s.politicas.circuit_breaker = Some(CircuitBreaker {
18178 max_failures: 5,
18179 window: POLICY_BREAKER_WINDOW_MAX,
18180 });
18181 s.validate()
18182 .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
18183 }
18184
18185 #[test]
18186 fn accepts_circuit_breaker_window_typical_values() {
18187 // The documented production-playbook band positive-control
18188 // sweep — every value Hystrix / resilience4j / Istio / Envoy
18189 // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
18190 // through the long-tail failure-detection band (15m, 30m, 1h)
18191 // the cap accepts. Pin the inclusive validated set explicitly
18192 // so a future tightening of the ceiling surfaces here as a
18193 // deliberate test edit, not a silent contract narrowing.
18194 for window in [
18195 Duration::from_millis(1),
18196 Duration::from_millis(500),
18197 Duration::from_secs(1),
18198 Duration::from_secs(10), // Hystrix / Istio / Envoy default
18199 Duration::from_secs(30),
18200 Duration::from_secs(60), // resilience4j typical
18201 Duration::from_secs(300), // AWS App Mesh typical
18202 Duration::from_secs(900),
18203 Duration::from_secs(1800),
18204 Duration::from_secs(3600), // exactly 1h, the cap
18205 ] {
18206 let mut s = three_member_spec();
18207 s.politicas.circuit_breaker = Some(CircuitBreaker {
18208 max_failures: 5,
18209 window,
18210 });
18211 s.validate()
18212 .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
18213 }
18214 }
18215
18216 #[test]
18217 fn circuit_breaker_zero_window_takes_precedence_over_cap() {
18218 // The cross-arm ordering pin: `Duration::ZERO` is structurally
18219 // outside both `>= 1ms` (zero-floor) and
18220 // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
18221 // diagnostic is the more self-locating one (it directly names
18222 // the omit-axis remediation), so the validate gate must fire
18223 // on zero first. Same shape every other zero-then-cap
18224 // ordering on this surface uses
18225 // ([`AplicacaoError::PolicyTimeoutZero`] then
18226 // [`AplicacaoError::PolicyTimeoutExceedsCap`];
18227 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18228 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18229 let mut s = three_member_spec();
18230 s.politicas.circuit_breaker = Some(CircuitBreaker {
18231 max_failures: 5,
18232 window: Duration::ZERO,
18233 });
18234 assert_eq!(
18235 s.validate().unwrap_err(),
18236 AplicacaoError::PolicyBreakerZeroWindow,
18237 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18238 );
18239 }
18240
18241 #[test]
18242 fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
18243 // The cross-arm ordering pin: a `Duration` that is *both*
18244 // sub-millisecond (non-canonical-form) and structurally above
18245 // the cap surfaces the canonical-form diagnostic first,
18246 // because the round-trip-shape break is the more fundamental
18247 // issue (the value can't even round-trip through the codec, so
18248 // the cap diagnostic naming `1ms..=1h` would be misleading —
18249 // there's no integer-ms form of the offending value). Pin the
18250 // order so a future refactor that reorders the arms surfaces
18251 // here as a test failure rather than a silent diagnostic
18252 // regression. Peer of
18253 // `policy_timeout_canonical_takes_precedence_over_cap` on the
18254 // sibling duration-typed `:politicas :timeout` axis.
18255 let mut s = three_member_spec();
18256 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
18257 s.politicas.circuit_breaker = Some(CircuitBreaker {
18258 max_failures: 5,
18259 window,
18260 });
18261 assert_eq!(
18262 s.validate().unwrap_err(),
18263 AplicacaoError::PolicyBreakerWindowNotCanonical { window },
18264 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18265 );
18266 }
18267
18268 #[test]
18269 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
18270 // The cross-arm ordering pin between the two breaker axes: a
18271 // `CircuitBreaker` whose *both* `max_failures` is above its
18272 // cap *and* `window` is above its cap surfaces the
18273 // max-failures cap diagnostic first, because the validate
18274 // gate visits the failures arm before the window arm. Pin the
18275 // order so a future refactor that reorders the breaker arms
18276 // surfaces here.
18277 let mut s = three_member_spec();
18278 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18279 s.politicas.circuit_breaker = Some(CircuitBreaker {
18280 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18281 window,
18282 });
18283 assert_eq!(
18284 s.validate().unwrap_err(),
18285 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18286 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
18287 },
18288 "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
18289 );
18290 }
18291
18292 #[test]
18293 fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
18294 // The diagnostic-shape pin: the offending `Duration` is
18295 // carried verbatim into the
18296 // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
18297 // the surfaced error message names the value the author wrote
18298 // (`":politicas :circuit-breaker :window (Duration { secs:
18299 // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
18300 // just the cap. Same self-locating diagnostic shape every
18301 // other typed-cap arm on this surface carries
18302 // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
18303 // offending `Duration` verbatim).
18304 let mut s = three_member_spec();
18305 let window = Duration::from_secs(7200); // 2h
18306 s.politicas.circuit_breaker = Some(CircuitBreaker {
18307 max_failures: 5,
18308 window,
18309 });
18310 let err = s.validate().unwrap_err();
18311 assert!(
18312 matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
18313 "got {err:?}"
18314 );
18315 let msg = err.to_string();
18316 assert!(
18317 msg.contains("7200"),
18318 ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
18319 );
18320 }
18321
18322 #[test]
18323 fn circuit_breaker_window_cap_pins_canonical_value() {
18324 // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
18325 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
18326 // shared duration codec emits as a clean canonical string
18327 // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
18328 // the sibling duration-typed `:politicas :timeout` axis (the
18329 // two duration-typed `:politicas` axes share a uniform top
18330 // edge). Pinning the literal value here surfaces a future
18331 // drift (a relaxation to 24h, a tightening to 5m) as a
18332 // deliberate test edit, not a silent contract narrowing. Same
18333 // shape every other typed-cap value pin on this surface uses
18334 // (`policy_timeout_cap_pins_canonical_value`).
18335 assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
18336 assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
18337 assert_eq!(
18338 POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
18339 "the two duration-typed `:politicas` caps share the same top edge"
18340 );
18341 }
18342
18343 #[test]
18344 fn circuit_breaker_window_cap_value_round_trips_through_codec() {
18345 // The codec round-trip property the cap arm preserves: the
18346 // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
18347 // through the shared duration codec — every value at the cap
18348 // renders to a clean canonical string (`"1h"`) and parses back
18349 // to the same `Duration`. Pin this so a future drift between
18350 // the cap constant and the codec's largest emitted unit
18351 // surfaces here. Same shape every other typed boundary pin on
18352 // this surface uses
18353 // (`policy_timeout_cap_value_round_trips_through_codec`).
18354 let policy = MeshPolicy {
18355 circuit_breaker: Some(CircuitBreaker {
18356 max_failures: 5,
18357 window: POLICY_BREAKER_WINDOW_MAX,
18358 }),
18359 ..Default::default()
18360 };
18361 let json = serde_json::to_string(&policy).unwrap();
18362 // The codec emits `"1h"` for the canonical 1-hour magnitude.
18363 assert!(
18364 json.contains("\"1h\""),
18365 "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
18366 );
18367 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18368 assert_eq!(
18369 back.circuit_breaker.unwrap().window,
18370 POLICY_BREAKER_WINDOW_MAX
18371 );
18372 }
18373
18374 #[test]
18375 fn is_integer_millisecond_duration_predicate_tracks_codec() {
18376 // Pin the predicate's accepted set against the codec's
18377 // accepted set explicitly. The codec parses
18378 // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
18379 // accepted value is an integer-millisecond multiple — so the
18380 // predicate must accept exactly that set. Same shape every
18381 // other predicate-on-the-typed-slot helper carries
18382 // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
18383 // Read directly from the codec-owned predicate — the crate's
18384 // single source of truth every typed-`Duration` axis now routes
18385 // through via
18386 // [`crate::render::require_positive_canonical_bounded_duration`].
18387 use super::supervisor::duration_codec::is_integer_millisecond_duration;
18388 assert!(is_integer_millisecond_duration(Duration::ZERO));
18389 assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
18390 assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
18391 assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
18392 assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
18393 assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
18394 // Non-integer-millisecond residue: rejected.
18395 assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
18396 assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
18397 assert!(!is_integer_millisecond_duration(Duration::from_micros(
18398 1500
18399 )));
18400 assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
18401 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18402 999_999
18403 )));
18404 // The 1-ns-past-1ms boundary: rejected (no longer a clean
18405 // integer-millisecond multiple).
18406 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18407 1_000_001
18408 )));
18409 }
18410
18411 #[test]
18412 fn policy_timeout_validated_value_round_trips_through_codec() {
18413 // The structural property the canonical-ms gate enforces:
18414 // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
18415 // round-trips losslessly through the shared `duration_codec`
18416 // (serialize → string → deserialize → equal value). Pin this
18417 // end-to-end so a future change to either side (the validate
18418 // gate's accepted granularity, the codec's parse/render unit
18419 // set) that breaks the alignment surfaces here. The
18420 // previous-state shape (typed slot accepts arbitrary
18421 // `Duration`, codec only round-trips integer-ms) would fail
18422 // this test for any `Duration::from_micros(1500)` timeout —
18423 // the validate gate now forecloses that.
18424 for timeout in [
18425 Duration::from_millis(1),
18426 Duration::from_millis(1500),
18427 Duration::from_secs(30),
18428 Duration::from_secs(3600),
18429 ] {
18430 let mut s = three_member_spec();
18431 s.politicas.timeout = Some(timeout);
18432 s.validate().unwrap();
18433 let json = serde_json::to_string(&s.politicas).unwrap();
18434 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18435 assert_eq!(
18436 back.timeout, s.politicas.timeout,
18437 "every validated :timeout must round-trip losslessly through the codec"
18438 );
18439 }
18440 }
18441
18442 #[test]
18443 fn circuit_breaker_window_validated_value_round_trips_through_codec() {
18444 // Peer of the `:timeout` round-trip property on the breaker
18445 // axis.
18446 for window in [
18447 Duration::from_millis(1),
18448 Duration::from_millis(1500),
18449 Duration::from_secs(30),
18450 Duration::from_secs(3600),
18451 ] {
18452 let mut s = three_member_spec();
18453 s.politicas.circuit_breaker = Some(CircuitBreaker {
18454 max_failures: 5,
18455 window,
18456 });
18457 s.validate().unwrap();
18458 let json = serde_json::to_string(&s.politicas).unwrap();
18459 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18460 assert_eq!(
18461 back.circuit_breaker.unwrap().window,
18462 window,
18463 "every validated :circuit-breaker :window must round-trip losslessly"
18464 );
18465 }
18466 }
18467
18468 #[test]
18469 fn empty_politicas_validates() {
18470 // Omitting every policy axis is fine — defaults express "no
18471 // policy on this axis", not "policy = 0". The fixture's typical
18472 // values continue to validate; this test pins that
18473 // MeshPolicy::default() is a clean pass through validate().
18474 let mut s = three_member_spec();
18475 s.politicas = MeshPolicy::default();
18476 s.validate().unwrap();
18477 }
18478
18479 #[test]
18480 fn typical_politicas_validates_with_every_axis_set() {
18481 // The full §III.1 example block (timeout + retries + breaker +
18482 // mtls + rate-limit) — every axis nonzero — must remain a
18483 // clean pass.
18484 let mut s = three_member_spec();
18485 s.politicas = MeshPolicy {
18486 timeout: Some(Duration::from_secs(30)),
18487 retries: Some(3),
18488 circuit_breaker: Some(CircuitBreaker {
18489 max_failures: 5,
18490 window: Duration::from_secs(60),
18491 }),
18492 mtls_required: Some(true),
18493 rate_limit: Some(RateLimit {
18494 rate: 100,
18495 window: Duration::from_secs(1),
18496 }),
18497 };
18498 s.validate().unwrap();
18499 }
18500
18501 #[test]
18502 fn rejects_empty_cluster_name() {
18503 let mut s = three_member_spec();
18504 s.placement.clusters = vec!["rio".into(), "".into()];
18505 assert_eq!(
18506 s.validate().unwrap_err(),
18507 AplicacaoError::PlacementClusterEmpty
18508 );
18509 }
18510
18511 #[test]
18512 fn rejects_duplicate_cluster_names() {
18513 let mut s = three_member_spec();
18514 s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
18515 let err = s.validate().unwrap_err();
18516 assert!(
18517 matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
18518 "got {err:?}"
18519 );
18520 }
18521
18522 #[test]
18523 fn rejects_placement_cluster_with_uppercase() {
18524 // The canonical "I copied the cluster's display name verbatim"
18525 // typo — K8s context names are lowercase per DNS-1123 label
18526 // rule, but org docs often round-trip a TitleCase identifier
18527 // (`Rio`, `Mar-East`) from an ADR. Mirrors the
18528 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
18529 // on the peer name axis.
18530 let mut s = three_member_spec();
18531 s.placement.clusters = vec!["Rio".into(), "mar".into()];
18532 let err = s.validate().unwrap_err();
18533 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18534 panic!("expected PlacementClusterInvalid, got other variant");
18535 };
18536 assert_eq!(cluster, "Rio");
18537 assert!(
18538 reason.contains("uppercase"),
18539 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18540 );
18541 assert!(
18542 reason.contains("\"rio\""),
18543 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18544 );
18545 }
18546
18547 #[test]
18548 fn rejects_placement_cluster_with_underscore() {
18549 // The canonical "I'm thinking of an env var / hostname slug"
18550 // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
18551 // schema. K8s context filtering on `my_cluster` silently misses
18552 // the cluster the author intended; the gate moves it to caixa-
18553 // build time. Same shape as `rejects_membro_caixa_with_underscore`
18554 // (3f9d7a0).
18555 let mut s = three_member_spec();
18556 s.placement.clusters = vec!["my_cluster".into()];
18557 let err = s.validate().unwrap_err();
18558 assert!(
18559 matches!(
18560 err,
18561 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18562 if cluster == "my_cluster" && reason.contains('_')
18563 ),
18564 "got {err:?}"
18565 );
18566 }
18567
18568 #[test]
18569 fn rejects_placement_cluster_with_dot() {
18570 // A `:placement :clusters` entry is a single DNS-1123 *label*,
18571 // not a subdomain — even though K8s context names sometimes
18572 // carry a dotted form via kubeconfig conventions, the strictest
18573 // floor among the use sites (DNS-1035 cluster.x-k8s.io
18574 // `metadata.name`, Cilium identity label values) wins. The "I
18575 // want to namespace my cluster names with `.`" intent is
18576 // expressed via `-` (`mar-east`).
18577 let mut s = three_member_spec();
18578 s.placement.clusters = vec!["team.rio".into()];
18579 let err = s.validate().unwrap_err();
18580 assert!(
18581 matches!(
18582 err,
18583 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18584 if cluster == "team.rio" && reason.contains('.')
18585 ),
18586 "got {err:?}"
18587 );
18588 }
18589
18590 #[test]
18591 fn rejects_placement_cluster_with_leading_hyphen() {
18592 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
18593 // with an alphanumeric. The K8s apiserver rejects `-rio`
18594 // outright; the rendered fan-out would emit a `metadata.name:
18595 // "-rio"` that fails admission far from the source caixa.lisp.
18596 let mut s = three_member_spec();
18597 s.placement.clusters = vec!["-rio".into()];
18598 let err = s.validate().unwrap_err();
18599 assert!(
18600 matches!(
18601 err,
18602 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18603 if cluster == "-rio" && reason.contains("start and end")
18604 ),
18605 "got {err:?}"
18606 );
18607 }
18608
18609 #[test]
18610 fn rejects_placement_cluster_with_trailing_hyphen() {
18611 // The symmetric arm of the boundary rule. Pin separately so
18612 // both ends are covered against a future relaxation that only
18613 // checks one boundary (parallel to
18614 // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
18615 let mut s = three_member_spec();
18616 s.placement.clusters = vec!["rio-".into()];
18617 let err = s.validate().unwrap_err();
18618 assert!(
18619 matches!(
18620 err,
18621 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18622 if cluster == "rio-"
18623 ),
18624 "got {err:?}"
18625 );
18626 }
18627
18628 #[test]
18629 fn rejects_placement_cluster_with_unicode() {
18630 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
18631 // before it reaches K8s. The byte-by-byte ASCII validity check
18632 // rejects multi-byte UTF-8 sequences by the first byte that
18633 // fails `[a-z0-9-]`.
18634 let mut s = three_member_spec();
18635 s.placement.clusters = vec!["rió".into()];
18636 let err = s.validate().unwrap_err();
18637 assert!(
18638 matches!(
18639 err,
18640 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18641 if cluster == "rió"
18642 ),
18643 "got {err:?}"
18644 );
18645 }
18646
18647 #[test]
18648 fn rejects_placement_cluster_with_whitespace() {
18649 // Whitespace is the canonical "I pasted from a sketch / doc"
18650 // footgun. The apiserver rejects every cluster `metadata.name`
18651 // value carrying whitespace.
18652 let mut s = three_member_spec();
18653 s.placement.clusters = vec!["rio cluster".into()];
18654 let err = s.validate().unwrap_err();
18655 assert!(
18656 matches!(
18657 err,
18658 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18659 if cluster == "rio cluster"
18660 ),
18661 "got {err:?}"
18662 );
18663 }
18664
18665 #[test]
18666 fn rejects_placement_cluster_too_long() {
18667 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
18668 // pin. The diagnostic names both the cap (63) and the actual
18669 // length so the author can shorten in one edit. Mirrors
18670 // `rejects_membro_caixa_too_long` (3f9d7a0).
18671 let mut s = three_member_spec();
18672 let too_long = "a".repeat(64);
18673 s.placement.clusters = vec![too_long.clone()];
18674 let err = s.validate().unwrap_err();
18675 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18676 panic!("expected PlacementClusterInvalid");
18677 };
18678 assert_eq!(cluster, too_long);
18679 assert!(
18680 reason.contains("63") && reason.contains("64"),
18681 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18682 );
18683 }
18684
18685 #[test]
18686 fn placement_cluster_max_length_validates() {
18687 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
18688 // future tightening (e.g. dropping to 62) surfaces here as a
18689 // regression, mirroring `membro_caixa_max_length_validates`
18690 // (3f9d7a0).
18691 let mut s = three_member_spec();
18692 s.placement.clusters = vec!["a".repeat(63)];
18693 s.validate().unwrap();
18694 }
18695
18696 #[test]
18697 fn accepts_canonical_placement_cluster_forms() {
18698 // The DNS-1123 label shapes a caixa author is realistically
18699 // going to write for cluster names: single-word lowercase
18700 // (`rio`), regional hyphen-joined (`mar-east`), single
18701 // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
18702 // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
18703 // Pin every leg so a future tightening that bans (e.g.) digit-
18704 // start identifiers surfaces here.
18705 for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
18706 let mut s = three_member_spec();
18707 s.placement.clusters = vec![form.into()];
18708 s.validate().unwrap_or_else(|e| {
18709 panic!("canonical cluster form {form:?} must validate, got {e:?}")
18710 });
18711 }
18712 }
18713
18714 #[test]
18715 fn placement_cluster_empty_takes_precedence_over_invalid() {
18716 // Order pin: the existing `PlacementClusterEmpty` diagnostic
18717 // (which doesn't try to parse) fires before the new
18718 // `PlacementClusterInvalid` parse-side diagnostic, so an empty
18719 // `:clusters` entry keeps its narrower error message — the new
18720 // gate would also reject `""`, but the empty-string arm is the
18721 // more self-locating diagnostic. Mirrors the
18722 // `membro_caixa_empty_takes_precedence_over_invalid` pin
18723 // (3f9d7a0).
18724 let mut s = three_member_spec();
18725 s.placement.clusters = vec!["rio".into(), "".into()];
18726 let err = s.validate().unwrap_err();
18727 assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
18728 }
18729
18730 #[test]
18731 fn placement_cluster_invalid_fires_before_duplicate_check() {
18732 // Order pin: a malformed-shape `:clusters` entry surfaces *its
18733 // own* diagnostic, even when a later entry would otherwise
18734 // collapse onto a duplicate name. The per-entry shape gate runs
18735 // inline before the duplicate-key insert, parallel to
18736 // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
18737 let mut s = three_member_spec();
18738 s.placement.clusters = vec!["Rio".into(), "rio".into()];
18739 let err = s.validate().unwrap_err();
18740 assert!(
18741 matches!(
18742 err,
18743 AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
18744 ),
18745 "got {err:?}"
18746 );
18747 }
18748
18749 #[test]
18750 fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
18751 // The diagnostic-shape pin: the error names the offending
18752 // `:clusters` value verbatim so the author can grep their
18753 // caixa.lisp without re-running the build, and carries a
18754 // non-empty `reason` naming the specific violation. Same shape
18755 // every typed-shape gate enshrines
18756 // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
18757 // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
18758 let mut s = three_member_spec();
18759 s.placement.clusters = vec!["BAD_CLUSTER".into()];
18760 let err = s.validate().unwrap_err();
18761 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18762 panic!("expected PlacementClusterInvalid");
18763 };
18764 assert_eq!(cluster, "BAD_CLUSTER");
18765 assert!(
18766 !reason.is_empty(),
18767 "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
18768 );
18769 }
18770
18771 #[test]
18772 fn rejects_sharded_with_empty_clusters() {
18773 // §III.1: Sharded uses :clusters as the shard pool. An empty
18774 // pool means "shard across no clusters" — meaningless, same as
18775 // Replicated with no hosts.
18776 let mut s = three_member_spec();
18777 s.placement.estrategia = PlacementStrategy::Sharded;
18778 s.placement.shard_key = Some("$tenantId".into());
18779 s.placement.clusters = vec![];
18780 assert!(matches!(
18781 s.validate().unwrap_err(),
18782 AplicacaoError::PlacementWithoutClusters {
18783 estrategia: PlacementStrategy::Sharded
18784 }
18785 ));
18786 }
18787
18788 #[test]
18789 fn rejects_sharded_with_empty_shard_key() {
18790 let mut s = three_member_spec();
18791 s.placement.estrategia = PlacementStrategy::Sharded;
18792 s.placement.shard_key = Some("".into());
18793 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
18794 }
18795
18796 #[test]
18797 fn rejects_shard_key_under_replicated_strategy() {
18798 // The fail-before-pass-after pin: a `:placement (:estrategia
18799 // Replicated :shard-key "tenantId")` manifest carries the
18800 // hash-keyed-distribution slot on a strategy that never consumes
18801 // it. Before the gate the typed slot's value silently vanished
18802 // at the renderer layer (caixa-mesh emits `placement.shardKey`
18803 // verbatim regardless of strategy; the Akka-style cluster-
18804 // sharding reconciler keys off `estrategia == Sharded` and
18805 // ignores the slot otherwise), with no diagnostic. Lifting the
18806 // rejection to a build-time gate makes the
18807 // `shard_key.is_some() == matches!(estrategia, Sharded)`
18808 // partition a structural property of every validated
18809 // [`Placement`].
18810 let mut s = three_member_spec();
18811 // The fixture already uses Replicated; just add a shard-key.
18812 s.placement.shard_key = Some("$tenantId".into());
18813 let err = s.validate().unwrap_err();
18814 let AplicacaoError::ShardKeyOnNonSharded {
18815 estrategia,
18816 shard_key,
18817 } = err
18818 else {
18819 panic!("expected ShardKeyOnNonSharded, got {err:?}");
18820 };
18821 assert_eq!(estrategia, PlacementStrategy::Replicated);
18822 assert_eq!(shard_key, "$tenantId");
18823 }
18824
18825 #[test]
18826 fn rejects_shard_key_under_singlenode_strategy() {
18827 // Peer of the Replicated case above on the SingleNode arm: OTP
18828 // distributed-app takeover (one cluster runs at a time) has no
18829 // hash-keyed routing axis to consume `:shard-key` either, so
18830 // the rejection fires on both non-Sharded arms uniformly.
18831 let mut s = three_member_spec();
18832 s.placement.estrategia = PlacementStrategy::SingleNode;
18833 s.placement.shard_key = Some("$tenantId".into());
18834 let err = s.validate().unwrap_err();
18835 let AplicacaoError::ShardKeyOnNonSharded {
18836 estrategia,
18837 shard_key,
18838 } = err
18839 else {
18840 panic!("expected ShardKeyOnNonSharded, got {err:?}");
18841 };
18842 assert_eq!(estrategia, PlacementStrategy::SingleNode);
18843 assert_eq!(shard_key, "$tenantId");
18844 }
18845
18846 #[test]
18847 fn rejects_empty_shard_key_under_replicated_strategy() {
18848 // The `Some("")` case under non-Sharded is rejected by
18849 // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
18850 // fires before the empty-value gate), not
18851 // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
18852 // the `Sharded` arm). Pin the partition so a future reorder of
18853 // the validate_placement match arms doesn't silently swap which
18854 // diagnostic the author sees — both are author errors, but
18855 // ShardKeyOnNonSharded names which strategy is the actual fix
18856 // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
18857 // only says "pick a non-empty key".
18858 let mut s = three_member_spec();
18859 s.placement.shard_key = Some(String::new());
18860 let err = s.validate().unwrap_err();
18861 assert!(
18862 matches!(
18863 err,
18864 AplicacaoError::ShardKeyOnNonSharded {
18865 estrategia: PlacementStrategy::Replicated,
18866 ref shard_key,
18867 } if shard_key.is_empty()
18868 ),
18869 "got {err:?}"
18870 );
18871 }
18872
18873 #[test]
18874 fn replicated_without_shard_key_validates() {
18875 // The complement of the rejection: `:placement :estrategia
18876 // Replicated` with `:shard-key None` is the canonical happy
18877 // path on every existing fixture. Pin the no-shard-key case so
18878 // the new gate doesn't accidentally fire on `None`.
18879 let mut s = three_member_spec();
18880 assert!(matches!(
18881 s.placement.estrategia,
18882 PlacementStrategy::Replicated
18883 ));
18884 s.placement.shard_key = None;
18885 s.validate().unwrap();
18886 }
18887
18888 #[test]
18889 fn singlenode_without_shard_key_validates() {
18890 // Peer of the Replicated no-shard-key case on the SingleNode
18891 // arm — both non-Sharded strategies must validate cleanly when
18892 // the slot is omitted.
18893 let mut s = three_member_spec();
18894 s.placement.estrategia = PlacementStrategy::SingleNode;
18895 s.placement.shard_key = None;
18896 s.validate().unwrap();
18897 }
18898
18899 fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
18900 // Fixture builder for the `:placement :shard-key` shape gate
18901 // tests: a three-member Aplicacao on the `Sharded` strategy
18902 // with the supplied `:shard-key` slot. Co-locates the
18903 // arm-construction so every test below carries one line of
18904 // setup (the offending `:shard-key` value) and the assertion.
18905 let mut s = three_member_spec();
18906 s.placement.estrategia = PlacementStrategy::Sharded;
18907 s.placement.shard_key = Some(key.into());
18908 s
18909 }
18910
18911 #[test]
18912 fn rejects_shard_key_with_embedded_space() {
18913 // The canonical paste-from-aligned-doc footgun:
18914 // `:shard-key "$tenant Id"` — the Akka-style entity-id
18915 // extractor reads the slot as a single-token reference, and an
18916 // embedded space breaks the token boundary at the runtime
18917 // hash-extractor pass with no diagnostic naming the offending
18918 // entry.
18919 let s = sharded_spec_with_key("$tenant Id");
18920 let err = s.validate().unwrap_err();
18921 assert!(
18922 matches!(
18923 err,
18924 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18925 if shard_key == "$tenant Id" && reason.contains("space")
18926 ),
18927 "got {err:?}"
18928 );
18929 }
18930
18931 #[test]
18932 fn rejects_shard_key_with_leading_space() {
18933 // Leading-space arm of the embedded-whitespace footgun — the
18934 // paste-from-aligned-doc / paste-from-CSV-cell variant where
18935 // the leading column-padding leaked into the slot.
18936 let s = sharded_spec_with_key(" $tenantId");
18937 let err = s.validate().unwrap_err();
18938 assert!(
18939 matches!(
18940 err,
18941 AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
18942 if shard_key == " $tenantId"
18943 ),
18944 "got {err:?}"
18945 );
18946 }
18947
18948 #[test]
18949 fn rejects_shard_key_with_trailing_newline() {
18950 // The canonical paste-from-shell-heredoc footgun — every
18951 // `<<EOF` heredoc terminator paste leaves a trailing newline
18952 // the YAML emitter then folds away inconsistently across
18953 // emitter implementations.
18954 let s = sharded_spec_with_key("$tenantId\n");
18955 let err = s.validate().unwrap_err();
18956 assert!(
18957 matches!(
18958 err,
18959 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18960 if shard_key == "$tenantId\n" && reason.contains("0x0a")
18961 ),
18962 "got {err:?}"
18963 );
18964 }
18965
18966 #[test]
18967 fn rejects_shard_key_with_embedded_tab() {
18968 // The paste-from-aligned-doc tab-stop variant — tabs land
18969 // alongside spaces in copy-paste from formatted columns.
18970 let s = sharded_spec_with_key("$tenant\tId");
18971 let err = s.validate().unwrap_err();
18972 assert!(
18973 matches!(
18974 err,
18975 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18976 if shard_key == "$tenant\tId" && reason.contains("tab")
18977 ),
18978 "got {err:?}"
18979 );
18980 }
18981
18982 #[test]
18983 fn rejects_shard_key_with_control_character() {
18984 // The paste-from-binary / paste-from-screen-cleared-terminal
18985 // footgun — an embedded `\x01` (SOH) byte that some YAML
18986 // emitters silently strip and others escape as ``,
18987 // breaking round-trip across emitter implementations.
18988 let s = sharded_spec_with_key("$tenant\u{0001}Id");
18989 let err = s.validate().unwrap_err();
18990 assert!(
18991 matches!(
18992 err,
18993 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18994 if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
18995 ),
18996 "got {err:?}"
18997 );
18998 }
18999
19000 #[test]
19001 fn rejects_shard_key_with_non_ascii() {
19002 // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
19003 // footgun — non-ASCII bytes normalize differently between the
19004 // caixa-mesh-side YAML emitter and the in-cluster reconciler's
19005 // YAML parser, the same entity ID can silently map to two
19006 // distinct shards on a re-render.
19007 let s = sharded_spec_with_key("$tenàntId");
19008 let err = s.validate().unwrap_err();
19009 assert!(
19010 matches!(
19011 err,
19012 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19013 if shard_key == "$tenàntId" && reason.contains("non-ASCII")
19014 ),
19015 "got {err:?}"
19016 );
19017 }
19018
19019 #[test]
19020 fn rejects_shard_key_too_long() {
19021 // Length cap pin: 64 bytes — one byte over the
19022 // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
19023 // here is a paste-from-doc multi-line blob landing in
19024 // `:shard-key` instead of a single-token extractor expression.
19025 let too_long = "a".repeat(64);
19026 let s = sharded_spec_with_key(&too_long);
19027 let err = s.validate().unwrap_err();
19028 let AplicacaoError::ShardKeyInvalid {
19029 ref shard_key,
19030 ref reason,
19031 } = err
19032 else {
19033 panic!("expected ShardKeyInvalid, got {err:?}");
19034 };
19035 assert_eq!(shard_key, &too_long);
19036 assert!(
19037 reason.contains("63") && reason.contains("64"),
19038 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19039 );
19040 }
19041
19042 #[test]
19043 fn shard_key_max_length_validates() {
19044 // Boundary pin: 63 bytes exactly — the
19045 // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
19046 // dropping to 62) surfaces here as a regression, mirroring
19047 // `placement_cluster_max_length_validates` /
19048 // `placement_affinity_max_length_validates` on the peer
19049 // identifier-shaped slots.
19050 let s = sharded_spec_with_key(&"a".repeat(63));
19051 s.validate().unwrap();
19052 }
19053
19054 #[test]
19055 fn accepts_canonical_shard_key_forms() {
19056 // The Akka-style entity-id extractor shapes a caixa author is
19057 // realistically going to write — pin every leg so a future
19058 // tightening that bans (e.g.) the `${...}` interpolation
19059 // variant or the `metadata.<field>` JSONPath form surfaces
19060 // here as a regression. The canonical forms span:
19061 //
19062 // - bare property name (`tenantId`, `customerId`)
19063 // - Akka `ExtractEntityId` placeholder (`$tenantId`)
19064 // - JSONPath-style nested reference (`metadata.tenantId`,
19065 // `$.user.id`)
19066 // - interpolation-style template (`${tenant}`)
19067 // - snake_case property name (`customer_id`)
19068 // - kebab-case property name (`customer-id` — accepted
19069 // because the slot is a printable-ASCII single-token
19070 // reference, not a DNS-1123 label like
19071 // `:placement :affinity` / `:clusters`)
19072 // - single character (`a`, `$` — boundary)
19073 for form in [
19074 "tenantId",
19075 "customerId",
19076 "$tenantId",
19077 "metadata.tenantId",
19078 "$.user.id",
19079 "${tenant}",
19080 "customer_id",
19081 "customer-id",
19082 "a",
19083 "$",
19084 ] {
19085 let s = sharded_spec_with_key(form);
19086 s.validate().unwrap_or_else(|e| {
19087 panic!("canonical shard-key form {form:?} must validate, got {e:?}")
19088 });
19089 }
19090 }
19091
19092 #[test]
19093 fn shard_key_empty_takes_precedence_over_invalid() {
19094 // Order pin: the existing `ShardedKeyEmpty` diagnostic
19095 // (reserved for the `Sharded` `Some("")` arm) fires before the
19096 // new `ShardKeyInvalid` parse-side diagnostic, so an empty
19097 // `:shard-key` keeps its narrower error message — the new gate
19098 // would also reject `""` defensively, but the empty-string arm
19099 // is the more self-locating diagnostic. Mirrors the
19100 // `placement_cluster_empty_takes_precedence_over_invalid` pin
19101 // on the peer identifier-shaped slot.
19102 let s = sharded_spec_with_key("");
19103 let err = s.validate().unwrap_err();
19104 assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
19105 }
19106
19107 #[test]
19108 fn shard_key_invalid_diagnostic_carries_offending_value() {
19109 // The diagnostic-shape pin: the error names the offending
19110 // `:shard-key` value verbatim so the author can grep their
19111 // caixa.lisp without re-running the build, and carries a
19112 // parser-shaped `reason:` naming the specific violation —
19113 // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19114 // on the peer identifier-shaped slot.
19115 let s = sharded_spec_with_key("$tenant Id");
19116 let err = s.validate().unwrap_err();
19117 let AplicacaoError::ShardKeyInvalid {
19118 ref shard_key,
19119 ref reason,
19120 } = err
19121 else {
19122 panic!("expected ShardKeyInvalid, got {err:?}");
19123 };
19124 assert_eq!(shard_key, "$tenant Id");
19125 assert!(
19126 !reason.is_empty(),
19127 "reason must name the specific violation, got empty string"
19128 );
19129 }
19130
19131 #[test]
19132 fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
19133 // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
19134 // `:shard-key` carried on non-Sharded strategies) fires before
19135 // the shape gate, so a malformed `:shard-key` carried on (e.g.)
19136 // a `Replicated` strategy surfaces the more self-locating
19137 // strategy-mismatch diagnostic (naming the actual fix — drop
19138 // the slot, or switch to Sharded) rather than the shape
19139 // diagnostic. The strategy-mismatch arm is the more actionable
19140 // diagnostic: a malformed shard-key on Replicated is "you
19141 // shouldn't have a :shard-key here at all", not "your
19142 // :shard-key value is malformed".
19143 let mut s = three_member_spec();
19144 // Replicated is the default fixture strategy.
19145 s.placement.shard_key = Some("$tenant Id".into());
19146 let err = s.validate().unwrap_err();
19147 assert!(
19148 matches!(
19149 err,
19150 AplicacaoError::ShardKeyOnNonSharded {
19151 estrategia: PlacementStrategy::Replicated,
19152 ..
19153 }
19154 ),
19155 "got {err:?}"
19156 );
19157 }
19158
19159 #[test]
19160 fn rejects_empty_affinity_hint() {
19161 let mut s = three_member_spec();
19162 s.placement.affinity = Some("".into());
19163 assert_eq!(
19164 s.validate().unwrap_err(),
19165 AplicacaoError::PlacementAffinityEmpty
19166 );
19167 }
19168
19169 #[test]
19170 fn placement_without_affinity_validates() {
19171 // Omitting :affinity is fine — the placement engine falls back
19172 // to the default heuristic. Pin the no-hint case so the
19173 // affinity-empty rejection doesn't accidentally fire on `None`.
19174 let mut s = three_member_spec();
19175 s.placement.affinity = None;
19176 s.validate().unwrap();
19177 }
19178
19179 #[test]
19180 fn rejects_placement_affinity_with_uppercase() {
19181 // The canonical "I copied the ADR's display name verbatim" typo
19182 // — placement hints land verbatim in K8s label-selector
19183 // territory, where the apiserver enforces the DNS-1123 label
19184 // rule (lowercase-only) on every identity-keyed admission axis.
19185 // Mirrors `rejects_placement_cluster_with_uppercase` on the
19186 // sibling slot.
19187 let mut s = three_member_spec();
19188 s.placement.affinity = Some("DataLocality".into());
19189 let err = s.validate().unwrap_err();
19190 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19191 panic!("expected PlacementAffinityInvalid, got other variant");
19192 };
19193 assert_eq!(affinity, "DataLocality");
19194 assert!(
19195 reason.contains("uppercase"),
19196 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19197 );
19198 assert!(
19199 reason.contains("\"datalocality\""),
19200 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19201 );
19202 }
19203
19204 #[test]
19205 fn rejects_placement_affinity_with_underscore() {
19206 // The canonical "I'm thinking of an env var / Python identifier"
19207 // leak — `_` is forbidden by every DNS-1123 label schema. Same
19208 // shape as `rejects_placement_cluster_with_underscore` on the
19209 // sibling slot.
19210 let mut s = three_member_spec();
19211 s.placement.affinity = Some("data_locality".into());
19212 let err = s.validate().unwrap_err();
19213 assert!(
19214 matches!(
19215 err,
19216 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19217 if affinity == "data_locality" && reason.contains('_')
19218 ),
19219 "got {err:?}"
19220 );
19221 }
19222
19223 #[test]
19224 fn rejects_placement_affinity_with_dot() {
19225 // A `:placement :affinity` value is a single DNS-1123 *label*
19226 // (it lands as a K8s label value selector key), not a subdomain.
19227 // The "I want to namespace my hint with `.`" intent is expressed
19228 // via `-` (`data-locality-east`).
19229 let mut s = three_member_spec();
19230 s.placement.affinity = Some("data.locality".into());
19231 let err = s.validate().unwrap_err();
19232 assert!(
19233 matches!(
19234 err,
19235 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19236 if affinity == "data.locality" && reason.contains('.')
19237 ),
19238 "got {err:?}"
19239 );
19240 }
19241
19242 #[test]
19243 fn rejects_placement_affinity_with_unicode() {
19244 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19245 // before it reaches K8s. The byte-by-byte ASCII validity check
19246 // rejects multi-byte UTF-8 sequences by the first byte that
19247 // fails `[a-z0-9-]`.
19248 let mut s = three_member_spec();
19249 s.placement.affinity = Some("data-localité".into());
19250 let err = s.validate().unwrap_err();
19251 assert!(
19252 matches!(
19253 err,
19254 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19255 if affinity == "data-localité"
19256 ),
19257 "got {err:?}"
19258 );
19259 }
19260
19261 #[test]
19262 fn rejects_placement_affinity_with_leading_hyphen() {
19263 // DNS-1123 boundary rule: labels must start with an
19264 // alphanumeric. Pin separately from the trailing-hyphen arm so
19265 // a future relaxation that only checks one boundary surfaces
19266 // here as a regression (parallel to
19267 // `rejects_placement_cluster_with_leading_hyphen`).
19268 let mut s = three_member_spec();
19269 s.placement.affinity = Some("-data-locality".into());
19270 let err = s.validate().unwrap_err();
19271 assert!(
19272 matches!(
19273 err,
19274 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19275 if affinity == "-data-locality" && reason.contains("start and end")
19276 ),
19277 "got {err:?}"
19278 );
19279 }
19280
19281 #[test]
19282 fn rejects_placement_affinity_with_trailing_hyphen() {
19283 // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
19284 // ends are covered against a future relaxation.
19285 let mut s = three_member_spec();
19286 s.placement.affinity = Some("data-locality-".into());
19287 let err = s.validate().unwrap_err();
19288 assert!(
19289 matches!(
19290 err,
19291 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19292 if affinity == "data-locality-"
19293 ),
19294 "got {err:?}"
19295 );
19296 }
19297
19298 #[test]
19299 fn rejects_placement_affinity_with_whitespace() {
19300 // Whitespace is the canonical "I pasted from a sketch / doc"
19301 // footgun. The apiserver rejects every label-selector value
19302 // carrying whitespace.
19303 let mut s = three_member_spec();
19304 s.placement.affinity = Some("data locality".into());
19305 let err = s.validate().unwrap_err();
19306 assert!(
19307 matches!(
19308 err,
19309 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19310 if affinity == "data locality"
19311 ),
19312 "got {err:?}"
19313 );
19314 }
19315
19316 #[test]
19317 fn rejects_placement_affinity_too_long() {
19318 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19319 // pin. The diagnostic names both the cap (63) and the actual
19320 // length so the author can shorten in one edit. Mirrors
19321 // `rejects_placement_cluster_too_long`.
19322 let mut s = three_member_spec();
19323 let too_long = "a".repeat(64);
19324 s.placement.affinity = Some(too_long.clone());
19325 let err = s.validate().unwrap_err();
19326 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19327 panic!("expected PlacementAffinityInvalid");
19328 };
19329 assert_eq!(affinity, too_long);
19330 assert!(
19331 reason.contains("63") && reason.contains("64"),
19332 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19333 );
19334 }
19335
19336 #[test]
19337 fn placement_affinity_max_length_validates() {
19338 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19339 // future tightening (e.g. dropping to 62) surfaces here as a
19340 // regression, mirroring `placement_cluster_max_length_validates`.
19341 let mut s = three_member_spec();
19342 s.placement.affinity = Some("a".repeat(63));
19343 s.validate().unwrap();
19344 }
19345
19346 #[test]
19347 fn accepts_canonical_placement_affinity_forms() {
19348 // The DNS-1123 label shapes a caixa author is realistically
19349 // going to write for placement hints: the M3 canonical examples
19350 // (`data-locality`, `low-latency`, `anti-affinity`), the
19351 // single-token form (`affinity`), the single-character boundary
19352 // (`a`), the digit-start (DNS-1123 allows this, unlike
19353 // DNS-1035), and a regional-suffixed form. Pin every leg so a
19354 // future tightening that bans (e.g.) digit-start identifiers
19355 // surfaces here.
19356 for form in [
19357 "data-locality",
19358 "low-latency",
19359 "anti-affinity",
19360 "affinity",
19361 "a",
19362 "3-tier",
19363 "locality-east",
19364 ] {
19365 let mut s = three_member_spec();
19366 s.placement.affinity = Some(form.into());
19367 s.validate().unwrap_or_else(|e| {
19368 panic!("canonical affinity form {form:?} must validate, got {e:?}")
19369 });
19370 }
19371 }
19372
19373 #[test]
19374 fn placement_affinity_empty_takes_precedence_over_invalid() {
19375 // Order pin: the existing `PlacementAffinityEmpty` diagnostic
19376 // (which doesn't try to parse) fires before the new
19377 // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
19378 // `:affinity` keeps its narrower error message — the new gate
19379 // would also reject `""`, but the empty-string arm is the more
19380 // self-locating diagnostic. Mirrors the
19381 // `placement_cluster_empty_takes_precedence_over_invalid` pin.
19382 let mut s = three_member_spec();
19383 s.placement.affinity = Some(String::new());
19384 let err = s.validate().unwrap_err();
19385 assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
19386 }
19387
19388 #[test]
19389 fn placement_affinity_invalid_diagnostic_carries_offending_value() {
19390 // The diagnostic shape pin: every rejection carries the offending
19391 // `affinity:` verbatim plus a parser-shaped `reason:` so the
19392 // author can grep their caixa.lisp for `:affinity "<hint>"` and
19393 // fix it in one edit. Mirrors the
19394 // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19395 // pin on the sibling slot.
19396 let mut s = three_member_spec();
19397 s.placement.affinity = Some("Data_Locality".into());
19398 let err = s.validate().unwrap_err();
19399 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19400 panic!("expected PlacementAffinityInvalid");
19401 };
19402 assert_eq!(affinity, "Data_Locality");
19403 assert!(
19404 !reason.is_empty(),
19405 "diagnostic reason must not be empty (got: {reason:?})"
19406 );
19407 }
19408
19409 #[test]
19410 fn singlenode_with_takeover_candidates_validates() {
19411 // OTP distributed-application convention (MESH-COMPOSITION
19412 // §II.1): SingleNode runs on one cluster at a time but the
19413 // :clusters list enumerates the takeover candidates. Multiple
19414 // entries are not a contradiction — they are the failover pool.
19415 let mut s = three_member_spec();
19416 s.placement.estrategia = PlacementStrategy::SingleNode;
19417 s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
19418 s.validate().unwrap();
19419 }
19420
19421 // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
19422
19423 #[test]
19424 fn mesh_policy_default_is_empty() {
19425 // The Default impl carries None on every axis — the typed
19426 // analog of an unset `:politicas (())` slot. Renderers that
19427 // overlay the policy onto a cluster artifact key off this
19428 // predicate to skip the slot entirely; pinning so a future
19429 // axis added to MeshPolicy can't silently break the contract
19430 // (a new field whose Default is non-None would flip is_empty
19431 // to false on every existing caixa, surfacing here).
19432 assert!(MeshPolicy::default().is_empty());
19433 }
19434
19435 #[test]
19436 fn mesh_policy_with_only_timeout_is_not_empty() {
19437 let p = MeshPolicy {
19438 timeout: Some(Duration::from_secs(30)),
19439 ..Default::default()
19440 };
19441 assert!(!p.is_empty());
19442 }
19443
19444 #[test]
19445 fn mesh_policy_with_only_retries_is_not_empty() {
19446 let p = MeshPolicy {
19447 retries: Some(3),
19448 ..Default::default()
19449 };
19450 assert!(!p.is_empty());
19451 }
19452
19453 #[test]
19454 fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
19455 let p = MeshPolicy {
19456 circuit_breaker: Some(CircuitBreaker {
19457 max_failures: 5,
19458 window: Duration::from_secs(60),
19459 }),
19460 ..Default::default()
19461 };
19462 assert!(!p.is_empty());
19463 }
19464
19465 #[test]
19466 fn mesh_policy_with_only_mtls_required_is_not_empty() {
19467 // Even `mtls_required: Some(false)` (an explicit opt-out) is
19468 // not empty — the author *named* the axis, the renderer needs
19469 // to honor that vs. fall back to the cluster default.
19470 let p = MeshPolicy {
19471 mtls_required: Some(false),
19472 ..Default::default()
19473 };
19474 assert!(!p.is_empty());
19475 }
19476
19477 #[test]
19478 fn mesh_policy_with_only_rate_limit_is_not_empty() {
19479 let p = MeshPolicy {
19480 rate_limit: Some(RateLimit {
19481 rate: 100,
19482 window: Duration::from_secs(1),
19483 }),
19484 ..Default::default()
19485 };
19486 assert!(!p.is_empty());
19487 }
19488
19489 #[test]
19490 fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
19491 // The three-member happy-path fixture sets timeout + retries +
19492 // mtls_required — every populated axis must read non-empty.
19493 // Pin the round-trip so the M3.x per-:politicas emitter (the
19494 // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
19495 // on is_empty() to decide whether to emit at all without
19496 // re-deriving the contract from inline field probes.
19497 assert!(!three_member_spec().politicas.is_empty());
19498 }
19499
19500 // ── shared duration codec: cross-slot integer-magnitude gate ──
19501 //
19502 // The integer-magnitude discipline applied to
19503 // `supervisor::duration_codec::parse` lifts onto every typed slot
19504 // that routes through the shared codec — `MeshPolicy::timeout`
19505 // (`:politicas :timeout`) and `CircuitBreaker::window`
19506 // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
19507 // These cross-slot tests pin that the gate fires at the serde
19508 // layer for both typed slots, not just for the supervisor side.
19509
19510 #[test]
19511 fn policy_timeout_serde_rejects_fractional_seconds() {
19512 // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
19513 // so the shared codec's integer-magnitude gate applies on
19514 // deserialize. `"1.5s"` previously parsed to 1500ms and round-
19515 // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
19516 // deserialize with the canonical-form diagnostic naming the
19517 // offending `"1.5"` and the remediation `"1500ms"`.
19518 let payload = r#"{"timeout":"1.5s"}"#;
19519 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19520 let msg = err.to_string();
19521 assert!(
19522 msg.contains("not a non-negative integer"),
19523 "expected integer-magnitude diagnostic in {msg:?}"
19524 );
19525 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19526 assert!(
19527 msg.contains("\"1500ms\""),
19528 "missing canonical-form remediation in {msg:?}"
19529 );
19530 }
19531
19532 #[test]
19533 fn policy_timeout_serde_rejects_leading_plus_sign() {
19534 // Pin the leading-`+` arm cross-slot — the prior f64 parser
19535 // accepted `"+30s"` silently and round-tripped to `"30s"`.
19536 let payload = r#"{"timeout":"+30s"}"#;
19537 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19538 let msg = err.to_string();
19539 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
19540 }
19541
19542 #[test]
19543 fn circuit_breaker_window_serde_rejects_fractional_minutes() {
19544 // `CircuitBreaker::window` uses `with =
19545 // "supervisor::duration_codec_required"` (the required-Duration
19546 // variant that delegates to the same shared parser). `"0.5m"`
19547 // parsed to 30s and round-tripped to `"30s"` on next emit —
19548 // DRIFT closed.
19549 let payload = format!(
19550 r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
19551 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19552 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19553 );
19554 let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
19555 let msg = err.to_string();
19556 assert!(
19557 msg.contains("not a non-negative integer"),
19558 "expected integer-magnitude diagnostic in {msg:?}"
19559 );
19560 assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
19561 assert!(
19562 msg.contains("\"30s\""),
19563 "missing canonical-form remediation in {msg:?}"
19564 );
19565 }
19566
19567 #[test]
19568 fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
19569 // Pin the happy-path on the cross-slot side: every canonical
19570 // author shape `render` ever emits parses cleanly through the
19571 // shared codec on the `CircuitBreaker` slot. The
19572 // codec's accepted set (post-gate) is exactly its emitted set
19573 // for the integer-magnitude class.
19574 for window_lit in ["30s", "500ms", "2m", "1h"] {
19575 let payload = format!(
19576 r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
19577 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19578 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19579 );
19580 let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
19581 panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
19582 });
19583 assert_eq!(cb.max_failures, 5);
19584 }
19585 }
19586
19587 // ── rate_limit_codec: integer-magnitude gate ──
19588 //
19589 // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
19590 // / 737a676 / d53c922 trajectory landed on every typed-duration /
19591 // typed-byte-size codec in caixa-core lifts onto the fifth typed
19592 // codec — `rate_limit_codec` — through the digit-only magnitude
19593 // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
19594 // These tests pin the gate at the serde layer for `:politicas
19595 // :rate-limit` (the only typed slot the codec backs), and at the
19596 // codec-internal `parse` layer for the canonical positive cases.
19597
19598 #[test]
19599 fn rate_limit_serde_rejects_fractional_rate() {
19600 // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
19601 // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
19602 // wording, which didn't name the canonical-form remediation or
19603 // the round-trip drift the next emit would produce. Now refused
19604 // at deserialize with the canonical-form diagnostic naming the
19605 // offending `"1.5"` magnitude and the round-trip drift wording.
19606 let payload = r#"{"rateLimit":"1.5/s"}"#;
19607 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19608 let msg = err.to_string();
19609 assert!(
19610 msg.contains("not a non-negative integer"),
19611 "expected integer-magnitude diagnostic in {msg:?}"
19612 );
19613 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19614 assert!(
19615 msg.contains("THEORY.md"),
19616 "missing render-determinism contract citation in {msg:?}"
19617 );
19618 }
19619
19620 #[test]
19621 fn rate_limit_serde_rejects_leading_plus_sign() {
19622 // `u32::from_str("+100")` returns `Ok(100)` (Rust's
19623 // permissive-`+` parse), so `"+100/s"` silently parsed to
19624 // `RateLimit { 100, 1s }` and round-tripped through `render` to
19625 // `"100/s"` — a *different* canonical string on the next emit,
19626 // breaking the THEORY.md Part V render-determinism contract
19627 // exactly the way the peer duration codecs' `"+30s"` case did.
19628 // This is the load-bearing class the digit-only gate closes
19629 // beyond what `u32::from_str`'s strictness covers on its own.
19630 let payload = r#"{"rateLimit":"+100/s"}"#;
19631 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19632 let msg = err.to_string();
19633 assert!(
19634 msg.contains("not a non-negative integer"),
19635 "expected integer-magnitude diagnostic in {msg:?}"
19636 );
19637 assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
19638 }
19639
19640 #[test]
19641 fn rate_limit_serde_rejects_leading_minus_sign() {
19642 // The signed-negative arm: `"-1/s"` lands on the
19643 // non-canonical-but-numeric branch via the `i64` fallback (the
19644 // `f64` parse also succeeds), surfacing the canonical-form
19645 // diagnostic. Replaces the prior value-laundered "not a u32"
19646 // wording with the unified diagnostic across signs.
19647 let payload = r#"{"rateLimit":"-1/s"}"#;
19648 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19649 let msg = err.to_string();
19650 assert!(
19651 msg.contains("not a non-negative integer"),
19652 "expected integer-magnitude diagnostic in {msg:?}"
19653 );
19654 assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
19655 }
19656
19657 #[test]
19658 fn rate_limit_serde_rejects_decimal_shaped_integer() {
19659 // `"100.0/s"` is integer-valued numerically but not in the
19660 // codec's accepted set — `render` emits `"100/s"`, so the
19661 // round-trip would drift. Lifted to the canonical-form
19662 // diagnostic peer with the duration codec's `"1.0s"` case
19663 // (1c55a2a).
19664 let payload = r#"{"rateLimit":"100.0/s"}"#;
19665 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19666 let msg = err.to_string();
19667 assert!(
19668 msg.contains("not a non-negative integer"),
19669 "expected integer-magnitude diagnostic in {msg:?}"
19670 );
19671 assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
19672 }
19673
19674 #[test]
19675 fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
19676 // Non-numeric, non-digit-only input lands on the existing
19677 // narrower `"not a u32"` arm (preserved for diagnostic-shape
19678 // stability on the parser-shape footgun case). Pin this so a
19679 // future relaxation of the numeric-fallback predicate doesn't
19680 // silently collapse garbage onto the canonical-form arm — same
19681 // partition the peer duration codecs draw between
19682 // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
19683 let payload = r#"{"rateLimit":"abc/s"}"#;
19684 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19685 let msg = err.to_string();
19686 assert!(
19687 msg.contains("not a u32"),
19688 "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
19689 );
19690 assert!(
19691 !msg.contains("not a non-negative integer"),
19692 "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
19693 );
19694 }
19695
19696 #[test]
19697 fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
19698 // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
19699 // u32's range. The digit-only gate passes; `u32::from_str`
19700 // fails on overflow. Surface that with the overflow-shaped
19701 // diagnostic naming the offending magnitude verbatim, peer
19702 // with `supervisor::duration_codec`'s overflow arm. Pinning
19703 // the wording so a future refactor doesn't silently collapse
19704 // overflow onto the canonical-form arm.
19705 let payload = r#"{"rateLimit":"4294967296/s"}"#;
19706 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19707 let msg = err.to_string();
19708 assert!(
19709 msg.contains("overflows u32"),
19710 "expected overflow diagnostic in {msg:?}"
19711 );
19712 assert!(
19713 msg.contains("\"4294967296\""),
19714 "missing offending magnitude in {msg:?}"
19715 );
19716 }
19717
19718 #[test]
19719 fn rate_limit_serde_rejects_leading_zero_magnitude() {
19720 // `"0100/s"` is digit-only, so the existing
19721 // non-digit-only / sign / fractional arm doesn't catch it —
19722 // `u32::from_str("0100")` returns `Ok(100)`, so before this
19723 // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
19724 // round-tripped through `render` to `"100/s"` — a *different*
19725 // canonical string on the next emit, breaking the THEORY.md
19726 // Part V render-determinism contract exactly the way the
19727 // peer `"+100/s"` case did before the leading-`+` arm landed.
19728 // This is the load-bearing class the leading-zero gate closes
19729 // beyond what the existing digit-only / sign / fractional
19730 // gates cover, and the peer arm to the leading-`+` test
19731 // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
19732 // canonical-form-drift axis.
19733 let payload = r#"{"rateLimit":"0100/s"}"#;
19734 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19735 let msg = err.to_string();
19736 assert!(
19737 msg.contains("non-canonical leading zero"),
19738 "expected leading-zero diagnostic in {msg:?}"
19739 );
19740 assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
19741 assert!(
19742 msg.contains("THEORY.md"),
19743 "missing render-determinism contract citation in {msg:?}"
19744 );
19745 }
19746
19747 #[test]
19748 fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
19749 // `"00/s"` is the degenerate leading-zero case — every byte
19750 // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
19751 // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
19752 // a *different* canonical string, same render-determinism
19753 // violation. The single-byte `"0/s"` itself is in the
19754 // accepted set (round-trips losslessly through `render`,
19755 // refused downstream by `PolicyRateLimitZero`); the
19756 // multi-byte `"00/s"` is not. Pins the boundary between the
19757 // accepted single-`0` and the rejected leading-zero class.
19758 let payload = r#"{"rateLimit":"00/s"}"#;
19759 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19760 let msg = err.to_string();
19761 assert!(
19762 msg.contains("non-canonical leading zero"),
19763 "expected leading-zero diagnostic in {msg:?}"
19764 );
19765 assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
19766 }
19767
19768 #[test]
19769 fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
19770 // Cross-window pin — the gate is window-agnostic; the
19771 // leading-zero class is a property of the magnitude, not the
19772 // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
19773 // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
19774 // single-window coverage extended across the three canonical
19775 // windows the codec accepts.
19776 let payload = r#"{"rateLimit":"007/h"}"#;
19777 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19778 let msg = err.to_string();
19779 assert!(
19780 msg.contains("non-canonical leading zero"),
19781 "expected leading-zero diagnostic in {msg:?}"
19782 );
19783 assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
19784 }
19785
19786 #[test]
19787 fn rate_limit_serde_rejects_leading_whitespace() {
19788 // `" 100/s"` — the canonical paste-from-aligned-doc /
19789 // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
19790 // the top-level `s.trim()` silently ate the leading space and
19791 // parsed the value to `RateLimit { 100, 1s }`, which then
19792 // round-tripped through `render` to `"100/s"` (a *different*
19793 // canonical string on the next emit) — the exact
19794 // canonical-form-drift class the leading-`+` / leading-zero
19795 // arms already close, extended to the whitespace byte class.
19796 let payload = r#"{"rateLimit":" 100/s"}"#;
19797 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19798 let msg = err.to_string();
19799 assert!(
19800 msg.contains("contains whitespace byte"),
19801 "expected whitespace diagnostic in {msg:?}"
19802 );
19803 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19804 assert!(
19805 msg.contains("THEORY.md"),
19806 "missing render-determinism contract citation in {msg:?}"
19807 );
19808 }
19809
19810 #[test]
19811 fn rate_limit_serde_rejects_trailing_whitespace() {
19812 // `"100/s "` — the canonical shell-history / trailing-space
19813 // paste footgun. Before this gate the top-level `s.trim()`
19814 // silently ate the trailing space and parsed to
19815 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
19816 // next emit — same canonical-form drift as the leading-space
19817 // sibling, closed on the same whitespace-byte arm.
19818 let payload = r#"{"rateLimit":"100/s "}"#;
19819 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19820 let msg = err.to_string();
19821 assert!(
19822 msg.contains("contains whitespace byte"),
19823 "expected whitespace diagnostic in {msg:?}"
19824 );
19825 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19826 }
19827
19828 #[test]
19829 fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
19830 // `"100 / s"` — the canonical typographically-spaced author
19831 // shape (the same idiom every prose reference to a rate limit
19832 // renders as, mistakenly retained when the value is pasted
19833 // into a codec-shaped slot). Before this gate the per-part
19834 // `rate_str.trim()` / `unit.trim()` calls silently ate both
19835 // spaces on either side of `/` and parsed to
19836 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
19837 // codec's *internal* whitespace-tolerance vector, orthogonal
19838 // to the leading / trailing surface but the same canonical-
19839 // form-drift class. Pins the arm as strictly stronger than the
19840 // pre-existing top-level `s.trim()` behavior: it fires on
19841 // whitespace anywhere in the value, not just at the string
19842 // boundary.
19843 let payload = r#"{"rateLimit":"100 / s"}"#;
19844 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19845 let msg = err.to_string();
19846 assert!(
19847 msg.contains("contains whitespace byte"),
19848 "expected whitespace diagnostic in {msg:?}"
19849 );
19850 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19851 }
19852
19853 #[test]
19854 fn rate_limit_serde_rejects_tab_byte() {
19855 // `"\t100/s"` — the canonical paste-from-indented-doc /
19856 // paste-from-YAML-block-scalar footgun where a tab byte leads
19857 // the magnitude. Pins that the gate covers tab (`0x09`) as
19858 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
19859 // members and both would be silently swallowed by `s.trim()`
19860 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
19861 // space alone to the full ASCII-whitespace set (space `0x20`,
19862 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
19863 // the tab arm as a representative of the non-space members.
19864 let payload = r#"{"rateLimit":"\t100/s"}"#;
19865 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19866 let msg = err.to_string();
19867 assert!(
19868 msg.contains("contains whitespace byte"),
19869 "expected whitespace diagnostic in {msg:?}"
19870 );
19871 assert!(
19872 msg.contains("0x09"),
19873 "missing offending tab byte in {msg:?}"
19874 );
19875 }
19876
19877 // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
19878 //
19879 // Successor to the ASCII-whitespace arm (1ad7755) on
19880 // `rate_limit_codec` — closes the strictly-complementary class the
19881 // byte-scan cannot see, through the lifted
19882 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
19883
19884 #[test]
19885 fn rate_limit_serde_rejects_leading_nbsp() {
19886 // NBSP prefix — paste-from-typography footgun. Byte-scan
19887 // misses, `str::trim` silently strips it, value drifts to
19888 // `"100/s"` on next serialize.
19889 let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
19890 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19891 let msg = err.to_string();
19892 assert!(
19893 msg.contains("non-ASCII Unicode whitespace character"),
19894 "expected non-ASCII whitespace diagnostic in {msg:?}"
19895 );
19896 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
19897 }
19898
19899 #[test]
19900 fn rate_limit_serde_rejects_internal_em_space() {
19901 // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
19902 // paste-from-typography footgun on the `<integer>/<unit>`
19903 // shape.
19904 let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
19905 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19906 let msg = err.to_string();
19907 assert!(
19908 msg.contains("non-ASCII Unicode whitespace character"),
19909 "expected non-ASCII whitespace diagnostic in {msg:?}"
19910 );
19911 assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
19912 }
19913
19914 #[test]
19915 fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
19916 // Positive-control pin: every ASCII-only canonical form the
19917 // renderer emits stays accepted through the new arm.
19918 for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
19919 let payload = format!(r#"{{"rateLimit":{lit}}}"#);
19920 let p: MeshPolicy = serde_json::from_str(&payload)
19921 .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
19922 assert!(p.rate_limit.is_some());
19923 }
19924 }
19925
19926 #[test]
19927 fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
19928 // The boundary case — `"0/s"` is the canonical form
19929 // `render(RateLimit { 0, 1s })` emits, so the codec accepts
19930 // it at the parse layer; the downstream
19931 // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
19932 // `rate == 0` at the typed-validate layer above. Pins the
19933 // partition: the leading-zero gate at the codec layer does
19934 // not poach the rate-zero semantic-validation arm at the
19935 // typed-validate layer above (a future stricter codec must
19936 // not reject `"0/s"` here, or it'd collapse the diagnostic
19937 // partitioning that lets `PolicyRateLimitZero` name the
19938 // offending typed slot).
19939 let payload = r#"{"rateLimit":"0/s"}"#;
19940 let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
19941 panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
19942 });
19943 let rl = policy.rate_limit.expect("rate_limit must be Some");
19944 assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
19945 assert_eq!(
19946 rl.window,
19947 Duration::from_secs(1),
19948 "single-`0` magnitude with `s` unit must parse to window=1s"
19949 );
19950 }
19951
19952 #[test]
19953 fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
19954 // The complementary boundary pin — every magnitude
19955 // `render` emits starts with `[1-9]` (or is the single byte
19956 // `"0"`), so the canonical-form predicate is `(len == 1) ||
19957 // (first byte != '0')`. Pinning the `len > 1 && first byte ==
19958 // '1'` case explicitly so a future tightening of the gate
19959 // (e.g. an over-eager "no leading digit < 5" rule, or a
19960 // mistakenly anchored start-of-magnitude byte check) lands
19961 // here before the canonical-forms-iterating test would catch
19962 // it.
19963 let payload = r#"{"rateLimit":"100/s"}"#;
19964 let policy: MeshPolicy = serde_json::from_str(payload)
19965 .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
19966 let rl = policy.rate_limit.expect("rate_limit must be Some");
19967 assert_eq!(
19968 rl.rate, 100,
19969 "canonical-100 magnitude must parse to rate=100"
19970 );
19971 }
19972
19973 #[test]
19974 fn rate_limit_serde_accepts_integer_canonical_forms() {
19975 // Pin the happy-path: every canonical author shape `render`
19976 // ever emits parses cleanly through the codec post-gate. The
19977 // codec's accepted set (post-gate) is exactly its emitted set
19978 // for the integer-magnitude class — same property
19979 // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
19980 // gates guarantee on the peer codecs. Iterating across rate
19981 // magnitudes (including `"0"`, which the codec accepts even
19982 // though `validate_politicas` rejects `rate == 0` at the typed
19983 // layer above) closes the codec contract at the parse layer
19984 // independently of the validate layer.
19985 for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
19986 for unit_lit in ["s", "m", "h"] {
19987 let lit = format!("{rate_lit}/{unit_lit}");
19988 let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
19989 let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
19990 panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
19991 });
19992 let rl = policy.rate_limit.expect("rate_limit must be Some");
19993 assert_eq!(
19994 rl.rate,
19995 rate_lit.parse::<u32>().unwrap(),
19996 "rate mismatch for {lit:?}"
19997 );
19998 }
19999 }
20000 }
20001
20002 #[test]
20003 fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
20004 // The structural property the gate enforces: serialize ∘
20005 // deserialize is the identity on every canonical author shape.
20006 // Peer of `parse_byte_size`'s and `parse_duration`'s
20007 // `_round_trips_through_render_for_every_canonical_form` tests
20008 // on the rate-limit axis. Before the gate, `"+100/s"` violated
20009 // this (`parse` → `RateLimit { 100, 1s }` → `render` →
20010 // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
20011 for rate in [1u32, 100, 5000, 1_000_000] {
20012 for (window, unit) in [
20013 (Duration::from_secs(1), "s"),
20014 (Duration::from_secs(60), "m"),
20015 (Duration::from_secs(3600), "h"),
20016 ] {
20017 let policy = MeshPolicy {
20018 rate_limit: Some(RateLimit { rate, window }),
20019 ..Default::default()
20020 };
20021 let json = serde_json::to_string(&policy).unwrap();
20022 let expected = format!("\"{rate}/{unit}\"");
20023 assert!(
20024 json.contains(&expected),
20025 "expected {expected:?} in {json:?}"
20026 );
20027 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20028 assert_eq!(
20029 back.rate_limit, policy.rate_limit,
20030 "round-trip for {json:?}"
20031 );
20032 }
20033 }
20034 }
20035
20036 // ── self-membership cross-slot gate ──────────────────────────────
20037
20038 #[test]
20039 fn validate_no_self_membership_rejects_self_named_membro() {
20040 // An Aplicacao whose `:membros` lists its own `:nome` is a
20041 // one-node lacre-closure recursion — rejected, naming the parent.
20042 let membros = vec![
20043 membro("catalog", "^0.1"),
20044 membro("checkout", "^0.1"),
20045 membro("cart", "^0.1"),
20046 ];
20047 let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
20048 assert!(
20049 matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
20050 "got {err:?}"
20051 );
20052 }
20053
20054 #[test]
20055 fn validate_no_self_membership_accepts_distinct_membros() {
20056 // Positive control: distinct member names (including a member
20057 // that is itself an Aplicacao — recursive composition is valid,
20058 // MESH-COMPOSITION §V) pass the gate.
20059 let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
20060 validate_no_self_membership(&membros, "checkout").unwrap();
20061 }
20062
20063 #[test]
20064 fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
20065 // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
20066 // `NoMembros` arm (the more-fundamental "graph must have nodes"
20067 // gate), not by this cross-slot self-edge gate. Keeping the
20068 // self-membership predicate vacuously-ok on the empty input
20069 // matches its supervisor-axis peer
20070 // (`validate_no_self_supervision_empty_children_is_ok`) and
20071 // makes the gate composable from any future call site (an M4
20072 // CR materializer's per-membros validator) without re-checking
20073 // emptiness.
20074 validate_no_self_membership(&[], "checkout").unwrap();
20075 }
20076
20077 #[test]
20078 fn validate_no_self_membership_diagnostic_names_offending_caixa() {
20079 // Pinning the Display: the self-membership diagnostic must name
20080 // the offending caixa verbatim + the "lists itself" framing the
20081 // author can grep for, so the cluster-far failure surfaces at
20082 // build time with one-line remediation. Same diagnostic shape
20083 // as the supervisor-axis `ChildSupervisesSelf` peer.
20084 let membros = vec![membro("orquestra", "^0.1")];
20085 let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
20086 let msg = err.to_string();
20087 assert!(
20088 msg.contains("orquestra"),
20089 "diagnostic must name the offending caixa nome (got: {msg:?})"
20090 );
20091 assert!(
20092 msg.contains("lists itself"),
20093 "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
20094 );
20095 }
20096
20097 #[test]
20098 fn default_servico_port_constant_pins_canonical_8080_literal() {
20099 // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
20100 // at the verbatim `8080` literal both consumers (the
20101 // `Entrada::port` serde default via [`default_port`] and the
20102 // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
20103 // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
20104 // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
20105 // discipline (a085b26) on the per-renderer canonical-K8s-axis
20106 // string-constant axis: a future refactor that drifts the
20107 // constant out from under either consumer surfaces here ahead
20108 // of every per-renderer's first emission. The literal value
20109 // matches the well-known HTTP-alt port the `pleme-computeunit`
20110 // library chart already emits as its `trigger.service.port`
20111 // default — by construction the same value the substrate
20112 // assumes about every Servico's in-cluster L4 listener.
20113 assert_eq!(
20114 DEFAULT_SERVICO_PORT, 8080,
20115 "canonical Servico port literal must remain `8080` verbatim — \
20116 this is the value both the `Entrada::port` serde default and the \
20117 caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
20118 );
20119 }
20120
20121 #[test]
20122 fn default_port_helper_returns_canonical_servico_port_constant() {
20123 // The bridge-arm — pins that the [`default_port`] helper
20124 // [`Entrada::port`]'s `#[serde(default = "default_port")]`
20125 // attribute hooks routes through the lifted
20126 // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
20127 // literal. A future refactor that re-introduces the `8080`
20128 // literal at the helper's return site (silently re-opening
20129 // the drift footgun this lift closed) surfaces here ahead of
20130 // every author-side `(:entrada (:host … :para …))` slot
20131 // without an explicit `:port`. Peer with the
20132 // `default_namespace_re_export_points_at_caixa_core_canonical`
20133 // pin on the caixa-mesh-side re-export axis.
20134 assert_eq!(
20135 default_port(),
20136 DEFAULT_SERVICO_PORT,
20137 "the serde-default helper must route through the lifted constant"
20138 );
20139 }
20140
20141 #[test]
20142 fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
20143 // The end-to-end pin — an author-surface `(:entrada (:host …
20144 // :para …))` without an explicit `:port` slot deserializes to
20145 // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
20146 // verbatim. Routes the canonical lifted constant through both
20147 // the serde-default machinery (the `#[serde(default =
20148 // "default_port")]` attribute) and the typed-value-shape
20149 // contract (the resulting [`Entrada::port`] value). A future
20150 // refactor that drifts either axis — replacing the serde
20151 // hook's helper, changing the typed slot's wire shape — would
20152 // surface here before any per-renderer's CNP / Gateway /
20153 // HTTPRoute emission consumed the drifted default.
20154 let entrada: Entrada =
20155 serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
20156 assert_eq!(
20157 entrada.port, DEFAULT_SERVICO_PORT,
20158 "the serde default must materialize as the lifted canonical Servico port"
20159 );
20160 }
20161
20162 #[test]
20163 fn servico_port_min_pins_canonical_accept_set_floor() {
20164 // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
20165 // verbatim `1` literal every typed `:entrada :port` acceptance
20166 // gate keys off. Peer with the
20167 // [`default_servico_port_constant_pins_canonical_8080_literal`]
20168 // discipline on the canonical-Servico-port-constant axis: a
20169 // future refactor that drifts the accept-set floor out from
20170 // under the sole consumer at [`AplicacaoSpec::validate`]'s
20171 // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
20172 // every per-`:entrada` `EntradaPortZero` diagnostic. The
20173 // literal value matches the IANA-registered TCP/UDP port
20174 // space floor (`1..=65535` — port `0` is the "any ephemeral"
20175 // sentinel, not a well-defined destination the substrate's
20176 // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
20177 // axis can honor).
20178 assert_eq!(
20179 SERVICO_PORT_MIN, 1,
20180 "canonical Servico port accept-set floor must remain `1` verbatim — \
20181 this is the value the `AplicacaoSpec::validate` gate at \
20182 `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
20183 );
20184 }
20185
20186 #[test]
20187 fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
20188 // The cross-const invariant pin — the substrate's canonical
20189 // default port must satisfy its own accept-set floor by
20190 // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
20191 // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
20192 // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
20193 // override the operator pins through a future
20194 // `:placement :default-port` slot that lands out-of-range, a
20195 // per-edition Servico-port migration that lifted the floor
20196 // above the previous default without coordinating the pair —
20197 // would silently invalidate the serde-default emission at
20198 // every author-side `(:entrada (:host … :para …))` slot
20199 // without an explicit `:port`: the default port would fall
20200 // below the accept-set floor, the `AplicacaoSpec::validate`
20201 // gate would reject every default-carrying Aplicacao as
20202 // `EntradaPortZero`, and the substrate's typed
20203 // `(defcaixa … :kind Aplicacao)` surface would fail validate
20204 // on every Aplicacao whose author omitted `:entrada :port`
20205 // for the substrate's chosen default — a class of authoring-
20206 // surface footguns the compile-time pin structurally closes.
20207 // Peer with the
20208 // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
20209 // (27f9b34) cross-const invariant pin discipline on the peer
20210 // canonical-Helm-per-values-block child-chart-enablement-toggle
20211 // axis pair.
20212 assert!(
20213 SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
20214 "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
20215 satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
20216 every default-carrying `(:entrada (:host … :para …))` slot without an \
20217 explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
20218 hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
20219 );
20220 }
20221
20222 #[test]
20223 fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
20224 // The gate-site pin — asserts the `AplicacaoSpec::validate`
20225 // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
20226 // `EntradaPortZero` diagnostic on the below-floor input
20227 // `port: 0` (the only below-floor value the `u16` field can
20228 // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
20229 // is the singleton `{0}`). A future refactor that drifts the
20230 // gate off the lifted const (silently re-introducing an
20231 // inline `if e.port == 0` byte-check) surfaces here — the
20232 // pin cannot distinguish `< 1` from `== 0` on the current
20233 // floor, but it *does* pin that the diagnostic fires on `0`
20234 // through whichever gate is wired, so any future accept-set
20235 // floor migration (a hypothetical unprivileged-only
20236 // migration lifting `SERVICO_PORT_MIN` to `1024`) must
20237 // update this test alongside the const declaration —
20238 // structurally guaranteeing the gate + accept-set + pin
20239 // trio move together. Peer with the
20240 // [`rejects_zero_entrada_port`] behavioral pin on the same
20241 // per-`:entrada :port` axis — that pin asserts the pre-lift
20242 // behavioral contract (`port: 0` → `EntradaPortZero`); this
20243 // pin adds the structural link to the lifted floor const.
20244 assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
20245 let mut s = three_member_spec();
20246 s.entrada.as_mut().unwrap().port = 0;
20247 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
20248 }
20249
20250 // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
20251
20252 #[test]
20253 fn membro_serde_keys_match_lifted_membro_key_consts() {
20254 // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
20255 // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
20256 // name the exact camelCase JSON keys the
20257 // `#[serde(rename_all = "camelCase")]` attribute on
20258 // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
20259 // that each canonical byte-sequence appears verbatim in the
20260 // JSON — a future accidental `rename_all = "snake_case"` /
20261 // `"kebab-case"` / verbatim-field-name flip at the derive
20262 // attribute (any of which would silently break every downstream
20263 // JSON consumer that reaches for one of the two consts via
20264 // `Value::get(...)`) surfaces here as a build-time test failure
20265 // at `aplicacao.rs`, not as an apply-time
20266 // `.get(<stale-canonical-const>)` returning `None` far from the
20267 // derive-attr drift's commit. Peer with the sibling
20268 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
20269 // (40cc4e5) pin on the M2 supervision-tree top-level axis —
20270 // same discipline the SupervisorSpec top-level lift established,
20271 // extended here to the M3 [`Membro`] per-`:membros` axis.
20272 let m = Membro {
20273 caixa: "catalog".into(),
20274 versao: "^0.1".into(),
20275 };
20276 let json = serde_json::to_string(&m).unwrap();
20277 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
20278 let quoted = format!("\"{key}\"");
20279 assert!(
20280 json.contains("ed),
20281 "serialized Membro must carry the lifted MEMBRO_KEY_* \
20282 byte-sequence {quoted} verbatim in the JSON emission \
20283 (got: {json})",
20284 );
20285 }
20286 }
20287
20288 #[test]
20289 fn membro_key_consts_are_pairwise_distinct() {
20290 // Cross-axis drift-detection pin: a future collapse of the two
20291 // canonical [`Membro`] per-entry byte-strings onto the same
20292 // value (e.g. an accidental copy-paste flip of
20293 // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
20294 // silently reroute every downstream probe on one axis onto the
20295 // sibling axis's overlay entry and pass every propagation-probe
20296 // test that expected only the stale axis's value. Peer of the
20297 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
20298 // (40cc4e5).
20299 let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
20300 for (i, a) in all.iter().enumerate() {
20301 for b in all.iter().skip(i + 1) {
20302 assert_ne!(
20303 a, b,
20304 "MEMBRO_KEY_* consts must be pairwise-distinct \
20305 canonical byte-sequences — got `{a}` == `{b}`",
20306 );
20307 }
20308 }
20309 }
20310
20311 // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
20312 // URL-path fallback resolver every HTTPRoute-aware renderer
20313 // reaching for a per-rule path-list resolution routes through.
20314 // The four pin tests below fix the four-way accept-set the
20315 // resolver must always honor: (:paths-non-empty-verbatim,
20316 // :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
20317 // :paths-preserves-order-across-multiple-entries) — drift on any
20318 // arm surfaces at caixa-core build time rather than at cluster-
20319 // apply time. Peer discipline with `MeshPolicy::is_empty` on the
20320 // sibling `:politicas` typed-primitive dispatch axis.
20321
20322 fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
20323 Entrada {
20324 host: "example.com".into(),
20325 para: "cart".into(),
20326 paths: paths.into_iter().map(String::from).collect(),
20327 port: DEFAULT_SERVICO_PORT,
20328 }
20329 }
20330
20331 #[test]
20332 fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
20333 // The typed `:entrada :paths` slot carries an author-declared
20334 // list — the resolver returns each entry verbatim, no
20335 // catch-all substitution. The canonical "author declared
20336 // paths, honor them verbatim" arm of the path-list dispatch.
20337 let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20338 assert_eq!(
20339 e.resolved_paths(),
20340 vec!["/api/cart", "/api/products"],
20341 "resolved_paths must return each `:entrada :paths` entry \
20342 verbatim when the typed slot is non-empty (got {:?})",
20343 e.resolved_paths(),
20344 );
20345 }
20346
20347 #[test]
20348 fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
20349 // Empty `:entrada :paths` slot — the resolver substitutes the
20350 // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20351 // catch-all fallback verbatim. Pins the empty-arm of the
20352 // resolver's four-way accept-set against a future silent
20353 // detour that returned an empty Vec (which would emit an
20354 // HTTPRoute with zero rules — silently dropping every
20355 // external `:entrada` flow at admission time), routed to a
20356 // different fallback shape, or dropped the catch-all
20357 // altogether.
20358 let e = entrada_with_paths(vec![]);
20359 assert_eq!(
20360 e.resolved_paths(),
20361 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20362 "resolved_paths on empty `:entrada :paths` must fall back \
20363 to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
20364 all — got {:?}",
20365 e.resolved_paths(),
20366 );
20367 }
20368
20369 #[test]
20370 fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
20371 // Single-entry `:entrada :paths` — the resolver returns the
20372 // single declared path verbatim, NOT the catch-all fallback
20373 // (author declared a path, honor it — the empty-arm and the
20374 // len-1 arm are semantically distinct axes of the resolver's
20375 // accept-set). Pins that the resolver treats "author declared
20376 // one path" as authored input, not as the empty case.
20377 let e = entrada_with_paths(vec!["/api/only"]);
20378 assert_eq!(
20379 e.resolved_paths(),
20380 vec!["/api/only"],
20381 "resolved_paths on single-entry `:entrada :paths` must \
20382 return the declared path verbatim, NOT the catch-all \
20383 fallback (got {:?})",
20384 e.resolved_paths(),
20385 );
20386 }
20387
20388 #[test]
20389 fn resolved_paths_preserves_author_declared_order() {
20390 // The `:entrada :paths` list is author-ordered — the resolver
20391 // preserves the author's declaration order verbatim, since
20392 // per-rule dispatch order at the K8s Gateway API HTTPRoute
20393 // consumer is significant (first-match-wins under the
20394 // path-prefix matcher). Pins against a future silent
20395 // re-sort / dedup / normalize detour that reordered author
20396 // input.
20397 let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
20398 assert_eq!(
20399 e.resolved_paths(),
20400 vec!["/z/last", "/a/first", "/m/mid"],
20401 "resolved_paths must preserve author-declared `:entrada \
20402 :paths` order verbatim — got {:?}",
20403 e.resolved_paths(),
20404 );
20405 }
20406
20407 // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
20408 // slot `&[String]` slice accessor every per-`:entrada` consumer
20409 // that must see the author's declaration verbatim (not the
20410 // fallback-applied projection the sibling `resolved_paths`
20411 // returns) routes through. The three pin tests below fix the
20412 // accept-set the accessor must honor: (:non-empty-byte-equal,
20413 // :empty-projects-empty-slice, :preserves-author-declared-order)
20414 // — drift on any arm surfaces at caixa-core build time rather
20415 // than at cluster-apply time. Peer discipline with the sibling
20416 // [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
20417 // peer M3 mesh-slot `Vec<String>`-carry axis.
20418
20419 #[test]
20420 fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
20421 // Byte-equal pin: [`Entrada::paths`] must project the raw
20422 // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
20423 // slice borrowed from the typed slot's own [`Vec<String>`]
20424 // storage — no re-ordering, no dedup, no per-entry normalization,
20425 // no fallback substitution (the fallback-applying projection is
20426 // the sibling [`Entrada::resolved_paths`] resolver). Pins against
20427 // a future silent detour that re-normalized the list, dropped
20428 // duplicates the [`AplicacaoSpec::validate`]
20429 // `EntradaPathDuplicate` refusal already rejects at build time,
20430 // or (most severe) accidentally routed through the fallback-
20431 // applying sibling and returned the substrate catch-all when
20432 // the author declared an empty list — collapsing the raw-slot
20433 // and fallback-applied axes into one and breaking the
20434 // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
20435 //
20436 // Peer of the sibling
20437 // [`Placement::clusters`]-shape byte-equal pin
20438 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20439 // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
20440 let fixtures: Vec<Vec<String>> = vec![
20441 Vec::new(),
20442 vec!["/api/cart".into()],
20443 vec!["/api/cart".into(), "/api/products".into()],
20444 vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
20445 ];
20446 for paths in fixtures {
20447 let e = Entrada {
20448 host: "example.com".into(),
20449 para: "cart".into(),
20450 paths: paths.clone(),
20451 port: DEFAULT_SERVICO_PORT,
20452 };
20453 assert_eq!(
20454 e.paths(),
20455 paths.as_slice(),
20456 "Entrada::paths must return :entrada :paths verbatim \
20457 (got {:?}, expected {:?})",
20458 e.paths(),
20459 paths.as_slice(),
20460 );
20461 assert_eq!(
20462 e.paths(),
20463 e.paths.as_slice(),
20464 "Entrada::paths accessor and .paths.as_slice() field \
20465 access must byte-equal — the accessor is the substrate-\
20466 primitive typed dispatch every downstream per-`:entrada` \
20467 raw-slot path-list consumer must route through",
20468 );
20469 assert_eq!(
20470 e.paths().len(),
20471 e.paths.len(),
20472 "Entrada::paths().len() must byte-equal self.paths.len() \
20473 — a length drift would silently split the paired \
20474 pre-flight cascade-head `.is_empty()` probe input in \
20475 the sibling [`Entrada::resolved_paths`] resolver from \
20476 the per-entry validate loop's traversal input in \
20477 [`AplicacaoSpec::validate`]",
20478 );
20479 }
20480 }
20481
20482 #[test]
20483 fn resolved_paths_reads_through_lifted_paths_accessor() {
20484 // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
20485 // pre-flight `.paths().is_empty()` cascade-head probe (which
20486 // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20487 // catch-all fallback arm when the accessor projects the empty
20488 // slice) and the per-entry `.paths().iter().map(String::as_str)`
20489 // projection (which must reach every entry in the same order
20490 // the accessor projects, so the sibling
20491 // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
20492 // per-entry projection stay in lockstep by construction) must
20493 // both key off the lifted accessor. Pins the two-site coherence
20494 // by exercising each production consumer end-to-end: (1) the
20495 // catch-all-fallback arm under the empty slice, (2) the
20496 // author-declared-verbatim arm under a two-entry cohort whose
20497 // per-entry projection must byte-equal the input's per-entry
20498 // author-declared paths in the author's declared order.
20499 //
20500 // Peer of the sibling M3
20501 // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
20502 // `validate_placement_reads_through_lifted_clusters_accessor`
20503 // on the sibling `Placement::clusters` reader-site convergence.
20504 let empty = entrada_with_paths(vec![]);
20505 assert_eq!(
20506 empty.resolved_paths(),
20507 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20508 "resolved_paths on empty :entrada :paths must trip the \
20509 lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
20510 catch-all fallback — routing through the lifted paths() \
20511 accessor must not silently drop the fallback arm",
20512 );
20513
20514 let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20515 assert_eq!(
20516 declared.resolved_paths(),
20517 vec!["/api/cart", "/api/products"],
20518 "resolved_paths on non-empty :entrada :paths must return each \
20519 entry verbatim in the author's declared order — routing \
20520 through the lifted paths() accessor must not silently \
20521 reorder or drop entries",
20522 );
20523 // Byte-equal pin against the raw-slot accessor to keep the
20524 // fallback-applying resolver's per-entry projection input in
20525 // lockstep with the raw-slot accessor's projection.
20526 let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
20527 assert_eq!(
20528 declared.resolved_paths(),
20529 raw_projected,
20530 "resolved_paths non-empty projection must byte-equal the \
20531 lifted paths() accessor's per-entry String::as_str projection \
20532 — the two projections share the same input slice by \
20533 construction, so any drift here would surface a silent \
20534 re-ordering / dedup / normalization detour in the resolver",
20535 );
20536 }
20537
20538 #[test]
20539 fn validate_reads_through_lifted_entrada_paths_accessor() {
20540 // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
20541 // per-entry value-shape gate's `for p in e.paths()` traversal
20542 // (which must reach every entry in the same order the accessor
20543 // projects, so both the per-entry `EntradaPathEmpty` /
20544 // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
20545 // the duplicate-detection HashSet insert that trips
20546 // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
20547 // projection) must route through the lifted accessor. Pins the
20548 // coherence by exercising each production consumer end-to-end:
20549 // (1) the `EntradaPathEmpty` refusal fires on the second entry
20550 // of a two-entry cohort whose head is valid but tail is empty
20551 // (which requires the loop to reach the second entry through
20552 // the accessor), and (2) the `EntradaPathDuplicate` refusal
20553 // fires on the second entry of a two-entry cohort that shares
20554 // a path (which requires the loop to reach both entries — a
20555 // first-entry-only projection would silently pass since the
20556 // dedup HashSet has room for the first insert).
20557 //
20558 // Peer of the sibling
20559 // `validate_placement_reads_through_lifted_clusters_accessor`
20560 // on the sibling `Placement::clusters` reader-site convergence.
20561 let base = crate::AplicacaoSpec {
20562 membros: vec![crate::Membro {
20563 caixa: "cart".into(),
20564 versao: "^0.1".into(),
20565 }],
20566 contratos: Vec::new(),
20567 politicas: crate::MeshPolicy::default(),
20568 placement: crate::Placement {
20569 estrategia: crate::PlacementStrategy::SingleNode,
20570 clusters: vec!["rio".into()],
20571 shard_key: None,
20572 affinity: None,
20573 },
20574 entrada: Some(Entrada {
20575 host: "example.com".into(),
20576 para: "cart".into(),
20577 paths: vec!["/api/cart".into(), String::new()],
20578 port: DEFAULT_SERVICO_PORT,
20579 }),
20580 };
20581 assert_eq!(
20582 base.validate(),
20583 Err(crate::AplicacaoError::EntradaPathEmpty),
20584 "validate must trip EntradaPathEmpty on the second entry of \
20585 a two-entry cohort — routing through the lifted paths() \
20586 accessor must not silently short-circuit the loop at the \
20587 valid head entry",
20588 );
20589
20590 let mut dup = base;
20591 dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
20592 assert_eq!(
20593 dup.validate(),
20594 Err(crate::AplicacaoError::EntradaPathDuplicate {
20595 path: "/api/cart".into(),
20596 }),
20597 "validate must trip EntradaPathDuplicate on the second entry \
20598 of a two-entry cohort that shares a path — routing through \
20599 the lifted paths() accessor must not silently short-circuit \
20600 the dedup HashSet insert at the first entry",
20601 );
20602 }
20603
20604 // ── Entrada::hostname / Entrada::hostnames — the substrate-
20605 // canonical per-`:entrada` DNS-hostname resolver pair every
20606 // Gateway-API-aware renderer reaching for a per-listener
20607 // singular `hostname:` filter (Gateway) or a per-route plural
20608 // `spec.hostnames[]` filter list (HTTPRoute) routes through.
20609 // The three pin tests below fix the two-way accept-set the pair
20610 // must always honor: (:singular-byte-equal-to-host,
20611 // :plural-is-singleton-of-singular, :plural-len-is-one) — drift
20612 // on any arm surfaces at caixa-core build time rather than at
20613 // cluster-apply time when the API server refuses the HTTPRoute
20614 // for non-intersecting hostname filters. Peer discipline with
20615 // the sibling `resolved_paths` accept-set pin block above on the
20616 // per-`:entrada` path-list resolver axis.
20617
20618 fn entrada_with_host(host: &str) -> Entrada {
20619 Entrada {
20620 host: host.into(),
20621 para: "cart".into(),
20622 paths: Vec::new(),
20623 port: DEFAULT_SERVICO_PORT,
20624 }
20625 }
20626
20627 #[test]
20628 fn hostname_returns_entrada_host_byte_equal() {
20629 // The canonical singular-axis pin: [`Entrada::hostname`] must
20630 // return the `:entrada :host` field byte-for-byte, borrowed
20631 // from the typed slot's own [`String`] storage. Pins against a
20632 // future silent detour that re-normalized the host (an
20633 // accidental `.to_lowercase()` — validate_entrada_host already
20634 // enforces lowercase, so any re-normalization is redundant + a
20635 // drift surface between the validator and the accessor), a
20636 // trailing-`.` fully-qualified DNS shape substitution, or a
20637 // Punycode round-trip that lowered a Unicode host through IDNA.
20638 let e = entrada_with_host("checkout.quero.cloud");
20639 assert_eq!(
20640 e.hostname(),
20641 "checkout.quero.cloud",
20642 "Entrada::hostname must return :entrada :host verbatim \
20643 (got {:?})",
20644 e.hostname(),
20645 );
20646 assert_eq!(
20647 e.hostname(),
20648 e.host.as_str(),
20649 "Entrada::hostname must byte-equal the .host field access",
20650 );
20651 }
20652
20653 #[test]
20654 fn hostnames_returns_singleton_of_hostname_accessor() {
20655 // The pair-invariant pin: [`Entrada::hostnames`] must always
20656 // return exactly `vec![hostname()]` — the singleton list whose
20657 // sole entry is the substrate's canonical per-`:entrada`
20658 // singular hostname. Pins the two-consumer coherence axis: the
20659 // Gateway listener's singular `hostname:` filter and the
20660 // HTTPRoute's plural `spec.hostnames[]` filter list must
20661 // agree, else the Gateway API v1.x conformance layer rejects
20662 // the HTTPRoute at attach time with
20663 // `Accepted:False/NoMatchingParent` (the parent Gateway's
20664 // listener hostname doesn't intersect the route's hostname
20665 // filter list) — a divergence whose apply-time symptom is far
20666 // from any single-site commit and never surfaces in the
20667 // emitted YAML. Pinning the pair-invariant here makes any
20668 // future accidental split (an accidental `.to_string() + "."`
20669 // trailing-`.` on the plural side that didn't land on the
20670 // singular side, an accidental prefix stripping on one axis,
20671 // an accidental wildcard prepend the SNI fan-out overlay
20672 // authors on the plural side without a paired singular
20673 // migration) trip at caixa-core build time.
20674 let e = entrada_with_host("checkout.quero.cloud");
20675 assert_eq!(
20676 e.hostnames(),
20677 vec![e.hostname()],
20678 "Entrada::hostnames must return `vec![hostname()]` under \
20679 the pair-invariant — got {:?} vs. singleton {:?}",
20680 e.hostnames(),
20681 vec![e.hostname()],
20682 );
20683 }
20684
20685 #[test]
20686 fn hostnames_is_singleton_under_single_host_author_surface() {
20687 // The singleton-shape pin: under today's single-hostname-per-
20688 // `:entrada` author surface (the `:host` slot is a single
20689 // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
20690 // must always return a list of length exactly one. Pins
20691 // against a future silent detour that returned an empty list
20692 // (which would emit an HTTPRoute with `spec.hostnames: []` —
20693 // matching every incoming Host header regardless of the
20694 // Aplicacao's declared ingress apex, silently over-matching
20695 // every foreign VirtualHost the parent Gateway also fronts) or
20696 // a duplicated entry (which the Gateway API v1.x parser
20697 // accepts as a `[]-length-2 list of equal hostnames]` but
20698 // whose semantics differ from the intended singleton). The
20699 // author-surface extension point ("a future `:entrada
20700 // :alt-hosts` list overlay" the docstring names) is the sole
20701 // future axis that flips this pin — that migration will re-
20702 // author this test to pin the new plural cardinality.
20703 let e = entrada_with_host("checkout.quero.cloud");
20704 assert_eq!(
20705 e.hostnames().len(),
20706 1,
20707 "Entrada::hostnames must be a singleton under today's \
20708 single-hostname-per-`:entrada` author surface — got \
20709 length {}: {:?}",
20710 e.hostnames().len(),
20711 e.hostnames(),
20712 );
20713 }
20714
20715 // ── Entrada::destination — the substrate-canonical per-`:entrada`
20716 // destination-Servico scalar accessor every Gateway-API
20717 // HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
20718 // discriminator arg (HTTPRoute name composer) or a per-rule
20719 // `backendRefs[0].name` axis routes through. The two pin tests
20720 // below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
20721 // either arm surfaces at caixa-core build time rather than at
20722 // cluster-apply time when an HTTPRoute's `metadata.name` and
20723 // `backendRefs[]` silently disagree on which destination Servico
20724 // the ingress fronts. Peer discipline with the sibling
20725 // `resolved_paths` + `hostname` + `hostnames` accept-set pin
20726 // blocks above on the per-`:entrada` path-list / DNS-hostname
20727 // resolver axes.
20728
20729 #[test]
20730 fn destination_returns_entrada_para_byte_equal() {
20731 // The canonical destination-scalar pin: [`Entrada::destination`]
20732 // must return the `:entrada :para` field byte-for-byte, borrowed
20733 // from the typed slot's own [`String`] storage. Pins against a
20734 // future silent detour that re-normalized the destination (an
20735 // accidental `.to_lowercase()` — the destination Servico is
20736 // already validated as a DNS-1123 label upstream, so any
20737 // re-normalization is redundant + a drift surface between the
20738 // validator and the accessor), a namespace-prefix rewrite (an
20739 // accidental `format!("{namespace}/{para}")` per-CR fully-
20740 // qualified rewrite that didn't land on the peer axis), or a
20741 // per-cluster suffix stamp the operator authors on one
20742 // consumer without the other.
20743 for para in ["cart", "checkout", "catalog", "orders-v2"] {
20744 let e = Entrada {
20745 host: "checkout.quero.cloud".into(),
20746 para: para.into(),
20747 paths: Vec::new(),
20748 port: DEFAULT_SERVICO_PORT,
20749 };
20750 assert_eq!(
20751 e.destination(),
20752 para,
20753 "Entrada::destination must return :entrada :para verbatim \
20754 (got {:?}, expected {para:?})",
20755 e.destination(),
20756 );
20757 assert_eq!(
20758 e.destination(),
20759 e.para.as_str(),
20760 "Entrada::destination must byte-equal the .para field access",
20761 );
20762 }
20763 }
20764
20765 #[test]
20766 fn destination_borrows_from_entrada_para_storage() {
20767 // The borrow-not-copy pin: [`Entrada::destination`] must
20768 // return a `&str` slice that borrows from the typed slot's
20769 // own [`String`] storage — same-address invariant with
20770 // `entrada.para.as_str()`. Pins against a future silent detour
20771 // that allocated a fresh `String` (`self.para.clone()` in the
20772 // body would type-check but silently drop the borrow, and
20773 // every downstream consumer that assumed the returned slice
20774 // outlives `&self` would break on a stale-reference use-after-
20775 // free). Peer with the sibling `hostname_returns_entrada_
20776 // host_byte_equal` on the singular-DNS-hostname axis.
20777 let e = entrada_with_host("checkout.quero.cloud");
20778 let dest = e.destination();
20779 let para_slice = e.para.as_str();
20780 assert_eq!(
20781 dest.as_ptr(),
20782 para_slice.as_ptr(),
20783 "Entrada::destination must borrow from the .para String's \
20784 backing storage — a fresh allocation here means the \
20785 accessor no longer names the substrate-primitive typed \
20786 dispatch and every downstream consumer would silently \
20787 carry a detached copy",
20788 );
20789 assert_eq!(
20790 dest.len(),
20791 para_slice.len(),
20792 "Entrada::destination and .para.as_str() must byte-equal in \
20793 length as well as in address",
20794 );
20795 }
20796
20797 #[test]
20798 fn port_returns_entrada_port_verbatim_across_permutations() {
20799 // The canonical L4-port-scalar pin: [`Entrada::port`] must
20800 // return the `:entrada :port` field verbatim as a `u16` across
20801 // every author-declared value in the validated accept-set
20802 // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
20803 // silent detour that clamped the port (an accidental
20804 // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
20805 // land on the peer [`AplicacaoSpec::port_for_destination`]
20806 // resolver), rewrote it through a per-cluster port-remap table
20807 // the operator authors on one consumer without the other, or
20808 // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
20809 // serde-default value (which would silently collapse the
20810 // distinction between "author explicitly declared `:port 8080`"
20811 // and "author omitted the slot and inherited the default" the
20812 // future per-cluster override slot depends on). Peer with the
20813 // sibling `destination_returns_entrada_para_byte_equal` +
20814 // `hostname_returns_entrada_host_byte_equal` pins on the
20815 // per-`:entrada` `&str` scalar axes.
20816 for port in [
20817 SERVICO_PORT_MIN,
20818 DEFAULT_SERVICO_PORT,
20819 8443u16,
20820 9090u16,
20821 u16::MAX,
20822 ] {
20823 let e = Entrada {
20824 host: "checkout.quero.cloud".into(),
20825 para: "cart".into(),
20826 paths: Vec::new(),
20827 port,
20828 };
20829 assert_eq!(
20830 e.port(),
20831 port,
20832 "Entrada::port must return :entrada :port verbatim \
20833 (got {}, expected {port})",
20834 e.port(),
20835 );
20836 assert_eq!(
20837 e.port(),
20838 e.port,
20839 "Entrada::port accessor and .port field access must \
20840 byte-equal — the accessor is the substrate-primitive \
20841 typed dispatch every downstream L4-port consumer must \
20842 route through",
20843 );
20844 }
20845 }
20846
20847 #[test]
20848 fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
20849 // Two-consumer coherence pin: the
20850 // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
20851 // (which reads through [`Entrada::port`] to compare against
20852 // [`SERVICO_PORT_MIN`]) and the
20853 // [`AplicacaoSpec::port_for_destination`] resolver (which reads
20854 // through [`Entrada::port`] to emit the per-destination
20855 // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
20856 // lifted accessor, so any future rebrand on the typed slot's
20857 // reader shape lands at exactly one place. Pins the two-site
20858 // coherence by exercising a below-floor port through validate
20859 // (which must reject) and a validated in-accept-set port through
20860 // port_for_destination (which must emit the same value the
20861 // accessor returns).
20862 let mut spec = three_member_spec();
20863 if let Some(e) = spec.entrada.as_mut() {
20864 e.port = 0;
20865 }
20866 assert_eq!(
20867 spec.validate().unwrap_err(),
20868 AplicacaoError::EntradaPortZero,
20869 "validate must reject `:entrada :port 0` through the lifted \
20870 Entrada::port accessor — port zero lies below \
20871 SERVICO_PORT_MIN and the validator routes through port() \
20872 to name the floor",
20873 );
20874
20875 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
20876 let mut spec = three_member_spec();
20877 if let Some(e) = spec.entrada.as_mut() {
20878 e.port = port;
20879 }
20880 spec.validate().expect(
20881 "entrada with in-accept-set :port must validate — the \
20882 structural-floor gate reads through Entrada::port",
20883 );
20884 let entrada_ref = spec.entrada().expect(":entrada present");
20885 assert_eq!(
20886 spec.port_for_destination(entrada_ref.destination()),
20887 entrada_ref.port(),
20888 "port_for_destination(entrada.destination()) must equal \
20889 entrada.port() — the two consumers of the per-:entrada \
20890 L4-port axis (validator, per-destination resolver) both \
20891 route through Entrada::port",
20892 );
20893 }
20894 }
20895
20896 #[test]
20897 fn wit_contract_source_returns_de_byte_equal_across_permutations() {
20898 // The canonical caller-Servico-scalar pin: [`WitContract::source`]
20899 // must return the `:contratos :de` field byte-for-byte, borrowed
20900 // from the typed slot's own [`String`] storage. Peer of the
20901 // sibling `destination_returns_entrada_para_byte_equal` pin on
20902 // the per-`:entrada` axis — same "the substrate-primitive
20903 // accessor must byte-equal the raw field access verbatim across
20904 // every author-declared value" discipline extended to the
20905 // per-`:contratos` caller arm. Pins against a future silent
20906 // detour that re-normalized the caller (an accidental
20907 // `.to_lowercase()` — every `:contratos :de` is validated as a
20908 // DNS-1123 label upstream via `validate_contrato_caixa`, so any
20909 // re-normalization is redundant + a drift surface between the
20910 // validator and the accessor), a namespace-prefix rewrite (an
20911 // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
20912 // rewrite that didn't land on the peer axis), or a per-cluster
20913 // suffix stamp the operator authors on one consumer without the
20914 // other.
20915 for de in ["cart", "checkout", "catalog", "orders-v2"] {
20916 let c = WitContract {
20917 de: de.into(),
20918 para: "downstream".into(),
20919 wit: "wasi:http/proxy".into(),
20920 endpoint: Some("/lookup".into()),
20921 subject: None,
20922 slot: None,
20923 };
20924 assert_eq!(
20925 c.source(),
20926 de,
20927 "WitContract::source must return :contratos :de verbatim \
20928 (got {:?}, expected {de:?})",
20929 c.source(),
20930 );
20931 assert_eq!(
20932 c.source(),
20933 c.de.as_str(),
20934 "WitContract::source must byte-equal the .de field access",
20935 );
20936 }
20937 }
20938
20939 #[test]
20940 fn wit_contract_source_borrows_from_de_storage() {
20941 // The borrow-not-copy pin: [`WitContract::source`] must return a
20942 // `&str` slice that borrows from the typed slot's own [`String`]
20943 // storage — same-address invariant with `c.de.as_str()`. Pins
20944 // against a future silent detour that allocated a fresh `String`
20945 // (`self.de.clone()` in the body would type-check but silently
20946 // drop the borrow, and every downstream consumer that assumed
20947 // the returned slice outlives `&self` would break on a stale-
20948 // reference use-after-free). Peer of the sibling
20949 // `destination_borrows_from_entrada_para_storage` on the
20950 // per-`:entrada` axis.
20951 let c = WitContract {
20952 de: "cart".into(),
20953 para: "catalog".into(),
20954 wit: "wasi:http/proxy".into(),
20955 endpoint: Some("/lookup".into()),
20956 subject: None,
20957 slot: None,
20958 };
20959 let src = c.source();
20960 let de_slice = c.de.as_str();
20961 assert_eq!(
20962 src.as_ptr(),
20963 de_slice.as_ptr(),
20964 "WitContract::source must borrow from the .de String's \
20965 backing storage — a fresh allocation here means the \
20966 accessor no longer names the substrate-primitive typed \
20967 dispatch and every downstream consumer would silently \
20968 carry a detached copy",
20969 );
20970 assert_eq!(
20971 src.len(),
20972 de_slice.len(),
20973 "WitContract::source and .de.as_str() must byte-equal in \
20974 length as well as in address",
20975 );
20976 }
20977
20978 #[test]
20979 fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
20980 // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
20981 // must return the `:contratos :para` field byte-for-byte,
20982 // borrowed from the typed slot's own [`String`] storage. Peer of
20983 // the sibling `destination_returns_entrada_para_byte_equal` on
20984 // the per-`:entrada` axis — both accessors name "the destination-
20985 // Servico byte-string" concept on their respective mesh-slot
20986 // atoms (per-ingress apex vs. per-typed-edge callee) and both
20987 // must project the underlying `.para` field verbatim so every
20988 // downstream renderer that composes them with peer accessors
20989 // (e.g. `spec.port_for_destination(c.destination())` at the CNP
20990 // per-edge L4 port emit site) reads the same byte-string the
20991 // author declared.
20992 for para in ["catalog", "payment", "orders", "inventory-v3"] {
20993 let c = WitContract {
20994 de: "cart".into(),
20995 para: para.into(),
20996 wit: "wasi:http/proxy".into(),
20997 endpoint: Some("/lookup".into()),
20998 subject: None,
20999 slot: None,
21000 };
21001 assert_eq!(
21002 c.destination(),
21003 para,
21004 "WitContract::destination must return :contratos :para \
21005 verbatim (got {:?}, expected {para:?})",
21006 c.destination(),
21007 );
21008 assert_eq!(
21009 c.destination(),
21010 c.para.as_str(),
21011 "WitContract::destination must byte-equal the .para \
21012 field access",
21013 );
21014 }
21015 }
21016
21017 #[test]
21018 fn wit_contract_destination_borrows_from_para_storage() {
21019 // The borrow-not-copy pin: [`WitContract::destination`] must
21020 // return a `&str` slice that borrows from the typed slot's own
21021 // [`String`] storage — same-address invariant with
21022 // `c.para.as_str()`. Peer of the sibling
21023 // `destination_borrows_from_entrada_para_storage` on the
21024 // per-`:entrada` axis.
21025 let c = WitContract {
21026 de: "cart".into(),
21027 para: "catalog".into(),
21028 wit: "wasi:http/proxy".into(),
21029 endpoint: Some("/lookup".into()),
21030 subject: None,
21031 slot: None,
21032 };
21033 let dest = c.destination();
21034 let para_slice = c.para.as_str();
21035 assert_eq!(
21036 dest.as_ptr(),
21037 para_slice.as_ptr(),
21038 "WitContract::destination must borrow from the .para \
21039 String's backing storage — a fresh allocation here means \
21040 the accessor no longer names the substrate-primitive typed \
21041 dispatch and every downstream consumer would silently \
21042 carry a detached copy",
21043 );
21044 assert_eq!(
21045 dest.len(),
21046 para_slice.len(),
21047 "WitContract::destination and .para.as_str() must byte-equal \
21048 in length as well as in address",
21049 );
21050 }
21051
21052 #[test]
21053 fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
21054 // The canonical per-`:contratos` WIT-world-reference scalar pin:
21055 // [`WitContract::world_ref`] must return the `:contratos :wit`
21056 // field byte-for-byte, borrowed from the typed slot's own
21057 // [`String`] storage. Sibling of the peer per-`:contratos`
21058 // [`WitContract::source`] / [`WitContract::destination`]
21059 // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
21060 // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
21061 // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
21062 // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
21063 // "the substrate-primitive accessor must byte-equal the raw
21064 // field access verbatim across every author-declared value"
21065 // discipline extended to the per-`:contratos` WIT-world arm.
21066 // Pins against a future silent detour that re-canonicalized the
21067 // WIT world reference (an accidental `.to_lowercase()` pass that
21068 // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
21069 // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
21070 // gate is already lowercase-prefixed so any re-normalization is
21071 // redundant + a drift surface between the validator and the
21072 // accessor), an M4-promotion-shape rewrite that formatted a
21073 // typed WIT-world enum through [`Display`] and silently drifted
21074 // the printer output from the source `caixa.lisp`, or a per-
21075 // cluster WIT-alias rewrite that didn't land on the peer field-
21076 // access sites. Five values sweep the shape-dispatch accept-set
21077 // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
21078 // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
21079 // `wasi:keyvalue/`).
21080 for (wit, endpoint, subject, slot) in [
21081 ("wasi:http/proxy", Some("/lookup"), None, None),
21082 ("http:proxy", Some("/health"), None, None),
21083 ("nats:pub-sub", None, Some("orders.paid"), None),
21084 ("kafka:events", None, Some("checkout-events"), None),
21085 ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
21086 ] {
21087 let c = WitContract {
21088 de: "cart".into(),
21089 para: "downstream".into(),
21090 wit: wit.into(),
21091 endpoint: endpoint.map(str::to_string),
21092 subject: subject.map(str::to_string),
21093 slot: slot.map(str::to_string),
21094 };
21095 assert_eq!(
21096 c.world_ref(),
21097 wit,
21098 "WitContract::world_ref must return :contratos :wit \
21099 verbatim (got {:?}, expected {wit:?})",
21100 c.world_ref(),
21101 );
21102 assert_eq!(
21103 c.world_ref(),
21104 c.wit.as_str(),
21105 "WitContract::world_ref must byte-equal the .wit field \
21106 access",
21107 );
21108 }
21109 }
21110
21111 #[test]
21112 fn wit_contract_world_ref_borrows_from_wit_storage() {
21113 // The borrow-not-copy pin: [`WitContract::world_ref`] must
21114 // return a `&str` slice that borrows from the typed slot's own
21115 // [`String`] storage — same-address invariant with
21116 // `c.wit.as_str()`. Pins against a future silent detour that
21117 // allocated a fresh `String` (`self.wit.clone()` in the body
21118 // would type-check but silently drop the borrow, and every
21119 // downstream consumer that assumed the returned slice outlives
21120 // `&self` would break on a stale-reference use-after-free — the
21121 // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
21122 // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
21123 // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
21124 // / [`is_pubsub`][WitContract::is_pubsub] /
21125 // [`is_store`][WitContract::is_store] methods route through —
21126 // each borrow from the WitContract's own storage and each would
21127 // silently misbehave if this accessor produced a detached copy).
21128 // Peer of the sibling per-`:contratos` [`WitContract::source`] /
21129 // [`WitContract::destination`] and per-`:entrada`
21130 // [`Entrada::destination`] / [`Entrada::hostname`] and
21131 // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
21132 // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
21133 let c = WitContract {
21134 de: "cart".into(),
21135 para: "catalog".into(),
21136 wit: "wasi:http/proxy".into(),
21137 endpoint: Some("/lookup".into()),
21138 subject: None,
21139 slot: None,
21140 };
21141 let world = c.world_ref();
21142 let wit_slice = c.wit.as_str();
21143 assert_eq!(
21144 world.as_ptr(),
21145 wit_slice.as_ptr(),
21146 "WitContract::world_ref must borrow from the .wit String's \
21147 backing storage — a fresh allocation here means the \
21148 accessor no longer names the substrate-primitive typed \
21149 dispatch and every downstream consumer would silently carry \
21150 a detached copy",
21151 );
21152 assert_eq!(
21153 world.len(),
21154 wit_slice.len(),
21155 "WitContract::world_ref and .wit.as_str() must byte-equal in \
21156 length as well as in address",
21157 );
21158 }
21159
21160 #[test]
21161 fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
21162 // Sibling-triple invariant pin composing all three per-`:contratos`
21163 // substrate-primitive typed dispatches — [`WitContract::source`]
21164 // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
21165 // [`WitContract::world_ref`] — at the joint
21166 // `(source(), destination(), world_ref())` call shape every
21167 // renderer that fans on per-edge caller-callee-shape identity
21168 // keys off. The invariant, evaluated per-contract:
21169 //
21170 // (c.source(), c.destination(), c.world_ref())
21171 // == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
21172 //
21173 // Closes the last unlifted per-`:contratos` scalar axis — every
21174 // downstream consumer that reads the triple now routes through
21175 // exactly three typed dispatches on the substrate primitive,
21176 // not two typed + one open-coded field access. A future refactor
21177 // that silently split any one accessor's projection (an
21178 // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
21179 // canonicalization that didn't reach the peer `source`/
21180 // `destination` arms, an accidental `source()` per-cluster
21181 // caller-alias rewrite that didn't land on the `world_ref` peer)
21182 // surfaces at caixa-core build time. Peer of the sibling per-
21183 // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
21184 // per-`:entrada` `(hostname(), destination())` (6db982c /
21185 // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
21186 // axes, extended to the per-`:contratos` triple.
21187 for (de, para, wit, endpoint, subject, slot) in [
21188 (
21189 "cart",
21190 "catalog",
21191 "wasi:http/proxy",
21192 Some("/lookup"),
21193 None,
21194 None,
21195 ),
21196 (
21197 "checkout",
21198 "orders",
21199 "nats:pub-sub",
21200 None,
21201 Some("orders.paid"),
21202 None,
21203 ),
21204 (
21205 "cart",
21206 "kv",
21207 "wasi:keyvalue/store",
21208 None,
21209 None,
21210 Some("carts/{cart_id}"),
21211 ),
21212 (
21213 "orders-v2",
21214 "inventory-v3",
21215 "http:proxy",
21216 Some("/reserve"),
21217 None,
21218 None,
21219 ),
21220 ] {
21221 let c = WitContract {
21222 de: de.into(),
21223 para: para.into(),
21224 wit: wit.into(),
21225 endpoint: endpoint.map(str::to_string),
21226 subject: subject.map(str::to_string),
21227 slot: slot.map(str::to_string),
21228 };
21229 assert_eq!(
21230 (c.source(), c.destination(), c.world_ref()),
21231 (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
21232 "(WitContract::source, ::destination, ::world_ref) must \
21233 project (.de, .para, .wit) verbatim across every author-\
21234 declared triple (got ({:?}, {:?}, {:?}), expected \
21235 ({de:?}, {para:?}, {wit:?}))",
21236 c.source(),
21237 c.destination(),
21238 c.world_ref(),
21239 );
21240 }
21241 }
21242
21243 #[test]
21244 fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
21245 // The canonical per-`:contratos` owned-form caller-callee-pair
21246 // pin: [`WitContract::edge_pair`] must return the
21247 // `(source(), destination())` tuple in owned form byte-for-byte,
21248 // projected through the lifted [`WitContract::source`] /
21249 // [`WitContract::destination`] scalar accessors. Pins the
21250 // composite-projection invariant on the per-`:contratos`
21251 // mesh-slot atom — every author-declared `(de, para)` pair must
21252 // round-trip verbatim through the substrate primitive's typed
21253 // dispatch, so the nine [`AplicacaoError`] diagnostic-
21254 // construction sites the accessor now feeds
21255 // ([`AplicacaoError::EmptyWit`],
21256 // [`AplicacaoError::ContratoEndpointEmpty`],
21257 // [`AplicacaoError::ContratoEndpointNotAbsolute`],
21258 // [`AplicacaoError::ContratoEndpointInvalid`],
21259 // [`AplicacaoError::ContratoSubjectEmpty`],
21260 // [`AplicacaoError::ContratoSubjectInvalid`],
21261 // [`AplicacaoError::ContratoSlotEmpty`],
21262 // [`AplicacaoError::ContratoSlotInvalid`],
21263 // [`AplicacaoError::ContratoDuplicate`]) all read the same
21264 // `(de, para)` label pair every author sees at the source
21265 // `caixa.lisp`. Pins against a future silent detour that swapped
21266 // the `.0` / `.1` arms (an accidental `(destination(),
21267 // source())` re-order in the body would silently invert every
21268 // downstream diagnostic's `de:` / `para:` label pair, silently
21269 // reversing the direction of every operator-facing typed error
21270 // arrow), a fresh-allocation shape drift (an accidental
21271 // `.to_string()` on one arm but not the other would leave the
21272 // owned/borrowed pair mismatched vs. the sibling `source()` /
21273 // `destination()` returns), or an M4 per-cluster caller/callee-
21274 // alias rewrite that landed on `source()` without reaching
21275 // `destination()` (or vice versa). Peer of the sibling per-
21276 // `:contratos` `(source, destination, world_ref)` triple
21277 // pin above on the mesh-slot-atom scalar-value axes, extended
21278 // to the owned-form pair-projection axis.
21279 for (de, para, wit, endpoint, subject, slot) in [
21280 (
21281 "cart",
21282 "catalog",
21283 "wasi:http/proxy",
21284 Some("/lookup"),
21285 None,
21286 None,
21287 ),
21288 (
21289 "checkout",
21290 "orders",
21291 "nats:pub-sub",
21292 None,
21293 Some("orders.paid"),
21294 None,
21295 ),
21296 (
21297 "cart",
21298 "kv",
21299 "wasi:keyvalue/store",
21300 None,
21301 None,
21302 Some("carts/{cart_id}"),
21303 ),
21304 (
21305 "orders-v2",
21306 "inventory-v3",
21307 "http:proxy",
21308 Some("/reserve"),
21309 None,
21310 None,
21311 ),
21312 ] {
21313 let c = WitContract {
21314 de: de.into(),
21315 para: para.into(),
21316 wit: wit.into(),
21317 endpoint: endpoint.map(str::to_string),
21318 subject: subject.map(str::to_string),
21319 slot: slot.map(str::to_string),
21320 };
21321 assert_eq!(
21322 c.edge_pair(),
21323 (de.to_string(), para.to_string()),
21324 "WitContract::edge_pair must return (:contratos :de, \
21325 :contratos :para) as an owned tuple verbatim (got {:?}, \
21326 expected ({de:?}, {para:?}))",
21327 c.edge_pair(),
21328 );
21329 }
21330 }
21331
21332 #[test]
21333 fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
21334 // The composition pin: [`WitContract::edge_pair`] must return
21335 // exactly `(source().to_string(), destination().to_string())` —
21336 // the owned form of the sibling accessor pair — so any future
21337 // refactor that silently re-authored the caller-arm / callee-arm
21338 // projection to bypass the lifted scalar accessors (an accidental
21339 // `(self.de.clone(), self.para.clone())` regression back to the
21340 // raw field-access shape, an M4-typed-caller-enum `Display`
21341 // re-canonicalization on `source()` that didn't reach
21342 // `edge_pair()`, a per-cluster alias rewrite the operator lands
21343 // on `destination()` without reaching this composite projection)
21344 // trips at caixa-core build time. Pins the "typed dispatch
21345 // composes with typed dispatch, not with raw field access"
21346 // discipline every downstream diagnostic-construction site now
21347 // routes through — a `de:` / `para:` label pair whose
21348 // projection silently drifted off the substrate primitive's
21349 // scalar accessors would silently split the diagnostic's self-
21350 // locating signal from the source `caixa.lisp` author's view.
21351 // Peer of the sibling per-`:politicas` `is_empty` /
21352 // `validate_politicas` accessor-routing-pin family on the M3
21353 // mesh-slot family (18575, 18739, 18918, 19140, 19371).
21354 let c = WitContract {
21355 de: "cart".into(),
21356 para: "catalog".into(),
21357 wit: "wasi:http/proxy".into(),
21358 endpoint: Some("/lookup".into()),
21359 subject: None,
21360 slot: None,
21361 };
21362 assert_eq!(
21363 c.edge_pair(),
21364 (c.source().to_string(), c.destination().to_string()),
21365 "WitContract::edge_pair must compose exactly \
21366 (source().to_string(), destination().to_string()) — a \
21367 bypass of either sibling accessor here would silently \
21368 decouple the composite-projection axis from the \
21369 substrate-primitive scalar accessors every downstream \
21370 consumer routes through",
21371 );
21372 }
21373
21374 #[test]
21375 fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
21376 {
21377 // The canonical per-`:contratos` owned-form
21378 // caller-callee-world-ref-triple pin:
21379 // [`WitContract::edge_triple`] must return the
21380 // `(source(), destination(), world_ref())` tuple in owned form
21381 // byte-for-byte, projected through the lifted
21382 // [`WitContract::source`] / [`WitContract::destination`] /
21383 // [`WitContract::world_ref`] scalar accessors. Pins the
21384 // composite-projection invariant on the per-`:contratos`
21385 // mesh-slot atom — every author-declared `(de, para, wit)`
21386 // triple must round-trip verbatim through the substrate
21387 // primitive's typed dispatch, so the nine
21388 // [`AplicacaoError`] diagnostic-construction sites the
21389 // accessor now feeds (the [`WitTarget`]-dispatch's eight
21390 // wrong-target / missing-target / invalid-wit / capability-
21391 // with-payload arms in [`WitContract::target`], plus the
21392 // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
21393 // diagnostic constructor in [`AplicacaoSpec::validate`]) all
21394 // read the same `(de, para, wit)` triple every author sees at
21395 // the source `caixa.lisp`. Pins against a future silent
21396 // detour that swapped any two arms (an accidental `(destination(),
21397 // source(), world_ref())` re-order in the body would silently
21398 // invert every downstream diagnostic's `de:` / `para:` label
21399 // pair, silently reversing the direction of every operator-
21400 // facing typed error arrow), a fresh-allocation shape drift
21401 // (an accidental `.to_string()` skipped on one arm would leave
21402 // the owned/borrowed triple mismatched vs. the sibling
21403 // `source()` / `destination()` / `world_ref()` returns), or an
21404 // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
21405 // canonicalization pass that landed on one accessor without
21406 // reaching the peers. Peer of the sibling per-`:contratos`
21407 // caller-callee-pair
21408 // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
21409 // pin on the mesh-slot-atom composite-projection axis,
21410 // extended to the triple-projection axis.
21411 for (de, para, wit, endpoint, subject, slot) in [
21412 (
21413 "cart",
21414 "catalog",
21415 "wasi:http/proxy",
21416 Some("/lookup"),
21417 None,
21418 None,
21419 ),
21420 (
21421 "checkout",
21422 "orders",
21423 "nats:pub-sub",
21424 None,
21425 Some("orders.paid"),
21426 None,
21427 ),
21428 (
21429 "cart",
21430 "kv",
21431 "wasi:keyvalue/store",
21432 None,
21433 None,
21434 Some("carts/{cart_id}"),
21435 ),
21436 (
21437 "orders-v2",
21438 "inventory-v3",
21439 "http:proxy",
21440 Some("/reserve"),
21441 None,
21442 None,
21443 ),
21444 ] {
21445 let c = WitContract {
21446 de: de.into(),
21447 para: para.into(),
21448 wit: wit.into(),
21449 endpoint: endpoint.map(str::to_string),
21450 subject: subject.map(str::to_string),
21451 slot: slot.map(str::to_string),
21452 };
21453 assert_eq!(
21454 c.edge_triple(),
21455 (de.to_string(), para.to_string(), wit.to_string()),
21456 "WitContract::edge_triple must return (:contratos :de, \
21457 :contratos :para, :contratos :wit) as an owned triple \
21458 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
21459 c.edge_triple(),
21460 );
21461 }
21462 }
21463
21464 #[test]
21465 fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
21466 // The composition pin: [`WitContract::edge_triple`] must return
21467 // exactly `(source().to_string(), destination().to_string(),
21468 // world_ref().to_string())` — the owned form of the sibling
21469 // scalar-accessor triple — so any future refactor that silently
21470 // re-authored one arm's projection to bypass the lifted scalar
21471 // accessors (an accidental `(self.de.clone(), self.para.clone(),
21472 // self.wit.clone())` regression back to the raw field-access
21473 // shape the internal `edge` closure and the ContratoDuplicate
21474 // diagnostic both carried before this lift landed, an
21475 // M4-typed-caller-enum `Display` re-canonicalization on
21476 // `source()` that didn't reach `edge_triple()`, a per-cluster
21477 // alias rewrite the operator lands on `destination()` /
21478 // `world_ref()` without reaching this composite projection)
21479 // trips at caixa-core build time. Pins the "typed dispatch
21480 // composes with typed dispatch, not with raw field access"
21481 // discipline every downstream diagnostic-construction site now
21482 // routes through — a `de:` / `para:` / `wit:` triple whose
21483 // projection silently drifted off the substrate primitive's
21484 // scalar accessors would silently split the diagnostic's self-
21485 // locating signal from the source `caixa.lisp` author's view.
21486 // Peer of the sibling per-`:contratos` edge_pair composition-
21487 // pin above on the mesh-slot-atom composite-projection axis.
21488 let c = WitContract {
21489 de: "cart".into(),
21490 para: "catalog".into(),
21491 wit: "wasi:http/proxy".into(),
21492 endpoint: Some("/lookup".into()),
21493 subject: None,
21494 slot: None,
21495 };
21496 assert_eq!(
21497 c.edge_triple(),
21498 (
21499 c.source().to_string(),
21500 c.destination().to_string(),
21501 c.world_ref().to_string(),
21502 ),
21503 "WitContract::edge_triple must compose exactly \
21504 (source().to_string(), destination().to_string(), \
21505 world_ref().to_string()) — a bypass of any sibling accessor \
21506 here would silently decouple the composite-projection axis \
21507 from the substrate-primitive scalar accessors every \
21508 downstream consumer routes through",
21509 );
21510 }
21511
21512 #[test]
21513 fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
21514 // The canonical semantics-pin: [`WitContract::edge_triple`] must
21515 // project the full `(de, para, wit)` identity of a `:contratos`
21516 // edge — the sub-triple every triple-carrying
21517 // [`AplicacaoError::Contrato*`] diagnostic weaves into its
21518 // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
21519 // missing-target, capability-with-payload, invalid-wit, and the
21520 // duplicate-gate). Rejects a drift in shape (an accidental
21521 // silent detour that returned a `(de, para)` pair or added an
21522 // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
21523 // would trip here because the return type would no longer
21524 // pattern-match the eight `let (de, para, wit) = edge();`
21525 // destructures the [`WitContract::target`] dispatch feeds off
21526 // + the paired duplicate-gate `let (de, para, wit) =
21527 // c.edge_triple();` destructure in
21528 // [`AplicacaoSpec::validate`]). Peer of the sibling per-
21529 // `:contratos` caller-callee-pair pin above extended to the
21530 // triple projection surface: closes the "one composite
21531 // accessor per typed diagnostic-construction sub-tuple"
21532 // discipline on the per-`:contratos` mesh-slot-atom axis.
21533 let c = WitContract {
21534 de: "checkout".into(),
21535 para: "orders".into(),
21536 wit: "nats:pub-sub".into(),
21537 endpoint: None,
21538 subject: Some("orders.paid".into()),
21539 slot: None,
21540 };
21541 let (de, para, wit) = c.edge_triple();
21542 assert_eq!(de, "checkout");
21543 assert_eq!(para, "orders");
21544 assert_eq!(wit, "nats:pub-sub");
21545 }
21546
21547 #[test]
21548 fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
21549 {
21550 // The composition pin: [`WitContract::identity`] must return
21551 // exactly `(source(), destination(), world_ref(), endpoint(),
21552 // subject(), slot())` — the borrowed form of the six-scalar-
21553 // accessor identity axis. Any future refactor that silently
21554 // re-authored one arm's projection to bypass a scalar accessor
21555 // (a `self.de.as_str()` regression back to raw field access on
21556 // any of the three required arms, a `self.endpoint.as_deref()`
21557 // regression on any of the three optional arms, an M4 per-
21558 // cluster caller/callee-alias rewrite the operator lands on
21559 // `source()` / `destination()` without reaching this composite
21560 // projection) trips at caixa-core build time. Sweeps four
21561 // permutations of the WIT-shape × payload lattice — HTTP with
21562 // endpoint, pub-sub with subject, store with slot, payload-less
21563 // capability — so every payload arm is exercised. Peer of the
21564 // sibling per-`:contratos`
21565 // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
21566 // composition pin on the mesh-slot-atom composite-projection
21567 // axis; extends the discipline from the (de, para, wit) prefix
21568 // onto the full-identity axis carrying the three payload arms.
21569 for (de, para, wit, endpoint, subject, slot) in [
21570 (
21571 "cart",
21572 "catalog",
21573 "wasi:http/proxy",
21574 Some("/lookup"),
21575 None,
21576 None,
21577 ),
21578 (
21579 "checkout",
21580 "orders",
21581 "nats:pub-sub",
21582 None,
21583 Some("orders.paid"),
21584 None,
21585 ),
21586 (
21587 "cart",
21588 "kv",
21589 "wasi:keyvalue/store",
21590 None,
21591 None,
21592 Some("carts/{cart_id}"),
21593 ),
21594 ("audit", "sink", "wasi:logging", None, None, None),
21595 ] {
21596 let c = WitContract {
21597 de: de.into(),
21598 para: para.into(),
21599 wit: wit.into(),
21600 endpoint: endpoint.map(str::to_owned),
21601 subject: subject.map(str::to_owned),
21602 slot: slot.map(str::to_owned),
21603 };
21604 assert_eq!(
21605 c.identity(),
21606 (
21607 c.source(),
21608 c.destination(),
21609 c.world_ref(),
21610 c.endpoint(),
21611 c.subject(),
21612 c.slot(),
21613 ),
21614 "WitContract::identity must compose exactly \
21615 (source(), destination(), world_ref(), endpoint(), \
21616 subject(), slot()) — a bypass of any sibling accessor \
21617 here would silently decouple the identity-projection \
21618 axis from the substrate-primitive scalar accessors \
21619 every dedup-key consumer routes through",
21620 );
21621 }
21622 }
21623
21624 #[test]
21625 fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
21626 // The canonical semantics-pin: [`WitContract::identity`] must
21627 // project the six-axis (de, para, wit, endpoint, subject, slot)
21628 // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21629 // gate keys off — two `WitContract`s that agree on all six axes
21630 // are the same typed edge declared twice, the graph-edge
21631 // analogue of duplicate `:membros` / `:placement :clusters` /
21632 // `:entrada :paths` entries. Rejects a shape drift (an
21633 // accidental silent detour that returned a prefix tuple or
21634 // added an extra field) by pattern-matching the six-arm shape.
21635 // Peer of the sibling per-`:contratos`
21636 // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
21637 // pin extended from the (de, para, wit) prefix onto the full
21638 // six-axis identity that the dedup key rides.
21639 let c = WitContract {
21640 de: "cart".into(),
21641 para: "catalog".into(),
21642 wit: "wasi:http/proxy".into(),
21643 endpoint: Some("/products/:id".into()),
21644 subject: None,
21645 slot: None,
21646 };
21647 let (de, para, wit, endpoint, subject, slot) = c.identity();
21648 assert_eq!(de, "cart");
21649 assert_eq!(para, "catalog");
21650 assert_eq!(wit, "wasi:http/proxy");
21651 assert_eq!(endpoint, Some("/products/:id"));
21652 assert_eq!(subject, None);
21653 assert_eq!(slot, None);
21654
21655 // Two byte-identical contracts must produce equal identities —
21656 // the dedup key's foundational invariant.
21657 let c2 = c.clone();
21658 assert_eq!(c.identity(), c2.identity());
21659
21660 // Any change on any of the six axes must break the identity —
21661 // sweeps by mutating one axis at a time.
21662 let mut mutated = c.clone();
21663 mutated.de = "search".into();
21664 assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
21665 let mut mutated = c.clone();
21666 mutated.para = "warehouse".into();
21667 assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
21668 let mut mutated = c.clone();
21669 mutated.wit = "http:legacy".into();
21670 assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
21671 let mut mutated = c.clone();
21672 mutated.endpoint = Some("/search".into());
21673 assert_ne!(
21674 c.identity(),
21675 mutated.identity(),
21676 "endpoint axis must partition"
21677 );
21678 let mut mutated = c.clone();
21679 mutated.subject = Some("orders.paid".into());
21680 assert_ne!(
21681 c.identity(),
21682 mutated.identity(),
21683 "subject axis must partition"
21684 );
21685 let mut mutated = c;
21686 mutated.slot = Some("carts/{id}".into());
21687 assert_ne!(mutated.identity().5, None, "slot axis must partition");
21688 }
21689
21690 #[test]
21691 fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
21692 // The canonical per-`:contratos` structural-self-edge pin:
21693 // [`WitContract::is_self_loop`] must return `true` when the
21694 // `:de` and `:para` fields agree byte-for-byte, across every
21695 // WIT-shape variant the per-edge shape family carries. Pins
21696 // the shape-agnostic identity-space partition the
21697 // [`AplicacaoSpec::validate`] self-edge gate at
21698 // caixa-core/src/aplicacao.rs:5559 fires against — all four
21699 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
21700 // under the same one predicate. Four permutations sweep the
21701 // accept-set: HTTP with endpoint, pub-sub with subject, KV
21702 // store with slot, and payload-less capability.
21703 for (nome, wit, endpoint, subject, slot) in [
21704 ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
21705 ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
21706 (
21707 "kv",
21708 "wasi:keyvalue/store",
21709 None,
21710 None,
21711 Some("carts/{cart_id}"),
21712 ),
21713 ("audit", "wasi:logging", None, None, None),
21714 ] {
21715 let c = WitContract {
21716 de: nome.into(),
21717 para: nome.into(),
21718 wit: wit.into(),
21719 endpoint: endpoint.map(str::to_string),
21720 subject: subject.map(str::to_string),
21721 slot: slot.map(str::to_string),
21722 };
21723 assert!(
21724 c.is_self_loop(),
21725 "WitContract::is_self_loop must return true when \
21726 :contratos :de == :contratos :para (got false on \
21727 {nome:?} under {wit:?})",
21728 );
21729 }
21730 }
21731
21732 #[test]
21733 fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
21734 // The complement pin: [`WitContract::is_self_loop`] must return
21735 // `false` on every well-shaped inter-Servico contract (the
21736 // author-intended `:contratos` shape MESH-COMPOSITION §III.1
21737 // names — "Servico A calls Servico B" between two distinct
21738 // graph nodes). Pins against a future silent detour that
21739 // inverted the predicate (an accidental `!= ` swap for `==`
21740 // would silently reject every legitimate inter-Servico edge
21741 // and admit every self-edge — the exact inversion of the
21742 // author-intended shape). Four permutations sweep the same
21743 // WIT-shape accept-set the sibling positive-arm test carries.
21744 for (de, para, wit, endpoint, subject, slot) in [
21745 (
21746 "cart",
21747 "catalog",
21748 "wasi:http/proxy",
21749 Some("/lookup"),
21750 None,
21751 None,
21752 ),
21753 (
21754 "checkout",
21755 "orders",
21756 "nats:pub-sub",
21757 None,
21758 Some("orders.paid"),
21759 None,
21760 ),
21761 (
21762 "cart",
21763 "kv",
21764 "wasi:keyvalue/store",
21765 None,
21766 None,
21767 Some("carts/{cart_id}"),
21768 ),
21769 ("audit", "sink", "wasi:logging", None, None, None),
21770 ] {
21771 let c = WitContract {
21772 de: de.into(),
21773 para: para.into(),
21774 wit: wit.into(),
21775 endpoint: endpoint.map(str::to_string),
21776 subject: subject.map(str::to_string),
21777 slot: slot.map(str::to_string),
21778 };
21779 assert!(
21780 !c.is_self_loop(),
21781 "WitContract::is_self_loop must return false when \
21782 :contratos :de differs from :contratos :para (got true \
21783 on {de:?} → {para:?} under {wit:?})",
21784 );
21785 }
21786 }
21787
21788 #[test]
21789 fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
21790 // The composition pin: [`WitContract::is_self_loop`] must
21791 // resolve to exactly `self.source() == self.destination()` —
21792 // the equality probe of the sibling scalar-accessor pair — so
21793 // any future refactor that silently re-authored the predicate
21794 // to bypass the lifted scalar accessors (an accidental
21795 // `self.de == self.para` regression back to the raw field-
21796 // access shape, an M4-typed-caller-enum identity-comparison
21797 // rule that landed on `source()` without reaching
21798 // `destination()`, a per-cluster alias rewrite the operator
21799 // pins on `destination()` without reaching this predicate)
21800 // trips at caixa-core build time. Pins the "typed dispatch
21801 // composes with typed dispatch, not with raw field access"
21802 // discipline the sibling [`WitContract::edge_pair`] /
21803 // [`WitContract::edge_triple`] composite-projection accessors
21804 // already carry, extended onto the per-edge endpoint-equality
21805 // predicate axis. Positive and complement arms both fire.
21806 let self_edge = WitContract {
21807 de: "cart".into(),
21808 para: "cart".into(),
21809 wit: "wasi:http/proxy".into(),
21810 endpoint: Some("/lookup".into()),
21811 subject: None,
21812 slot: None,
21813 };
21814 assert_eq!(
21815 self_edge.is_self_loop(),
21816 self_edge.source() == self_edge.destination(),
21817 "WitContract::is_self_loop must compose exactly \
21818 `source() == destination()` — a bypass of either sibling \
21819 accessor here would silently decouple the endpoint-\
21820 equality predicate from the substrate-primitive scalar \
21821 accessors every downstream consumer routes through",
21822 );
21823 let inter_edge = WitContract {
21824 de: "cart".into(),
21825 para: "catalog".into(),
21826 wit: "wasi:http/proxy".into(),
21827 endpoint: Some("/lookup".into()),
21828 subject: None,
21829 slot: None,
21830 };
21831 assert_eq!(
21832 inter_edge.is_self_loop(),
21833 inter_edge.source() == inter_edge.destination(),
21834 "WitContract::is_self_loop must compose exactly \
21835 `source() == destination()` on the complement arm too",
21836 );
21837 }
21838
21839 #[test]
21840 fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
21841 // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
21842 // pin: [`WitContract::endpoint`] must return the `:contratos
21843 // :endpoint` field byte-for-byte, borrowed from the typed slot's
21844 // own `Option<String>` storage. Peer of the sibling
21845 // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
21846 // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
21847 // mesh-slot `Option<String>` optional-scalar axes — same "the
21848 // substrate-primitive accessor must byte-equal the raw field
21849 // access verbatim across every author-declared value" discipline
21850 // extended to the per-`:contratos` HTTP-payload-carrier arm.
21851 // Pins against a future silent detour that re-canonicalized the
21852 // endpoint (an accidental percent-encoding pass that didn't
21853 // reach the peer field-access site at the dedup key, a per-CR
21854 // fully-qualified prefix rewrite the operator authors on one
21855 // consumer without the other, or an M4 typed-path-template
21856 // `Display` re-canonicalization that silently drifted the
21857 // printer output from the source `caixa.lisp`). Four values
21858 // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
21859 // gate upstream admits (short root-path, dashed, param-shaped,
21860 // deep-hierarchy).
21861 for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
21862 let c = WitContract {
21863 de: "cart".into(),
21864 para: "catalog".into(),
21865 wit: "wasi:http/proxy".into(),
21866 endpoint: Some(endpoint.into()),
21867 subject: None,
21868 slot: None,
21869 };
21870 assert_eq!(
21871 c.endpoint(),
21872 Some(endpoint),
21873 "WitContract::endpoint must return :contratos :endpoint \
21874 verbatim (got {:?}, expected Some({endpoint:?}))",
21875 c.endpoint(),
21876 );
21877 assert_eq!(
21878 c.endpoint(),
21879 c.endpoint.as_deref(),
21880 "WitContract::endpoint must byte-equal the .endpoint \
21881 field's `.as_deref()` projection",
21882 );
21883 }
21884 }
21885
21886 #[test]
21887 fn wit_contract_endpoint_none_when_field_is_none() {
21888 // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
21889 // payload-carrier accessor pin: when the typed slot is absent —
21890 // the canonical shape under a non-HTTP `:wit` world per the
21891 // [`WitContract::target`]-enforced shape ↔ target partition
21892 // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
21893 // carries `:slot`, [`WitTarget::Capability`] carries none) —
21894 // [`WitContract::endpoint`] must return `None`. Pins against a
21895 // future silent detour that projected the absent slot to a
21896 // `Some("")` empty-string default (the canonical `Option<String>`
21897 // → `String` collapse footgun the sibling M2
21898 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21899 // emptiness predicates already guard on the peer M2 typed-slot
21900 // surfaces), a `Some("None")` stringified-None round-trip, or a
21901 // `Some` arm whose contents were derived from a sibling slot (an
21902 // accidental fallback to the `:subject` / `:slot` payload that
21903 // read the pub-sub / store payload into the endpoint axis).
21904 // Three contracts sweep the accept-set every non-HTTP `:wit`
21905 // world lands on — pub-sub NATS, key/value, and payload-less
21906 // capability.
21907 for (wit, subject, slot) in [
21908 ("nats:pub-sub", Some("orders.paid"), None),
21909 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
21910 ("wasi:cli/environment", None, None),
21911 ] {
21912 let c = WitContract {
21913 de: "cart".into(),
21914 para: "downstream".into(),
21915 wit: wit.into(),
21916 endpoint: None,
21917 subject: subject.map(str::to_string),
21918 slot: slot.map(str::to_string),
21919 };
21920 assert!(
21921 c.endpoint().is_none(),
21922 "WitContract::endpoint must return None when the typed \
21923 slot is absent under :wit {wit:?} (got {:?})",
21924 c.endpoint(),
21925 );
21926 assert_eq!(
21927 c.endpoint(),
21928 c.endpoint.as_deref(),
21929 "WitContract::endpoint must byte-equal the .endpoint \
21930 field's `.as_deref()` projection in the absent arm",
21931 );
21932 }
21933 }
21934
21935 #[test]
21936 fn wit_contract_endpoint_borrows_from_endpoint_storage() {
21937 // The borrow-not-copy pin: [`WitContract::endpoint`] must return
21938 // an `Option<&str>` whose `Some` arm borrows from the typed
21939 // slot's own [`String`] storage — same-address invariant with
21940 // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
21941 // detour that allocated a fresh `String`
21942 // (`self.endpoint.clone().map(...)` in the body would type-check
21943 // but silently drop the borrow, and every downstream consumer
21944 // that assumed the returned slice outlives `&self` would break
21945 // on a stale-reference use-after-free — the [`WitContract::target`]
21946 // Http-arm payload extraction rebinds the returned `Option<&str>`
21947 // through `.ok_or_else(...)` and threads the `&str` payload into
21948 // [`WitTarget::Http { endpoint: &'a str }`], the
21949 // [`AplicacaoSpec::validate`] duplicate-`:contratos`
21950 // [`ContratoIdentity`] dedup key threads the returned
21951 // `Option<&str>` into the six-tuple's HTTP arm — each borrow
21952 // from the WitContract's own storage and each would silently
21953 // misbehave if this accessor produced a detached copy). Peer of
21954 // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
21955 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
21956 // shaped optional-scalar axes — first extension of the
21957 // `Option<&str>` borrow-not-copy discipline onto the
21958 // per-`:contratos` HTTP-shaped payload-carrier axis.
21959 let c = WitContract {
21960 de: "cart".into(),
21961 para: "catalog".into(),
21962 wit: "wasi:http/proxy".into(),
21963 endpoint: Some("/lookup".into()),
21964 subject: None,
21965 slot: None,
21966 };
21967 let ep = c.endpoint().expect("Some arm");
21968 let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
21969 assert_eq!(
21970 ep.as_ptr(),
21971 storage_slice.as_ptr(),
21972 "WitContract::endpoint must borrow from the .endpoint \
21973 String's backing storage — a fresh allocation here means \
21974 the accessor no longer names the substrate-primitive typed \
21975 dispatch and every downstream consumer would silently \
21976 carry a detached copy",
21977 );
21978 assert_eq!(
21979 ep.len(),
21980 storage_slice.len(),
21981 "WitContract::endpoint and .endpoint.as_deref() must byte-\
21982 equal in length as well as in address",
21983 );
21984 }
21985
21986 #[test]
21987 fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
21988 // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
21989 // pin: [`WitContract::subject`] must return the `:contratos
21990 // :subject` field byte-for-byte, borrowed from the typed slot's
21991 // own `Option<String>` storage. Peer of the sibling per-`:contratos`
21992 // [`WitContract::endpoint`] (7020470) accessor pin on the M3
21993 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
21994 // optional-scalar axis — same "the substrate-primitive accessor
21995 // must byte-equal the raw field access verbatim across every
21996 // author-declared value" discipline extended to the pub-sub arm.
21997 // Pins against a future silent detour that re-canonicalized the
21998 // subject (an accidental `.to_lowercase()` normalization that
21999 // didn't reach the peer field-access site at the dedup key, a
22000 // per-CR fully-qualified prefix rewrite the operator authors on
22001 // one consumer without the other, or an M4 typed-subject-template
22002 // `Display` re-canonicalization that silently drifted the printer
22003 // output from the source `caixa.lisp`). Four values sweep the
22004 // NATS accept-set every pub-sub author-declared subject lands on
22005 // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
22006 for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
22007 let c = WitContract {
22008 de: "cart".into(),
22009 para: "notifier".into(),
22010 wit: "nats:pub-sub".into(),
22011 endpoint: None,
22012 subject: Some(subject.into()),
22013 slot: None,
22014 };
22015 assert_eq!(
22016 c.subject(),
22017 Some(subject),
22018 "WitContract::subject must return :contratos :subject \
22019 verbatim (got {:?}, expected Some({subject:?}))",
22020 c.subject(),
22021 );
22022 assert_eq!(
22023 c.subject(),
22024 c.subject.as_deref(),
22025 "WitContract::subject must byte-equal the .subject \
22026 field's `.as_deref()` projection",
22027 );
22028 }
22029 }
22030
22031 #[test]
22032 fn wit_contract_subject_none_when_field_is_none() {
22033 // The absent-`:subject` arm of the per-`:contratos` pub-sub-
22034 // shaped payload-carrier accessor pin: when the typed slot is
22035 // absent — the canonical shape under a non-pub-sub `:wit` world
22036 // per the [`WitContract::target`]-enforced shape ↔ target
22037 // partition ([`WitTarget::Http`] carries `:endpoint`,
22038 // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
22039 // carries none) — [`WitContract::subject`] must return `None`.
22040 // Pins against a future silent detour that projected the absent
22041 // slot to a `Some("")` empty-string default (the canonical
22042 // `Option<String>` → `String` collapse footgun the sibling M2
22043 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22044 // emptiness predicates already guard on the peer M2 typed-slot
22045 // surfaces), a `Some("None")` stringified-None round-trip, or a
22046 // `Some` arm whose contents were derived from a sibling slot (an
22047 // accidental fallback to the `:endpoint` / `:slot` payload that
22048 // read the HTTP / store payload into the subject axis). Three
22049 // contracts sweep the accept-set every non-pub-sub `:wit` world
22050 // lands on — HTTP proxy, key/value store, and payload-less
22051 // capability.
22052 for (wit, endpoint, slot) in [
22053 ("wasi:http/proxy", Some("/lookup"), None),
22054 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22055 ("wasi:cli/environment", None, None),
22056 ] {
22057 let c = WitContract {
22058 de: "cart".into(),
22059 para: "downstream".into(),
22060 wit: wit.into(),
22061 endpoint: endpoint.map(str::to_string),
22062 subject: None,
22063 slot: slot.map(str::to_string),
22064 };
22065 assert!(
22066 c.subject().is_none(),
22067 "WitContract::subject must return None when the typed \
22068 slot is absent under :wit {wit:?} (got {:?})",
22069 c.subject(),
22070 );
22071 assert_eq!(
22072 c.subject(),
22073 c.subject.as_deref(),
22074 "WitContract::subject must byte-equal the .subject \
22075 field's `.as_deref()` projection in the absent arm",
22076 );
22077 }
22078 }
22079
22080 #[test]
22081 fn wit_contract_subject_borrows_from_subject_storage() {
22082 // The borrow-not-copy pin: [`WitContract::subject`] must return
22083 // an `Option<&str>` whose `Some` arm borrows from the typed
22084 // slot's own [`String`] storage — same-address invariant with
22085 // `c.subject.as_deref().unwrap()`. Pins against a future silent
22086 // detour that allocated a fresh `String`
22087 // (`self.subject.clone().map(...)` in the body would type-check
22088 // but silently drop the borrow, and every downstream consumer
22089 // that assumed the returned slice outlives `&self` would break
22090 // on a stale-reference use-after-free — the [`WitContract::target`]
22091 // PubSub-arm payload extraction rebinds the returned
22092 // `Option<&str>` through `.ok_or_else(...)` and threads the
22093 // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
22094 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22095 // [`ContratoIdentity`] dedup key threads the returned
22096 // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
22097 // from the WitContract's own storage and each would silently
22098 // misbehave if this accessor produced a detached copy). Peer of
22099 // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
22100 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22101 // shaped optional-scalar axis — second extension of the
22102 // `Option<&str>` borrow-not-copy discipline onto the
22103 // per-`:contratos` payload-carrier family, this time on the
22104 // pub-sub arm.
22105 let c = WitContract {
22106 de: "cart".into(),
22107 para: "notifier".into(),
22108 wit: "nats:pub-sub".into(),
22109 endpoint: None,
22110 subject: Some("orders.paid".into()),
22111 slot: None,
22112 };
22113 let sub = c.subject().expect("Some arm");
22114 let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
22115 assert_eq!(
22116 sub.as_ptr(),
22117 storage_slice.as_ptr(),
22118 "WitContract::subject must borrow from the .subject \
22119 String's backing storage — a fresh allocation here means \
22120 the accessor no longer names the substrate-primitive typed \
22121 dispatch and every downstream consumer would silently \
22122 carry a detached copy",
22123 );
22124 assert_eq!(
22125 sub.len(),
22126 storage_slice.len(),
22127 "WitContract::subject and .subject.as_deref() must byte-\
22128 equal in length as well as in address",
22129 );
22130 }
22131
22132 #[test]
22133 fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
22134 // The canonical per-`:contratos` key/value-store-shaped
22135 // `:slot`-scalar pin: [`WitContract::slot`] must return the
22136 // `:contratos :slot` field byte-for-byte, borrowed from the
22137 // typed slot's own `Option<String>` storage. Peer of the
22138 // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
22139 // [`WitContract::subject`] (90de675) accessor pins on the M3
22140 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22141 // optional-scalar axis — same "the substrate-primitive
22142 // accessor must byte-equal the raw field access verbatim
22143 // across every author-declared value" discipline extended to
22144 // the store arm. Pins against a future silent detour that
22145 // re-canonicalized the slot template (an accidental
22146 // `.to_lowercase()` bucket-prefix normalization that didn't
22147 // reach the peer field-access site at the dedup key, a per-CR
22148 // fully-qualified prefix rewrite the operator authors on one
22149 // consumer without the other, or an M4 typed-key-template
22150 // `Display` re-canonicalization that silently drifted the
22151 // printer output from the source `caixa.lisp`). Four values
22152 // sweep the wasi:keyvalue accept-set every store-shaped
22153 // author-declared slot lands on (flat bucket, single-param
22154 // template, multi-param template, nested-hierarchy template).
22155 for slot in [
22156 "sessions",
22157 "carts/{cart_id}",
22158 "orders/{tenant}/{order_id}",
22159 "cache/tenant-a/orders/{id}",
22160 ] {
22161 let c = WitContract {
22162 de: "cart".into(),
22163 para: "kv".into(),
22164 wit: "wasi:keyvalue/store".into(),
22165 endpoint: None,
22166 subject: None,
22167 slot: Some(slot.into()),
22168 };
22169 assert_eq!(
22170 c.slot(),
22171 Some(slot),
22172 "WitContract::slot must return :contratos :slot \
22173 verbatim (got {:?}, expected Some({slot:?}))",
22174 c.slot(),
22175 );
22176 assert_eq!(
22177 c.slot(),
22178 c.slot.as_deref(),
22179 "WitContract::slot must byte-equal the .slot field's \
22180 `.as_deref()` projection",
22181 );
22182 }
22183 }
22184
22185 #[test]
22186 fn wit_contract_slot_none_when_field_is_none() {
22187 // The absent-`:slot` arm of the per-`:contratos` store-shaped
22188 // payload-carrier accessor pin: when the typed slot is absent —
22189 // the canonical shape under a non-store `:wit` world per the
22190 // [`WitContract::target`]-enforced shape ↔ target partition
22191 // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
22192 // carries `:subject`, [`WitTarget::Capability`] carries none) —
22193 // [`WitContract::slot`] must return `None`. Pins against a
22194 // future silent detour that projected the absent slot to a
22195 // `Some("")` empty-string default (the canonical
22196 // `Option<String>` → `String` collapse footgun the sibling M2
22197 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22198 // emptiness predicates already guard on the peer M2 typed-slot
22199 // surfaces), a `Some("None")` stringified-None round-trip, or
22200 // a `Some` arm whose contents were derived from a sibling
22201 // slot (an accidental fallback to the `:endpoint` / `:subject`
22202 // payload that read the HTTP / pub-sub payload into the store
22203 // axis). Three contracts sweep the accept-set every non-store
22204 // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
22205 // payload-less capability.
22206 for (wit, endpoint, subject) in [
22207 ("wasi:http/proxy", Some("/lookup"), None),
22208 ("nats:pub-sub", None, Some("orders.paid")),
22209 ("wasi:cli/environment", None, None),
22210 ] {
22211 let c = WitContract {
22212 de: "cart".into(),
22213 para: "downstream".into(),
22214 wit: wit.into(),
22215 endpoint: endpoint.map(str::to_string),
22216 subject: subject.map(str::to_string),
22217 slot: None,
22218 };
22219 assert!(
22220 c.slot().is_none(),
22221 "WitContract::slot must return None when the typed \
22222 slot is absent under :wit {wit:?} (got {:?})",
22223 c.slot(),
22224 );
22225 assert_eq!(
22226 c.slot(),
22227 c.slot.as_deref(),
22228 "WitContract::slot must byte-equal the .slot field's \
22229 `.as_deref()` projection in the absent arm",
22230 );
22231 }
22232 }
22233
22234 #[test]
22235 fn wit_contract_slot_borrows_from_slot_storage() {
22236 // The borrow-not-copy pin: [`WitContract::slot`] must return
22237 // an `Option<&str>` whose `Some` arm borrows from the typed
22238 // slot's own [`String`] storage — same-address invariant with
22239 // `c.slot.as_deref().unwrap()`. Pins against a future silent
22240 // detour that allocated a fresh `String`
22241 // (`self.slot.clone().map(...)` in the body would type-check
22242 // but silently drop the borrow, and every downstream consumer
22243 // that assumed the returned slice outlives `&self` would
22244 // break on a stale-reference use-after-free — the
22245 // [`WitContract::target`] Store-arm payload extraction rebinds
22246 // the returned `Option<&str>` through `.ok_or_else(...)` and
22247 // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
22248 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22249 // [`ContratoIdentity`] dedup key threads the returned
22250 // `Option<&str>` into the six-tuple's store arm — each borrow
22251 // from the WitContract's own storage and each would silently
22252 // misbehave if this accessor produced a detached copy). Peer
22253 // of the sibling per-`:contratos` [`WitContract::endpoint`]
22254 // (7020470) / [`WitContract::subject`] (90de675)
22255 // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
22256 // shaped optional-scalar axis — third and final extension of
22257 // the `Option<&str>` borrow-not-copy discipline onto the
22258 // per-`:contratos` payload-carrier family, this time on the
22259 // store arm.
22260 let c = WitContract {
22261 de: "cart".into(),
22262 para: "kv".into(),
22263 wit: "wasi:keyvalue/store".into(),
22264 endpoint: None,
22265 subject: None,
22266 slot: Some("carts/{cart_id}".into()),
22267 };
22268 let slot = c.slot().expect("Some arm");
22269 let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
22270 assert_eq!(
22271 slot.as_ptr(),
22272 storage_slice.as_ptr(),
22273 "WitContract::slot must borrow from the .slot String's \
22274 backing storage — a fresh allocation here means the \
22275 accessor no longer names the substrate-primitive typed \
22276 dispatch and every downstream consumer would silently \
22277 carry a detached copy",
22278 );
22279 assert_eq!(
22280 slot.len(),
22281 storage_slice.len(),
22282 "WitContract::slot and .slot.as_deref() must byte-equal \
22283 in length as well as in address",
22284 );
22285 }
22286
22287 #[test]
22288 fn membro_nome_returns_caixa_byte_equal_across_permutations() {
22289 // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
22290 // [`Membro::nome`] must return the `:membros :caixa` field
22291 // byte-for-byte, borrowed from the typed slot's own [`String`]
22292 // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
22293 // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22294 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22295 // slot-atom scalar-value axes — same "the substrate-primitive
22296 // accessor must byte-equal the raw field access verbatim across
22297 // every author-declared value" discipline extended to the
22298 // per-`:membros` member-identity arm. Pins against a future
22299 // silent detour that re-normalized the member identity (an
22300 // accidental `.to_lowercase()` — every `:membros :caixa` is
22301 // validated as a DNS-1123 label upstream via
22302 // [`validate_membro_caixa`], so any re-normalization is
22303 // redundant + a drift surface between the validator and the
22304 // accessor), a namespace-prefix rewrite (an accidental
22305 // `format!("{namespace}/{caixa}")` per-CR fully-qualified
22306 // rewrite that didn't land on the peer axes), or a per-cluster
22307 // alias stamp the operator authors on one consumer without the
22308 // other. Four values sweep the accept-set the DNS-1123 gate
22309 // upstream admits (short single-word / dashed / v-suffixed
22310 // member names).
22311 for name in ["cart", "checkout", "catalog", "orders-v2"] {
22312 let m = Membro {
22313 caixa: name.into(),
22314 versao: "^0.1".into(),
22315 };
22316 assert_eq!(
22317 m.nome(),
22318 name,
22319 "Membro::nome must return :membros :caixa verbatim \
22320 (got {:?}, expected {name:?})",
22321 m.nome(),
22322 );
22323 assert_eq!(
22324 m.nome(),
22325 m.caixa.as_str(),
22326 "Membro::nome must byte-equal the .caixa field access",
22327 );
22328 }
22329 }
22330
22331 #[test]
22332 fn membro_nome_borrows_from_caixa_storage() {
22333 // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
22334 // slice that borrows from the typed slot's own [`String`]
22335 // storage — same-address invariant with `m.caixa.as_str()`. Pins
22336 // against a future silent detour that allocated a fresh `String`
22337 // (`self.caixa.clone()` in the body would type-check but
22338 // silently drop the borrow, and every downstream consumer that
22339 // assumed the returned slice outlives `&self` would break on a
22340 // stale-reference use-after-free — the `HashSet<&str>` collector
22341 // at [`AplicacaoSpec::validate`]'s `names` seed, the
22342 // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
22343 // [`AplicacaoSpec::detect_sync_cycles`], the
22344 // [`crate::render::insert_first_seen`] dedup key at
22345 // [`AplicacaoSpec::validate_membros`] — each borrow from the
22346 // Membro's own storage and each would silently misbehave if
22347 // this accessor produced a detached copy). Peer of the sibling
22348 // per-`:contratos` [`WitContract::source`] /
22349 // [`WitContract::destination`] and per-`:entrada`
22350 // [`Entrada::destination`] borrow-invariant pins on the mesh-
22351 // slot-atom scalar-value axes.
22352 let m = Membro {
22353 caixa: "checkout".into(),
22354 versao: "^0.1".into(),
22355 };
22356 let name = m.nome();
22357 let caixa_slice = m.caixa.as_str();
22358 assert_eq!(
22359 name.as_ptr(),
22360 caixa_slice.as_ptr(),
22361 "Membro::nome must borrow from the .caixa String's backing \
22362 storage — a fresh allocation here means the accessor no \
22363 longer names the substrate-primitive typed dispatch and \
22364 every downstream consumer would silently carry a detached \
22365 copy",
22366 );
22367 assert_eq!(
22368 name.len(),
22369 caixa_slice.len(),
22370 "Membro::nome and .caixa.as_str() must byte-equal in length \
22371 as well as in address",
22372 );
22373 }
22374
22375 #[test]
22376 fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
22377 // The canonical per-`:membros` member-`:versao`-scalar pin:
22378 // [`Membro::versao_requirement`] must return the
22379 // `:membros :versao` field byte-for-byte, borrowed from the typed
22380 // slot's own [`String`] storage. Sibling of the peer
22381 // `membro_nome_returns_caixa_byte_equal_across_permutations`
22382 // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
22383 // — same "the substrate-primitive accessor must byte-equal the
22384 // raw field access verbatim across every author-declared value"
22385 // discipline extended to the per-`:membros` member-`:versao`
22386 // requirement-string arm. Pins against a future silent detour
22387 // that re-canonicalized the requirement (an accidental
22388 // `.to_string()` via [`parse_requirement`] → [`Display`] round-
22389 // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
22390 // drifted the printer output away from the source `caixa.lisp`,
22391 // an accidental whitespace trim on `"^ 0.1"` that no consumer
22392 // ever produced from the field-access side, an accidental
22393 // per-cluster lacre-projected concrete-version rewrite that
22394 // didn't land on the peer field-access sites). Five values sweep
22395 // the accept-set the shared
22396 // [`crate::render::require_valid_versao_requirement`] gate
22397 // admits (caret / tilde / exact / wildcard / bare-major).
22398 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
22399 let m = Membro {
22400 caixa: "cart".into(),
22401 versao: req.into(),
22402 };
22403 assert_eq!(
22404 m.versao_requirement(),
22405 req,
22406 "Membro::versao_requirement must return :membros :versao \
22407 verbatim (got {:?}, expected {req:?})",
22408 m.versao_requirement(),
22409 );
22410 assert_eq!(
22411 m.versao_requirement(),
22412 m.versao.as_str(),
22413 "Membro::versao_requirement must byte-equal the .versao \
22414 field access",
22415 );
22416 }
22417 }
22418
22419 #[test]
22420 fn membro_versao_requirement_borrows_from_versao_storage() {
22421 // The borrow-not-copy pin: [`Membro::versao_requirement`] must
22422 // return a `&str` slice that borrows from the typed slot's own
22423 // [`String`] storage — same-address invariant with
22424 // `m.versao.as_str()`. Pins against a future silent detour that
22425 // allocated a fresh `String` (`self.versao.clone()` in the body
22426 // would type-check but silently drop the borrow, and every
22427 // downstream consumer that assumed the returned slice outlives
22428 // `&self` would break on a stale-reference use-after-free). Peer
22429 // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22430 // per-`:contratos` [`WitContract::source`] /
22431 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22432 // [`Entrada::destination`] (6db982c) borrow-invariant pins on
22433 // the mesh-slot-atom scalar-value axes.
22434 let m = Membro {
22435 caixa: "checkout".into(),
22436 versao: "^0.1".into(),
22437 };
22438 let req = m.versao_requirement();
22439 let versao_slice = m.versao.as_str();
22440 assert_eq!(
22441 req.as_ptr(),
22442 versao_slice.as_ptr(),
22443 "Membro::versao_requirement must borrow from the .versao \
22444 String's backing storage — a fresh allocation here means \
22445 the accessor no longer names the substrate-primitive typed \
22446 dispatch and every downstream consumer would silently carry \
22447 a detached copy",
22448 );
22449 assert_eq!(
22450 req.len(),
22451 versao_slice.len(),
22452 "Membro::versao_requirement and .versao.as_str() must byte-\
22453 equal in length as well as in address",
22454 );
22455 }
22456
22457 #[test]
22458 fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
22459 // Sibling-pair invariant pin composing both per-`:membros`
22460 // substrate-primitive typed dispatches — [`Membro::nome`]
22461 // (4a32abf) and [`Membro::versao_requirement`] — at the joint
22462 // `(nome(), versao_requirement())` call shape every renderer
22463 // that fans on per-member identity + version pin keys off. The
22464 // invariant, evaluated per-member:
22465 //
22466 // (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
22467 //
22468 // Closes the last unlifted per-`:membros` scalar axis — every
22469 // downstream consumer that reads the pair now routes through
22470 // exactly two typed dispatches on the substrate primitive, not
22471 // one typed + one open-coded field access. A future refactor
22472 // that silently split either accessor's projection (an
22473 // accidental `nome()` namespace-prefix rewrite that didn't
22474 // reach the peer, an accidental `versao_requirement()` lacre-
22475 // projected concrete-version rewrite that didn't land on the
22476 // `nome()` peer) surfaces at caixa-core build time. Peer of the
22477 // sibling per-`:entrada` `(hostname(), destination())` and
22478 // per-`:contratos` `(source(), destination())` pair invariants
22479 // on the mesh-slot-atom scalar-value axes.
22480 for (caixa, versao) in [
22481 ("cart", "^0.1"),
22482 ("checkout", "~0.1.2"),
22483 ("catalog", "0.1.0"),
22484 ("orders-v2", "*"),
22485 ] {
22486 let m = Membro {
22487 caixa: caixa.into(),
22488 versao: versao.into(),
22489 };
22490 assert_eq!(
22491 (m.nome(), m.versao_requirement()),
22492 (m.caixa.as_str(), m.versao.as_str()),
22493 "(Membro::nome, Membro::versao_requirement) must project \
22494 (.caixa, .versao) verbatim across every author-declared \
22495 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
22496 m.nome(),
22497 m.versao_requirement(),
22498 );
22499 }
22500 }
22501
22502 #[test]
22503 fn validate_membros_empty_gate_routes_through_nome_accessor() {
22504 // Composition pin: [`AplicacaoSpec::validate_membros`]'s
22505 // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
22506 // not the raw `.caixa` field access. Structurally: setting
22507 // ONLY the `.caixa` field to `""` on an otherwise-well-formed
22508 // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
22509 // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
22510 // (i.e. the empty string) — so the emptiness predicate the
22511 // refusal arm reaches under is the accessor-projected value,
22512 // not a peer field that would silently drift under a future
22513 // accessor-side rewrite.
22514 //
22515 // Pins against a future silent detour that (a) re-derived the
22516 // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
22517 // instead of `self.nome().is_empty()`, silently disagreeing with
22518 // every peer consumer (the `validate_membro_caixa(m.nome())`
22519 // call one line below, the dedup-key `insert_first_seen(&mut
22520 // seen, m.nome(), …)` two lines below, the emit-side per-
22521 // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
22522 // (b) accessor-side introduced a per-tenant alias arm the
22523 // caller was unaware of, silently rewriting an author-declared
22524 // `:caixa "checkout"` to `""` — the raw-field-access gate
22525 // would fail-open while the accessor-routed peer consumers
22526 // would fail-closed, splitting the diagnostic from the actual
22527 // failure surface.
22528 //
22529 // Peer of the sibling
22530 // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
22531 // (c0110f1) composition pin — same "the shape-gate predicate
22532 // must route through the substrate-primitive typed dispatch"
22533 // discipline extended onto the per-`:membros` empty-`:caixa`
22534 // refusal-arm axis. Closes the last unlifted `.caixa` production-
22535 // code read site on `Membro` — after this converge every
22536 // caixa-core `.caixa` field access outside the accessor's own
22537 // body is either a test-side field-setter (in-module tests
22538 // constructing invalid-shape inputs) or a doc-comment reference.
22539 let mut s = three_member_spec();
22540 s.membros[1].caixa = String::new();
22541 assert!(
22542 s.membros[1].nome().is_empty(),
22543 "Membro::nome must byte-equal the .caixa field access — an \
22544 accessor-side detour that no longer projects the raw field \
22545 would silently split this drift-detection test from the \
22546 validate() refusal arm",
22547 );
22548 assert_eq!(
22549 s.membros[1].nome(),
22550 s.membros[1].caixa.as_str(),
22551 "Membro::nome and .caixa.as_str() must byte-equal on an \
22552 empty-`:caixa` entry — the emptiness gate keys off the \
22553 accessor by construction",
22554 );
22555 assert_eq!(
22556 s.validate().unwrap_err(),
22557 AplicacaoError::MembroCaixaEmpty,
22558 "validate_membros' emptiness gate must fire MembroCaixaEmpty \
22559 on an entry whose accessor-projected `nome()` is empty",
22560 );
22561 }
22562
22563 #[test]
22564 fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
22565 // The canonical per-`:placement` Akka-cluster-sharding
22566 // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
22567 // the `:placement :shard-key` field byte-for-byte, borrowed
22568 // from the typed slot's own `Option<String>` storage. Peer of
22569 // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22570 // per-`:contratos` [`WitContract::source`] /
22571 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22572 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22573 // slot-atom scalar-value axes — same "the substrate-primitive
22574 // accessor must byte-equal the raw field access verbatim across
22575 // every author-declared value" discipline extended to the
22576 // per-`:placement` Akka-cluster-sharding key extractor arm.
22577 // Pins against a future silent detour that re-normalized the
22578 // key (an accidental `.to_lowercase()` — every non-empty
22579 // `:shard-key` is validated as a printable-ASCII single-token
22580 // reference upstream via [`validate_placement_shard_key`], so
22581 // any re-normalization is redundant + a drift surface between
22582 // the validator and the accessor), a per-cluster alias rewrite
22583 // the operator authors on one consumer without the other, or an
22584 // accidental variable-prefix strip (`$tenantId` → `tenantId`)
22585 // that didn't land on the peer field-access sites. Four values
22586 // sweep the accept-set the shape gate admits — bare identifier,
22587 // `$`-prefixed variable, dotted path, `${}`-quoted variable —
22588 // the four canonical Akka-style entity-id extractor shapes the
22589 // future M4 cluster-sharding reconciler hashes.
22590 for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
22591 let p = Placement {
22592 estrategia: PlacementStrategy::Sharded,
22593 clusters: vec!["rio".into()],
22594 affinity: None,
22595 shard_key: Some(key.into()),
22596 };
22597 assert_eq!(
22598 p.shard_key(),
22599 Some(key),
22600 "Placement::shard_key must return :placement :shard-key \
22601 verbatim (got {:?}, expected Some({key:?}))",
22602 p.shard_key(),
22603 );
22604 assert_eq!(
22605 p.shard_key(),
22606 p.shard_key.as_deref(),
22607 "Placement::shard_key must byte-equal the .shard_key \
22608 field's `.as_deref()` projection",
22609 );
22610 }
22611 }
22612
22613 #[test]
22614 fn placement_shard_key_none_when_field_is_none() {
22615 // The absent-`:shard-key` arm of the per-`:placement`
22616 // Akka-cluster-sharding accessor pin: when the typed slot is
22617 // absent — the canonical shape under `:estrategia Replicated` /
22618 // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
22619 // enforced `shard_key.is_some() == matches!(estrategia,
22620 // Sharded)` partition — [`Placement::shard_key`] must return
22621 // `None`. Pins against a future silent detour that projected
22622 // the absent slot to a `Some("")` empty-string default (the
22623 // canonical `Option<String>` → `String` collapse footgun the
22624 // sibling M2 [`crate::LimitsSpec::is_empty`] /
22625 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22626 // already guard on the peer M2 typed-slot surfaces), a
22627 // `Some("None")` stringified-None round-trip, or a `Some` arm
22628 // whose contents were derived from a sibling slot (an
22629 // accidental fallback to `estrategia.as_str()` that read the
22630 // strategy discriminator into the key axis). Two placements
22631 // sweep the accept-set every `validate`-passing non-`Sharded`
22632 // shape lands on — `Replicated` (Erlang/OTP distributed-app
22633 // takeover) and `SingleNode` (single-node hosting).
22634 for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
22635 let p = Placement {
22636 estrategia,
22637 clusters: vec!["rio".into()],
22638 affinity: None,
22639 shard_key: None,
22640 };
22641 assert!(
22642 p.shard_key().is_none(),
22643 "Placement::shard_key must return None when the typed \
22644 slot is absent under :estrategia {estrategia:?} (got {:?})",
22645 p.shard_key(),
22646 );
22647 assert_eq!(
22648 p.shard_key(),
22649 p.shard_key.as_deref(),
22650 "Placement::shard_key must byte-equal the .shard_key \
22651 field's `.as_deref()` projection in the absent arm",
22652 );
22653 }
22654 }
22655
22656 #[test]
22657 fn placement_shard_key_borrows_from_shard_key_storage() {
22658 // The borrow-not-copy pin: [`Placement::shard_key`] must return
22659 // an `Option<&str>` whose `Some` arm borrows from the typed
22660 // slot's own [`String`] storage — same-address invariant with
22661 // `p.shard_key.as_deref().unwrap()`. Pins against a future
22662 // silent detour that allocated a fresh `String`
22663 // (`self.shard_key.clone().map(...)` in the body would type-
22664 // check but silently drop the borrow, and every downstream
22665 // consumer that assumed the returned slice outlives `&self`
22666 // would break on a stale-reference use-after-free — the
22667 // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
22668 // gate's `Some(k)`-bound match arm reads `k: &str` under the
22669 // accessor's return type and would silently misbehave if this
22670 // accessor produced a detached copy). Peer of the sibling
22671 // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
22672 // [`WitContract::source`] / [`WitContract::destination`]
22673 // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
22674 // (6db982c) borrow-invariant pins on the mesh-slot-atom
22675 // scalar-value axes — first extension of the discipline onto
22676 // an `Option<String>`-shaped optional-scalar axis.
22677 let p = Placement {
22678 estrategia: PlacementStrategy::Sharded,
22679 clusters: vec!["rio".into()],
22680 affinity: None,
22681 shard_key: Some("tenantId".into()),
22682 };
22683 let key = p.shard_key().expect("Some arm");
22684 let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
22685 assert_eq!(
22686 key.as_ptr(),
22687 storage_slice.as_ptr(),
22688 "Placement::shard_key must borrow from the .shard_key \
22689 String's backing storage — a fresh allocation here means \
22690 the accessor no longer names the substrate-primitive typed \
22691 dispatch and every downstream consumer would silently \
22692 carry a detached copy",
22693 );
22694 assert_eq!(
22695 key.len(),
22696 storage_slice.len(),
22697 "Placement::shard_key and .shard_key.as_deref() must byte-\
22698 equal in length as well as in address",
22699 );
22700 }
22701
22702 #[test]
22703 fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
22704 // The canonical per-`:placement` M3-Adaptive-compression-hint
22705 // scalar pin: [`Placement::affinity`] must return the
22706 // `:placement :affinity` field byte-for-byte, borrowed from the
22707 // typed slot's own `Option<String>` storage. Peer of the sibling
22708 // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
22709 // pin on the sibling `Option<&str>` optional-scalar axis — same
22710 // "the substrate-primitive accessor must byte-equal the raw
22711 // field access verbatim across every author-declared value"
22712 // discipline extended to the peer per-`:placement` M3-Adaptive-
22713 // compression-hint arm. Pins against a future silent detour
22714 // that re-normalized the hint (an accidental `.to_lowercase()`
22715 // — every `:affinity` is already validated as a DNS-1123 label
22716 // upstream via [`validate_placement_affinity`], so any re-
22717 // normalization is redundant + a drift surface between the
22718 // validator and the accessor), a per-cluster alias rewrite the
22719 // operator authors on one consumer without the other, or an
22720 // accidental hint-family collapse (`low-latency` → `latency`
22721 // that dropped the qualifier prefix). Four values sweep the
22722 // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
22723 // canonical adaptive-compression-weight biases the future M4
22724 // placement engine reads.
22725 for hint in [
22726 "data-locality",
22727 "low-latency",
22728 "high-throughput",
22729 "cost-optimized",
22730 ] {
22731 let p = Placement {
22732 estrategia: PlacementStrategy::Replicated,
22733 clusters: vec!["rio".into()],
22734 affinity: Some(hint.into()),
22735 shard_key: None,
22736 };
22737 assert_eq!(
22738 p.affinity(),
22739 Some(hint),
22740 "Placement::affinity must return :placement :affinity \
22741 verbatim (got {:?}, expected Some({hint:?}))",
22742 p.affinity(),
22743 );
22744 assert_eq!(
22745 p.affinity(),
22746 p.affinity.as_deref(),
22747 "Placement::affinity must byte-equal the .affinity \
22748 field's `.as_deref()` projection",
22749 );
22750 }
22751 }
22752
22753 #[test]
22754 fn placement_affinity_none_when_field_is_none() {
22755 // The absent-`:affinity` arm of the per-`:placement`
22756 // M3-Adaptive-compression-hint accessor pin: when the typed
22757 // slot is absent — the canonical shape of an Aplicacao that
22758 // leaves the compression weighting up to the placement engine's
22759 // cluster-default arm — [`Placement::affinity`] must return
22760 // `None`. Pins against a future silent detour that projected
22761 // the absent slot to a `Some("")` empty-string default (the
22762 // canonical `Option<String>` → `String` collapse footgun the
22763 // sibling M2 [`crate::LimitsSpec::is_empty`] /
22764 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22765 // already guard on the peer M2 typed-slot surfaces), a
22766 // `Some("None")` stringified-None round-trip, a `Some` arm
22767 // whose contents were derived from a sibling slot (an
22768 // accidental fallback to `estrategia.as_str()` that read the
22769 // strategy discriminator into the hint axis), or a
22770 // `Some("default")` implicit-default that would silently biases
22771 // the routing without the author having written one. Three
22772 // placements sweep the accept-set every `validate`-passing
22773 // `:affinity None` shape lands on — one per PlacementStrategy
22774 // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
22775 // with a shard-key), since `:affinity` is orthogonal to
22776 // `:estrategia` in the typed grammar.
22777 for (estrategia, shard_key) in [
22778 (PlacementStrategy::SingleNode, None),
22779 (PlacementStrategy::Replicated, None),
22780 (PlacementStrategy::Sharded, Some("tenantId".to_string())),
22781 ] {
22782 let p = Placement {
22783 estrategia,
22784 clusters: vec!["rio".into()],
22785 affinity: None,
22786 shard_key,
22787 };
22788 assert!(
22789 p.affinity().is_none(),
22790 "Placement::affinity must return None when the typed \
22791 slot is absent under :estrategia {estrategia:?} (got {:?})",
22792 p.affinity(),
22793 );
22794 assert_eq!(
22795 p.affinity(),
22796 p.affinity.as_deref(),
22797 "Placement::affinity must byte-equal the .affinity \
22798 field's `.as_deref()` projection in the absent arm",
22799 );
22800 }
22801 }
22802
22803 #[test]
22804 fn placement_affinity_borrows_from_affinity_storage() {
22805 // The borrow-not-copy pin: [`Placement::affinity`] must return
22806 // an `Option<&str>` whose `Some` arm borrows from the typed
22807 // slot's own [`String`] storage — same-address invariant with
22808 // `p.affinity.as_deref().unwrap()`. Pins against a future
22809 // silent detour that allocated a fresh `String`
22810 // (`self.affinity.clone().map(...)` in the body would type-
22811 // check but silently drop the borrow, and every downstream
22812 // consumer that assumed the returned slice outlives `&self`
22813 // would break on a stale-reference use-after-free — the
22814 // [`AplicacaoSpec::validate_placement`] per-hint value-shape
22815 // gate reads the accessor's `&str` return through the
22816 // [`validate_placement_affinity`] `&str` parameter and would
22817 // silently misbehave if this accessor produced a detached
22818 // copy). Peer of the sibling per-`:placement`
22819 // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
22820 // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
22821 // extends the discipline onto the sibling per-`:placement`
22822 // M3-Adaptive-compression-hint arm.
22823 let p = Placement {
22824 estrategia: PlacementStrategy::Replicated,
22825 clusters: vec!["rio".into()],
22826 affinity: Some("data-locality".into()),
22827 shard_key: None,
22828 };
22829 let hint = p.affinity().expect("Some arm");
22830 let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
22831 assert_eq!(
22832 hint.as_ptr(),
22833 storage_slice.as_ptr(),
22834 "Placement::affinity must borrow from the .affinity \
22835 String's backing storage — a fresh allocation here means \
22836 the accessor no longer names the substrate-primitive typed \
22837 dispatch and every downstream consumer would silently \
22838 carry a detached copy",
22839 );
22840 assert_eq!(
22841 hint.len(),
22842 storage_slice.len(),
22843 "Placement::affinity and .affinity.as_deref() must byte-\
22844 equal in length as well as in address",
22845 );
22846 }
22847
22848 #[test]
22849 fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
22850 // The canonical per-`:placement` distribution-strategy-scalar
22851 // pin: [`Placement::estrategia`] must return the `:placement
22852 // :estrategia` field verbatim as a [`PlacementStrategy`],
22853 // `Copy`-projected from the typed slot's own `PlacementStrategy`
22854 // storage across every variant in the closed accept-set
22855 // (`SingleNode` — Erlang/OTP distributed-app takeover;
22856 // `Replicated` — active-active across every named cluster;
22857 // `Sharded` — Akka-style hash-keyed entity distribution). Pins
22858 // against a future silent detour that re-derived the strategy
22859 // from a peer axis (an accidental fallback to
22860 // `if shard_key.is_some() { Sharded } else { Replicated }`
22861 // collapse that read the shard-key axis into the strategy
22862 // discriminator), a variant remap the operator authors on one
22863 // consumer without the other, or a stale-derive detour that
22864 // substituted [`PlacementStrategy::default`] when the field
22865 // held any explicit variant (which would silently collapse the
22866 // distinction between "author explicitly declared `:estrategia
22867 // Replicated`" and "author omitted the slot and inherited the
22868 // default" the future per-cluster override slot depends on).
22869 // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
22870 // pin on the `Copy`-return `u16` scalar axis — same "the
22871 // substrate-primitive accessor must byte-equal the raw field
22872 // access verbatim across every author-declared value" discipline
22873 // extended onto the per-`:placement` distribution-strategy
22874 // `Copy`-composite-enum scalar axis.
22875 for estrategia in [
22876 PlacementStrategy::SingleNode,
22877 PlacementStrategy::Replicated,
22878 PlacementStrategy::Sharded,
22879 ] {
22880 // Route the paired `:shard-key` fixture-builder through the
22881 // typed cross-slot invariant predicate
22882 // [`PlacementStrategy::requires_shard_key`] rather than the
22883 // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
22884 // arm-identity predicate — same discipline the sibling
22885 // `placement_strategy_variants_round_trip` fixture builder now
22886 // reads through.
22887 let shard_key = estrategia
22888 .requires_shard_key()
22889 .then(|| "tenantId".to_string());
22890 let p = Placement {
22891 estrategia,
22892 clusters: vec!["rio".into()],
22893 affinity: None,
22894 shard_key,
22895 };
22896 assert_eq!(
22897 p.estrategia(),
22898 estrategia,
22899 "Placement::estrategia must return :placement :estrategia \
22900 verbatim (got {:?}, expected {estrategia:?})",
22901 p.estrategia(),
22902 );
22903 assert_eq!(
22904 p.estrategia(),
22905 p.estrategia,
22906 "Placement::estrategia accessor and .estrategia field \
22907 access must byte-equal — the accessor is the substrate-\
22908 primitive typed dispatch every downstream distribution-\
22909 strategy consumer must route through",
22910 );
22911 }
22912 }
22913
22914 #[test]
22915 fn validate_placement_reads_through_lifted_estrategia_accessor() {
22916 // Three-consumer coherence pin: the
22917 // [`AplicacaoSpec::validate_placement`]
22918 // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
22919 // `estrategia:` field (which reads through
22920 // [`Placement::estrategia`] to name the strategy the empty
22921 // `:clusters` list was declared against), the same method's
22922 // `Sharded ↔ non-Sharded` `match` partition dispatch (which
22923 // reads through [`Placement::estrategia`] to fan across the
22924 // shape-gate cascades), and the non-`Sharded`-arm
22925 // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
22926 // `estrategia:` field (which reads through
22927 // [`Placement::estrategia`] to name the strategy the declared-
22928 // but-inert `:shard-key` was authored under) must all key off
22929 // the lifted accessor, so any future rebrand on the typed
22930 // slot's reader shape lands at exactly one place. Pins the
22931 // three-site coherence by exercising each error surface end-
22932 // to-end and asserting the surfaced `estrategia:` field byte-
22933 // equals the accessor's return. Peer of the sibling per-
22934 // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
22935 // pin on the M3 mesh-slot `Copy`-return scalar axis.
22936
22937 // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
22938 // whose `estrategia:` field must byte-equal the accessor's return
22939 // for every variant in the closed accept-set.
22940 for estrategia in [
22941 PlacementStrategy::SingleNode,
22942 PlacementStrategy::Replicated,
22943 PlacementStrategy::Sharded,
22944 ] {
22945 let mut spec = three_member_spec();
22946 spec.placement.estrategia = estrategia;
22947 spec.placement.clusters = Vec::new();
22948 // Route the paired `:shard-key` spec-mutator through the typed
22949 // cross-slot invariant predicate
22950 // [`PlacementStrategy::requires_shard_key`] rather than the
22951 // [`gen_platform::IsVariant`]-derived
22952 // [`PlacementStrategy::is_sharded`] arm-identity predicate —
22953 // same discipline the sibling
22954 // `placement_strategy_variants_round_trip` and
22955 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
22956 // fixture builders now read through.
22957 spec.placement.shard_key = estrategia
22958 .requires_shard_key()
22959 .then(|| "tenantId".to_string());
22960 let err = spec.validate().unwrap_err();
22961 match err {
22962 AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
22963 assert_eq!(
22964 e,
22965 spec.placement.estrategia(),
22966 "PlacementWithoutClusters.estrategia must byte-equal \
22967 Placement::estrategia() — the error carrier reads \
22968 through the lifted accessor",
22969 );
22970 }
22971 other => panic!(
22972 "expected PlacementWithoutClusters, got {other:?} for \
22973 estrategia={estrategia:?}"
22974 ),
22975 }
22976 }
22977
22978 // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
22979 // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
22980 // must byte-equal the accessor's return for both non-`Sharded`
22981 // strategies.
22982 for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
22983 let mut spec = three_member_spec();
22984 spec.placement.estrategia = estrategia;
22985 spec.placement.shard_key = Some("tenantId".into());
22986 let err = spec.validate().unwrap_err();
22987 match err {
22988 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
22989 assert_eq!(
22990 e,
22991 spec.placement.estrategia(),
22992 "ShardKeyOnNonSharded.estrategia must byte-equal \
22993 Placement::estrategia() — the non-Sharded-arm \
22994 refusal reads through the lifted accessor",
22995 );
22996 }
22997 other => panic!(
22998 "expected ShardKeyOnNonSharded, got {other:?} for \
22999 estrategia={estrategia:?}"
23000 ),
23001 }
23002 }
23003 }
23004
23005 // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
23006 //
23007 // The [`Placement::clusters`] accessor lift is the second slice-return
23008 // (`&[T]`) accessor on any typed slot — sibling to the seed M2
23009 // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
23010 // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
23011 // below cover (1) the accessor's byte-equal projection against the raw
23012 // field access across the empty / singleton / cohort fixtures the
23013 // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
23014 // and the per-cluster validate loop fan between, and (2) the two-
23015 // consumer coherence of the paired pre-flight refusal probe and the
23016 // per-cluster validate loop routing through the accessor on both arms.
23017
23018 #[test]
23019 fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
23020 // The canonical per-`:placement` cluster-pool-scalar-shape pin:
23021 // [`Placement::clusters`] must return the `:placement :clusters`
23022 // typed `Vec<String>` verbatim as a `&[String]` slice-view over
23023 // the same backing buffer the raw `self.clusters.as_slice()`
23024 // field access borrows from, byte-equal across every
23025 // representative fixture in the accept-set — the empty slice
23026 // (the pre-validation sentinel every
23027 // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
23028 // the singleton slice (the minimal `SingleNode`-shape cohort),
23029 // and multi-entry cohorts (the peer `Replicated` / `Sharded`
23030 // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
23031 //
23032 // Pins against a future silent detour that returned
23033 // `&Vec<String>` (which would type-check but leak the storage-
23034 // side `Vec`'s grow/push/reserve surface no consumer of the
23035 // typed view reaches for), a fresh-allocated `Vec<String>` copy
23036 // (which would type-check via a coercion but silently break
23037 // every downstream caller that relied on the slice sharing the
23038 // backing buffer's identity), or an out-of-order or length-
23039 // drifted projection (which would silently split the paired
23040 // pre-flight `.is_empty()` refusal probe's input from the per-
23041 // cluster validate loop's traversal input).
23042 //
23043 // Peer of the sibling M2
23044 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23045 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23046 // `:supervisor` static-child-list axis, extended onto the M3
23047 // per-`:placement` distribution-target-list `Vec`-carry axis.
23048 let fixtures: Vec<Vec<String>> = vec![
23049 Vec::new(),
23050 vec!["rio".into()],
23051 vec!["rio".into(), "mar".into()],
23052 vec!["rio".into(), "mar".into(), "plo".into()],
23053 ];
23054 for clusters in fixtures {
23055 let p = Placement {
23056 clusters: clusters.clone(),
23057 ..Placement::default()
23058 };
23059 assert_eq!(
23060 p.clusters(),
23061 clusters.as_slice(),
23062 "Placement::clusters must return :placement :clusters \
23063 verbatim (got {:?}, expected {:?})",
23064 p.clusters(),
23065 clusters.as_slice(),
23066 );
23067 assert_eq!(
23068 p.clusters(),
23069 p.clusters.as_slice(),
23070 "Placement::clusters accessor and .clusters.as_slice() \
23071 field access must byte-equal — the accessor is the \
23072 substrate-primitive typed dispatch every downstream \
23073 cluster-pool consumer must route through",
23074 );
23075 assert_eq!(
23076 p.clusters().len(),
23077 p.clusters.len(),
23078 "Placement::clusters().len() must byte-equal \
23079 self.clusters.len() — a length-drift would silently \
23080 split the paired pre-flight `.is_empty()` refusal \
23081 probe input from the per-cluster validate loop's \
23082 traversal input",
23083 );
23084 }
23085 }
23086
23087 #[test]
23088 fn validate_placement_reads_through_lifted_clusters_accessor() {
23089 // Two-consumer coherence pin: the
23090 // [`AplicacaoSpec::validate_placement`] pre-flight
23091 // `self.placement.clusters().is_empty()` refusal probe (which
23092 // must trip [`AplicacaoError::PlacementWithoutClusters`] when
23093 // the accessor projects the empty slice) and the per-cluster
23094 // validate loop's `for c in self.placement.clusters()`
23095 // traversal (which must reach every entry in the same order
23096 // the accessor projects, so both the per-entry value-shape
23097 // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
23098 // and the duplicate-detection HashSet insert that trips
23099 // [`AplicacaoError::PlacementClusterDuplicate`] key off the
23100 // accessor's projection) must both key off the lifted
23101 // accessor, so any future rebrand on the typed slot's reader
23102 // shape lands at exactly one place. Pins the two-site
23103 // coherence by exercising each production consumer end-to-end:
23104 // (1) the `PlacementWithoutClusters` refusal under the empty
23105 // slice, (2) the `PlacementClusterInvalid` refusal fires on
23106 // the second entry of a two-cluster cohort whose head is
23107 // valid but tail is not (which requires the loop to reach the
23108 // second entry through the accessor), and (3) the
23109 // `PlacementClusterDuplicate` refusal fires on the second
23110 // entry of a two-cluster cohort that shares a name (which
23111 // requires the loop to reach both entries — a first-entry-only
23112 // projection would silently pass since the dedup HashSet has
23113 // room for the first insert).
23114 //
23115 // Peer of the sibling M2
23116 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23117 // (bc92bce) coherence pin on the per-`:supervisor` static-
23118 // child-list axis, extended onto the M3 per-`:placement`
23119 // distribution-target-list `Vec`-carry axis.
23120
23121 // (1) Pre-flight `.is_empty()` probe: the empty slice must
23122 // trip `PlacementWithoutClusters`.
23123 let mut spec = three_member_spec();
23124 spec.placement.clusters = Vec::new();
23125 match spec.validate().unwrap_err() {
23126 AplicacaoError::PlacementWithoutClusters { .. } => {}
23127 other => panic!("expected PlacementWithoutClusters, got {other:?}"),
23128 }
23129 assert!(
23130 spec.placement.clusters().is_empty(),
23131 "the pre-flight refusal input must be the empty slice per \
23132 the accessor's projection",
23133 );
23134
23135 // (2) Per-cluster validate loop: a two-cluster cohort with an
23136 // invalid tail entry must trip `PlacementClusterInvalid` on
23137 // the tail — the loop must reach the second entry through
23138 // the accessor.
23139 let mut spec = three_member_spec();
23140 spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
23141 match spec.validate().unwrap_err() {
23142 AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
23143 assert_eq!(
23144 cluster, "BAD_CLUSTER",
23145 "PlacementClusterInvalid.cluster must carry the \
23146 tail entry the loop reached through the accessor",
23147 );
23148 }
23149 other => panic!("expected PlacementClusterInvalid, got {other:?}"),
23150 }
23151 assert_eq!(
23152 spec.placement.clusters().len(),
23153 2,
23154 "the per-cluster validate loop's traversal input must be \
23155 a two-element slice per the accessor's projection",
23156 );
23157
23158 // (3) Per-cluster validate loop: a two-cluster cohort that
23159 // shares a name must trip `PlacementClusterDuplicate` on the
23160 // second entry — the loop must reach both entries through the
23161 // accessor for the dedup HashSet's second insert to collide.
23162 let mut spec = three_member_spec();
23163 spec.placement.clusters = vec!["rio".into(), "rio".into()];
23164 match spec.validate().unwrap_err() {
23165 AplicacaoError::PlacementClusterDuplicate { cluster } => {
23166 assert_eq!(
23167 cluster, "rio",
23168 "PlacementClusterDuplicate.cluster must carry the \
23169 shared cluster name verbatim",
23170 );
23171 }
23172 other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
23173 }
23174 assert_eq!(
23175 spec.placement.clusters().len(),
23176 2,
23177 "the per-cluster validate loop's traversal input must be \
23178 a two-element slice per the accessor's projection",
23179 );
23180 }
23181
23182 #[test]
23183 fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
23184 // The canonical per-`:membros` member-list-slice-shape pin:
23185 // [`AplicacaoSpec::membros`] must return the `:membros` typed
23186 // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
23187 // same backing buffer the raw `self.membros.as_slice()` field
23188 // access borrows from, byte-equal across every representative
23189 // fixture in the accept-set — the empty slice (the pre-
23190 // validation sentinel every [`AplicacaoError::NoMembros`]
23191 // refusal keys off), the singleton slice (the minimal one-
23192 // Servico Aplicacao shape), and multi-entry cohorts (the peer
23193 // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
23194 // load-bearing identity of the application graph).
23195 //
23196 // Pins against a future silent detour that returned
23197 // `&Vec<Membro>` (which would type-check but leak the storage-
23198 // side `Vec`'s grow/push/reserve surface no consumer of the
23199 // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
23200 // (which would type-check via a coercion but silently break
23201 // every downstream caller that relied on the slice sharing the
23202 // backing buffer's identity), or an out-of-order or length-
23203 // drifted projection (which would silently split the paired
23204 // `HashSet<&str>` name-set seed's collect input from the
23205 // pre-flight `.is_empty()` refusal probe's input from the per-
23206 // member validate loop's traversal input from the
23207 // programs.yaml emitter's per-entry fan-out loop's input from
23208 // the `feira app graph` per-member print traversal's input).
23209 //
23210 // Peer of the sibling M2
23211 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23212 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23213 // `:supervisor` static-child-list axis and the sibling M3
23214 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23215 // (a6e18d7) `&[String]` byte-equal pin on the per-
23216 // `:placement` distribution-target-list axis — extends the
23217 // slice-return-accessor byte-equal-projection discipline onto
23218 // the outermost M3 mesh-slot type's per-Aplicacao member-list
23219 // `Vec`-carry axis.
23220 let fixtures: Vec<Vec<Membro>> = vec![
23221 Vec::new(),
23222 vec![membro("catalog", "^0.1")],
23223 vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23224 vec![
23225 membro("catalog", "^0.1"),
23226 membro("cart", "^0.1"),
23227 membro("payment", "^0.2"),
23228 ],
23229 ];
23230 for membros in fixtures {
23231 let s = AplicacaoSpec {
23232 membros: membros.clone(),
23233 contratos: Vec::new(),
23234 politicas: MeshPolicy::default(),
23235 placement: Placement::default(),
23236 entrada: None,
23237 };
23238 assert_eq!(
23239 s.membros(),
23240 membros.as_slice(),
23241 "AplicacaoSpec::membros must return :membros verbatim \
23242 (got {:?}, expected {:?})",
23243 s.membros(),
23244 membros.as_slice(),
23245 );
23246 assert_eq!(
23247 s.membros(),
23248 s.membros.as_slice(),
23249 "AplicacaoSpec::membros accessor and .membros.as_slice() \
23250 field access must byte-equal — the accessor is the \
23251 substrate-primitive typed dispatch every downstream \
23252 member-list consumer must route through",
23253 );
23254 assert_eq!(
23255 s.membros().len(),
23256 s.membros.len(),
23257 "AplicacaoSpec::membros().len() must byte-equal \
23258 self.membros.len() — a length-drift would silently \
23259 split the paired `HashSet<&str>` name-set seed's \
23260 collect input from the pre-flight `.is_empty()` \
23261 refusal probe input from the per-member validate \
23262 loop's traversal input",
23263 );
23264 }
23265 }
23266
23267 #[test]
23268 fn validate_reads_through_lifted_membros_accessor() {
23269 // Three-consumer coherence pin: the
23270 // [`AplicacaoSpec::validate_membros`] pre-flight
23271 // `self.membros().is_empty()` refusal probe (which must trip
23272 // [`AplicacaoError::NoMembros`] when the accessor projects the
23273 // empty slice), the same method's per-member validate loop's
23274 // `for m in self.membros()` traversal (which must reach every
23275 // entry in the same order the accessor projects, so both the
23276 // per-entry empty-`:caixa` gate that trips
23277 // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
23278 // detection `insert_first_seen` that trips
23279 // [`AplicacaoError::MembroDuplicate`] key off the accessor's
23280 // projection), and the peer [`AplicacaoSpec::validate`]'s
23281 // `HashSet<&str>` name-set seed's
23282 // `self.membros().iter().map(Membro::nome).collect()` collect
23283 // input (which every `:contratos` `:de` / `:para` membership
23284 // lookup rejects an unknown name against) must all three key
23285 // off the lifted accessor, so any future rebrand on the typed
23286 // slot's reader shape lands at exactly one place. Pins the
23287 // three-site coherence by exercising each production consumer
23288 // end-to-end: (1) the `NoMembros` refusal under the empty
23289 // slice, (2) the `MembroCaixaEmpty` refusal fires on the
23290 // second entry of a two-member cohort whose head is valid but
23291 // tail has an empty `:caixa` (which requires the loop to
23292 // reach the second entry through the accessor), and (3) the
23293 // `MembroDuplicate` refusal fires on the second entry of a
23294 // two-member cohort that shares a `:caixa` name (which
23295 // requires the loop to reach both entries through the
23296 // accessor for the dedup HashSet's second insert to collide).
23297 //
23298 // Peer of the sibling M2
23299 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23300 // (bc92bce) coherence pin on the per-`:supervisor` static-
23301 // child-list axis and the sibling M3
23302 // `validate_placement_reads_through_lifted_clusters_accessor`
23303 // (a6e18d7) coherence pin on the per-`:placement` distribution-
23304 // target-list axis — extends the slice-return-accessor
23305 // multi-consumer coherence discipline onto the outermost M3
23306 // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
23307
23308 // (1) Pre-flight `.is_empty()` probe: the empty slice must
23309 // trip `NoMembros`.
23310 let mut spec = three_member_spec();
23311 spec.membros = Vec::new();
23312 assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
23313 assert!(
23314 spec.membros().is_empty(),
23315 "the pre-flight refusal input must be the empty slice per \
23316 the accessor's projection",
23317 );
23318
23319 // (2) Per-member validate loop: a two-member cohort with an
23320 // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
23321 // the tail — the loop must reach the second entry through
23322 // the accessor.
23323 let mut spec = three_member_spec();
23324 spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
23325 assert_eq!(
23326 spec.validate().unwrap_err(),
23327 AplicacaoError::MembroCaixaEmpty,
23328 );
23329 assert_eq!(
23330 spec.membros().len(),
23331 2,
23332 "the per-member validate loop's traversal input must be \
23333 a two-element slice per the accessor's projection",
23334 );
23335
23336 // (3) Per-member validate loop: a two-member cohort that
23337 // shares a `:caixa` name must trip `MembroDuplicate` on the
23338 // second entry — the loop must reach both entries through the
23339 // accessor for the dedup HashSet's second insert to collide.
23340 let mut spec = three_member_spec();
23341 spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
23342 match spec.validate().unwrap_err() {
23343 AplicacaoError::MembroDuplicate { caixa } => {
23344 assert_eq!(
23345 caixa, "catalog",
23346 "MembroDuplicate.caixa must carry the shared \
23347 member name verbatim",
23348 );
23349 }
23350 other => panic!("expected MembroDuplicate, got {other:?}"),
23351 }
23352 assert_eq!(
23353 spec.membros().len(),
23354 2,
23355 "the per-member validate loop's traversal input must be \
23356 a two-element slice per the accessor's projection",
23357 );
23358 }
23359
23360 #[test]
23361 fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
23362 // The canonical per-`:contratos` contract-list-slice-shape pin:
23363 // [`AplicacaoSpec::contratos`] must return the `:contratos`
23364 // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
23365 // slice-view over the same backing buffer the raw
23366 // `self.contratos.as_slice()` field access borrows from, byte-
23367 // equal across every representative fixture in the accept-set —
23368 // the empty slice (the pre-validation "internal-only mesh" shape
23369 // an Aplicacao whose members exchange no typed edges renders
23370 // through), the singleton slice (the minimal one-edge Aplicacao
23371 // shape), and multi-entry cohorts (the peer multi-edge shapes
23372 // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
23373 // of the application graph).
23374 //
23375 // Pins against a future silent detour that returned
23376 // `&Vec<WitContract>` (which would type-check but leak the
23377 // storage-side `Vec`'s grow/push/reserve surface no consumer of
23378 // the typed view reaches for), a fresh-allocated
23379 // `Vec<WitContract>` copy (which would type-check via a coercion
23380 // but silently break every downstream caller that relied on the
23381 // slice sharing the backing buffer's identity), or an out-of-
23382 // order or length-drifted projection (which would silently split
23383 // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
23384 // seed's traversal input from the `detect_sync_cycles` per-edge
23385 // adjacency-list seed's traversal input from the
23386 // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
23387 // BTreeMap grouping loop's traversal input from the
23388 // `feira app graph` per-contract print traversal's input).
23389 //
23390 // Peer of the immediately-adjacent sibling M3
23391 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23392 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23393 // node-list axis, the sibling M3
23394 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23395 // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
23396 // distribution-target-list axis, and the sibling M2
23397 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23398 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23399 // `:supervisor` static-child-list axis — extends the slice-
23400 // return-accessor byte-equal-projection discipline onto the
23401 // outermost M3 mesh-slot type's per-Aplicacao contract-list
23402 // `Vec`-carry axis, closing the last unlifted per-
23403 // `AplicacaoSpec` `Vec`-carry axis.
23404 let fixtures: Vec<Vec<WitContract>> = vec![
23405 Vec::new(),
23406 vec![contract_http("cart", "catalog", "/products/:id")],
23407 vec![
23408 contract_http("cart", "catalog", "/products/:id"),
23409 contract_http("cart", "payment", "/charge"),
23410 ],
23411 vec![
23412 contract_http("cart", "catalog", "/products/:id"),
23413 contract_http("cart", "payment", "/charge"),
23414 contract_http("payment", "catalog", "/audit"),
23415 ],
23416 ];
23417 for contratos in fixtures {
23418 let s = AplicacaoSpec {
23419 membros: vec![
23420 membro("catalog", "^0.1"),
23421 membro("cart", "^0.1"),
23422 membro("payment", "^0.2"),
23423 ],
23424 contratos: contratos.clone(),
23425 politicas: MeshPolicy::default(),
23426 placement: Placement::default(),
23427 entrada: None,
23428 };
23429 assert_eq!(
23430 s.contratos(),
23431 contratos.as_slice(),
23432 "AplicacaoSpec::contratos must return :contratos verbatim \
23433 (got {:?}, expected {:?})",
23434 s.contratos(),
23435 contratos.as_slice(),
23436 );
23437 assert_eq!(
23438 s.contratos(),
23439 s.contratos.as_slice(),
23440 "AplicacaoSpec::contratos accessor and \
23441 .contratos.as_slice() field access must byte-equal — \
23442 the accessor is the substrate-primitive typed dispatch \
23443 every downstream contract-list consumer must route \
23444 through",
23445 );
23446 assert_eq!(
23447 s.contratos().len(),
23448 s.contratos.len(),
23449 "AplicacaoSpec::contratos().len() must byte-equal \
23450 self.contratos.len() — a length-drift would silently \
23451 split the paired per-edge validate-loop's traversal \
23452 input from the sync-cycle adjacency-list seed's \
23453 traversal input from the cilium_network_policies \
23454 per-`(:de, :para)` BTreeMap grouping loop's traversal \
23455 input from the `feira app graph` per-contract print \
23456 traversal's input",
23457 );
23458 }
23459 }
23460
23461 #[test]
23462 fn validate_reads_through_lifted_contratos_accessor() {
23463 // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
23464 // per-`:contratos` validate-loop's `for c in self.contratos()`
23465 // traversal (which must reach every entry in the same order the
23466 // accessor projects, so both the per-entry
23467 // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
23468 // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
23469 // dedup `HashSet` insert key off the accessor's projection),
23470 // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
23471 // `for c in self.contratos()` adjacency-list seed (which drives
23472 // the sync-subgraph deadlock-detection gate via
23473 // [`AplicacaoError::SyncCycle`]), and the peer
23474 // [`caixa_mesh::cilium_network_policies`]'s
23475 // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
23476 // grouping loop (which drives the per-CNP fan-out) must all
23477 // three key off the lifted accessor, so any future rebrand on
23478 // the typed slot's reader shape lands at exactly one place. Pins
23479 // the three-site coherence by exercising the two caixa-core
23480 // production consumers end-to-end: (1) the empty-`:contratos`
23481 // slice must validate without a per-edge diagnostic (the
23482 // per-edge loop is a no-op under the empty projection), (2) the
23483 // `ContratoMemberMissing` refusal fires on the second entry of a
23484 // two-edge cohort whose head references a valid member but tail
23485 // references a phantom name (which requires the loop to reach
23486 // the second entry through the accessor), and (3) the
23487 // `SyncCycle` refusal fires on a self-referential two-edge
23488 // cohort through the sync-cycle detector's peer projection
23489 // (which requires the detector to iterate the accessor's
23490 // projection to add the back-edge to its adjacency list).
23491 //
23492 // Peer of the sibling M3
23493 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23494 // three-consumer coherence pin on the per-`:membros` node-list
23495 // axis and the sibling M3
23496 // `validate_placement_reads_through_lifted_clusters_accessor`
23497 // (a6e18d7) coherence pin on the per-`:placement` distribution-
23498 // target-list axis — extends the slice-return-accessor multi-
23499 // consumer coherence discipline onto the outermost M3 mesh-slot
23500 // type's per-Aplicacao contract-list `Vec`-carry axis.
23501
23502 // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
23503 // and no per-edge diagnostic surfaces. Validate succeeds on
23504 // the well-formed `:membros` head.
23505 let mut spec = three_member_spec();
23506 spec.contratos = Vec::new();
23507 assert!(
23508 spec.validate().is_ok(),
23509 "empty :contratos must validate — the per-edge loop is a \
23510 no-op under the accessor's empty projection",
23511 );
23512 assert!(
23513 spec.contratos().is_empty(),
23514 "the per-edge validate loop's traversal input must be the \
23515 empty slice per the accessor's projection",
23516 );
23517
23518 // (2) Per-edge validate loop: a two-edge cohort whose tail
23519 // references a phantom `:para` member must trip
23520 // `ContratoMemberMissing` on the tail — the loop must reach
23521 // the second entry through the accessor for the membership
23522 // lookup to fail on the phantom name.
23523 let mut spec = three_member_spec();
23524 spec.contratos = vec![
23525 contract_http("cart", "catalog", "/products/:id"),
23526 contract_http("cart", "phantom", "/x"),
23527 ];
23528 let err = spec.validate().unwrap_err();
23529 assert!(
23530 matches!(
23531 err,
23532 AplicacaoError::ContratoMemberMissing { ref caixa }
23533 if caixa == "phantom"
23534 ),
23535 "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
23536 );
23537 assert_eq!(
23538 spec.contratos().len(),
23539 2,
23540 "the per-edge validate loop's traversal input must be \
23541 a two-element slice per the accessor's projection",
23542 );
23543
23544 // (3) Sync-cycle detector: a two-edge synchronous cohort
23545 // whose second edge closes the sync-subgraph back onto the
23546 // first must trip [`AplicacaoError::ContratoCycle`] — the
23547 // detector must iterate the accessor's projection to add
23548 // both edges to its adjacency list, so a length-drift on
23549 // the accessor's projection would silently disagree with
23550 // the sync-cycle detector on which edge closes the loop.
23551 // Peer projection to the `validate` per-edge loop above:
23552 // the sync-cycle detector routes through the same lifted
23553 // accessor, so a rebrand of the reader shape lands at one
23554 // place. Uses a two-edge cohort (cart → catalog → cart)
23555 // because the per-edge `ContratoSelfLoop` gate fires before
23556 // the sync-cycle detector on a single self-referential edge
23557 // (`cart → cart`) — the cycle-detector's input must be a
23558 // multi-edge cohort for its per-edge traversal input to be
23559 // observably wider than the per-edge validate loop's input.
23560 let mut spec = three_member_spec();
23561 spec.contratos = vec![
23562 contract_http("cart", "catalog", "/products/:id"),
23563 contract_http("catalog", "cart", "/callback"),
23564 ];
23565 let err = spec.validate().unwrap_err();
23566 assert!(
23567 matches!(err, AplicacaoError::ContratoCycle { .. }),
23568 "expected ContratoCycle from the sync-cycle detector on a \
23569 two-edge back-edge cohort, got {err:?}",
23570 );
23571 assert_eq!(
23572 spec.contratos().len(),
23573 2,
23574 "the sync-cycle detector's traversal input must be a \
23575 two-element slice per the accessor's projection",
23576 );
23577 }
23578
23579 #[test]
23580 fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
23581 // The canonical per-`:politicas` outer-composite-reference-shape
23582 // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
23583 // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
23584 // the same backing storage the raw `&self.politicas` field
23585 // access borrows from, byte-equal across every representative
23586 // fixture in the accept-set — the default `MeshPolicy` (the
23587 // author-empty "no policy on any axis" shape whose
23588 // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
23589 // shapes carrying one axis at a time
23590 // (`{mtls_required, timeout, retries, circuit_breaker,
23591 // rate_limit}` — the minimal five-axis fan-out over the
23592 // per-axis lifted accessor family every downstream mesh-artifact
23593 // emitter dispatches on), and the multi-axis composite (the
23594 // canonical `three_member_spec` fixture's `{timeout, retries,
23595 // mtls_required}` triple — the load-bearing shape every
23596 // Aplicacao-scoped fixture in this suite constructs).
23597 //
23598 // Pins against a future silent detour that returned a fresh-
23599 // cloned `MeshPolicy` copy (which would type-check via a `Clone`
23600 // impl but silently break every downstream caller that relied
23601 // on the reference sharing the composite's backing identity), a
23602 // reference to an operator-resolved overlay (the future
23603 // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
23604 // acknowledges — its resolution must land at exactly this
23605 // accessor body, not silently divert the raw slot away from a
23606 // second consumer), or an axis-shuffled projection (a future
23607 // detour that swapped `timeout` and `retries` through the
23608 // accessor would silently split the paired `validate_politicas`
23609 // per-axis bracket-dispatch's traversal input from the peer
23610 // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
23611 // emitter's fan-out input from the peer
23612 // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
23613 // overlay emitter's fan-out input).
23614 //
23615 // Peer of the sibling M3
23616 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23617 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23618 // node-list `Vec`-carry axis and the sibling M3
23619 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
23620 // (0dcc926) `&[WitContract]` byte-equal pin on the per-
23621 // `:contratos` edge-list `Vec`-carry axis — extends the outer-
23622 // accessor byte-equal-projection discipline onto the outermost
23623 // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
23624 // reference axis, the first `&Composite`-return accessor on the
23625 // outer [`AplicacaoSpec`] type.
23626 let fixtures: Vec<MeshPolicy> = vec![
23627 MeshPolicy::default(),
23628 MeshPolicy {
23629 mtls_required: Some(true),
23630 ..MeshPolicy::default()
23631 },
23632 MeshPolicy {
23633 mtls_required: Some(false),
23634 ..MeshPolicy::default()
23635 },
23636 MeshPolicy {
23637 timeout: Some(Duration::from_secs(30)),
23638 ..MeshPolicy::default()
23639 },
23640 MeshPolicy {
23641 retries: Some(3),
23642 ..MeshPolicy::default()
23643 },
23644 MeshPolicy {
23645 circuit_breaker: Some(CircuitBreaker {
23646 max_failures: 5,
23647 window: Duration::from_secs(30),
23648 }),
23649 ..MeshPolicy::default()
23650 },
23651 MeshPolicy {
23652 rate_limit: Some(RateLimit {
23653 rate: 100,
23654 window: Duration::from_secs(1),
23655 }),
23656 ..MeshPolicy::default()
23657 },
23658 MeshPolicy {
23659 timeout: Some(Duration::from_secs(30)),
23660 retries: Some(3),
23661 mtls_required: Some(true),
23662 ..MeshPolicy::default()
23663 },
23664 ];
23665 for politicas in fixtures {
23666 let s = AplicacaoSpec {
23667 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23668 contratos: Vec::new(),
23669 politicas: politicas.clone(),
23670 placement: Placement::default(),
23671 entrada: None,
23672 };
23673 assert_eq!(
23674 *s.politicas(),
23675 politicas,
23676 "AplicacaoSpec::politicas must return :politicas verbatim \
23677 (got {:?}, expected {:?})",
23678 s.politicas(),
23679 politicas,
23680 );
23681 assert!(
23682 std::ptr::eq(s.politicas(), &s.politicas),
23683 "AplicacaoSpec::politicas accessor and &self.politicas \
23684 field access must borrow the same backing storage — \
23685 the accessor is the substrate-primitive typed dispatch \
23686 every downstream mesh-policy composite consumer must \
23687 route through, and a reference-identity split would \
23688 silently break every consumer that relied on the \
23689 borrow sharing the composite's storage",
23690 );
23691 assert_eq!(
23692 s.politicas().is_empty(),
23693 s.politicas.is_empty(),
23694 "AplicacaoSpec::politicas().is_empty() must byte-equal \
23695 self.politicas.is_empty() — an emptiness-drift would \
23696 silently split the paired `validate_politicas` \
23697 per-axis bracket-dispatch's seed from the peer \
23698 caixa-mesh CNP mTLS-overlay emitter's key from the \
23699 peer caixa-mesh HTTPRoute timeout+retry overlay \
23700 emitter's key",
23701 );
23702 }
23703 }
23704
23705 #[test]
23706 fn validate_politicas_reads_through_lifted_politicas_accessor() {
23707 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23708 // per-axis bracket-dispatch seed (`let p = self.politicas();`,
23709 // followed by the per-axis fan-out `p.timeout()` /
23710 // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
23711 // the lifted axis-level accessor family) must key off the
23712 // lifted outer accessor, so any future rebrand on the typed
23713 // slot's outer-composite reader shape lands at exactly one
23714 // place. Pins the multi-axis coherence by exercising each
23715 // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
23716 // a `Some(Duration::ZERO)` timeout under the outer accessor's
23717 // reference projection, (2) `PolicyRetriesZero` fires on a
23718 // `Some(0)` retries under the same projection, and (3) an
23719 // empty [`MeshPolicy::default`] passes `validate_politicas` —
23720 // the outer accessor's reference-projection reaches every
23721 // per-axis branch without silently short-circuiting any.
23722 //
23723 // Peer of the sibling M3
23724 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23725 // three-consumer coherence pin on the per-`:membros` node-list
23726 // axis and the sibling M3
23727 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
23728 // three-consumer coherence pin on the per-`:contratos`
23729 // edge-list axis — extends the multi-consumer coherence
23730 // discipline onto the outermost M3 mesh-slot type's per-
23731 // Aplicacao mesh-policy composite-reference axis, the first
23732 // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
23733 // type.
23734
23735 // (1) `PolicyTimeoutZero` refusal under the outer accessor's
23736 // reference projection: a `Some(Duration::ZERO)` timeout must
23737 // trip the zero-floor gate. The bracket-dispatch's first arm
23738 // reads `p.timeout()` on the reference returned by the outer
23739 // accessor.
23740 let mut spec = three_member_spec();
23741 spec.politicas.timeout = Some(Duration::ZERO);
23742 spec.politicas.retries = None;
23743 spec.politicas.circuit_breaker = None;
23744 spec.politicas.rate_limit = None;
23745 assert_eq!(
23746 spec.validate().unwrap_err(),
23747 AplicacaoError::PolicyTimeoutZero,
23748 );
23749 assert!(
23750 std::ptr::eq(spec.politicas(), &spec.politicas),
23751 "the `validate_politicas` per-axis bracket-dispatch's \
23752 traversal input must be the same backing composite the \
23753 accessor's reference projection borrows from",
23754 );
23755
23756 // (2) `PolicyRetriesZero` refusal under the outer accessor's
23757 // reference projection: a `Some(0)` retries must trip the
23758 // zero-floor gate. The bracket-dispatch's second arm reads
23759 // `p.retries()` on the reference returned by the outer accessor.
23760 let mut spec = three_member_spec();
23761 spec.politicas.timeout = None;
23762 spec.politicas.retries = Some(0);
23763 spec.politicas.circuit_breaker = None;
23764 spec.politicas.rate_limit = None;
23765 assert_eq!(
23766 spec.validate().unwrap_err(),
23767 AplicacaoError::PolicyRetriesZero,
23768 );
23769
23770 // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
23771 // — every per-axis arm short-circuits on `None`, so the outer
23772 // accessor's reference projection reaches the fall-through
23773 // `Ok(())` without any per-axis refusal firing.
23774 let mut spec = three_member_spec();
23775 spec.politicas = MeshPolicy::default();
23776 assert!(
23777 spec.validate().is_ok(),
23778 "an empty `MeshPolicy` must pass `validate_politicas` — \
23779 every per-axis arm short-circuits on `None` under the \
23780 outer accessor's reference projection",
23781 );
23782 assert!(
23783 spec.politicas().is_empty(),
23784 "the outer accessor's reference projection must be the \
23785 empty composite per the `MeshPolicy::default()` fixture",
23786 );
23787 }
23788
23789 #[test]
23790 #[allow(clippy::too_many_lines)]
23791 fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
23792 // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23793 // per-axis bracket-dispatch's `:timeout` and `:retries` arms
23794 // must both key off the lifted axis-level accessors
23795 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
23796 // the peer `:circuit-breaker` / `:rate-limit` arms already
23797 // routing through [`MeshPolicy::circuit_breaker`] /
23798 // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
23799 // per axis on the substrate primitive" shape at the fan-out
23800 // (four axes, four accessors, no raw-field-access site
23801 // anywhere on the bracket-dispatch). Pins the per-axis
23802 // coherence at the accept-set boundaries the bracket carves:
23803 // 1. accessor byte-equal to raw field on every representative
23804 // accept-set value (`None`, sub-cap, at-cap, past-cap
23805 // sentinel) — a future accessor drift that no longer
23806 // shipped the raw slot verbatim would surface here,
23807 // 2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
23808 // routed through the accessor's projection, proving the
23809 // first arm reads through the accessor rather than a
23810 // silent-detour peer-axis field access,
23811 // 3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
23812 // through the accessor's projection, proving the second
23813 // arm reads through the accessor,
23814 // 4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
23815 // passes validate under the accessor projection (paired
23816 // with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
23817 // sibling axis), pinning the upper-boundary accept-arm
23818 // also routes through the accessor.
23819 //
23820 // Peer of the sibling M3
23821 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23822 // outer-composite-reference coherence pin (which asserts the
23823 // `let p = self.politicas()` seed); extends the discipline onto
23824 // the per-axis fan-out layer that consumes the seed's
23825 // reference. Same shape as
23826 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
23827 // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23828 // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
23829 // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
23830
23831 // (1) Accessor byte-equal to raw field on the `:timeout` axis
23832 // across the accept-set boundaries the bracket dispatch's
23833 // three-arm gate carves out
23834 // ([`crate::render::require_positive_canonical_bounded_duration`]
23835 // — zero-floor + canonical-form + upper-cap).
23836 for timeout in [
23837 None,
23838 Some(Duration::ZERO),
23839 Some(Duration::from_millis(1)),
23840 Some(POLICY_TIMEOUT_MAX),
23841 ] {
23842 let p = MeshPolicy {
23843 timeout,
23844 ..MeshPolicy::default()
23845 };
23846 assert_eq!(
23847 p.timeout(),
23848 p.timeout,
23849 "MeshPolicy::timeout accessor must byte-equal the raw \
23850 .timeout field across every accept-set boundary the \
23851 validate_politicas :timeout arm carves out — a drift \
23852 here would silently split the validate bracket's arm \
23853 from the peer caixa-mesh HTTPRoute timeout-overlay \
23854 emitter's read",
23855 );
23856 }
23857
23858 // (2) Accessor byte-equal to raw field on the `:retries` axis
23859 // across the accept-set boundaries the bracket dispatch's
23860 // two-arm gate carves out
23861 // ([`crate::render::require_positive_bounded_u32`] — zero-floor
23862 // + upper-cap).
23863 for retries in [
23864 None,
23865 Some(0u32),
23866 Some(1u32),
23867 Some(POLICY_RETRIES_MAX),
23868 Some(POLICY_RETRIES_MAX + 1),
23869 Some(u32::MAX),
23870 ] {
23871 let p = MeshPolicy {
23872 retries,
23873 ..MeshPolicy::default()
23874 };
23875 assert_eq!(
23876 p.retries(),
23877 p.retries,
23878 "MeshPolicy::retries accessor must byte-equal the raw \
23879 .retries field across every accept-set boundary the \
23880 validate_politicas :retries arm carves out — a drift \
23881 here would silently split the validate bracket's arm \
23882 from the peer caixa-mesh HTTPRoute retry-overlay \
23883 emitter's read",
23884 );
23885 }
23886
23887 // (3) `PolicyTimeoutZero` fires on the accessor-projected
23888 // zero-floor boundary. A silent detour that no longer read
23889 // through `p.timeout()` (a peer-axis field read, an accidental
23890 // Option::and-then chain that collapsed the None arm to Some,
23891 // an accessor rebrand that clamped the return through the
23892 // upper cap) would fail to refuse here.
23893 let mut spec = three_member_spec();
23894 spec.politicas.timeout = Some(Duration::ZERO);
23895 spec.politicas.retries = None;
23896 spec.politicas.circuit_breaker = None;
23897 spec.politicas.rate_limit = None;
23898 assert_eq!(
23899 spec.politicas().timeout(),
23900 Some(Duration::ZERO),
23901 "the accessor projection must reflect the fixture's \
23902 `Some(Duration::ZERO)` :timeout verbatim",
23903 );
23904 assert_eq!(
23905 spec.validate().unwrap_err(),
23906 AplicacaoError::PolicyTimeoutZero,
23907 "the validate_politicas :timeout zero-floor arm must fire \
23908 through the lifted accessor's projection — a silent \
23909 detour to a peer-axis field would fail to refuse",
23910 );
23911
23912 // (4) `PolicyRetriesZero` fires on the accessor-projected
23913 // zero-floor boundary on the sibling `:retries` axis.
23914 let mut spec = three_member_spec();
23915 spec.politicas.timeout = None;
23916 spec.politicas.retries = Some(0);
23917 spec.politicas.circuit_breaker = None;
23918 spec.politicas.rate_limit = None;
23919 assert_eq!(
23920 spec.politicas().retries(),
23921 Some(0),
23922 "the accessor projection must reflect the fixture's \
23923 `Some(0)` :retries verbatim",
23924 );
23925 assert_eq!(
23926 spec.validate().unwrap_err(),
23927 AplicacaoError::PolicyRetriesZero,
23928 "the validate_politicas :retries zero-floor arm must fire \
23929 through the lifted accessor's projection — a silent \
23930 detour to a peer-axis field would fail to refuse",
23931 );
23932
23933 // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
23934 // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
23935 // must pass validate under the accessor projection — pins the
23936 // upper-boundary accept-arm also routes through the lifted
23937 // accessor (a drift that clamped or short-circuited at the
23938 // upper boundary would fail the whole-spec validate here).
23939 let mut spec = three_member_spec();
23940 spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
23941 spec.politicas.retries = Some(POLICY_RETRIES_MAX);
23942 spec.politicas.circuit_breaker = None;
23943 spec.politicas.rate_limit = None;
23944 assert_eq!(
23945 spec.politicas().timeout(),
23946 Some(POLICY_TIMEOUT_MAX),
23947 "the accessor projection must reflect the fixture's \
23948 at-cap :timeout verbatim",
23949 );
23950 assert_eq!(
23951 spec.politicas().retries(),
23952 Some(POLICY_RETRIES_MAX),
23953 "the accessor projection must reflect the fixture's \
23954 at-cap :retries verbatim",
23955 );
23956 assert!(
23957 spec.validate().is_ok(),
23958 "at-cap :timeout + :retries must pass validate under the \
23959 accessor projection — the upper-boundary accept-arm on \
23960 both axes routes through the lifted accessor",
23961 );
23962 }
23963
23964 #[test]
23965 fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
23966 // The canonical per-`:placement` outer-composite-reference-shape
23967 // pin: [`AplicacaoSpec::placement`] must return the `:placement`
23968 // typed `Placement` verbatim as a `&Placement` reference over the
23969 // same backing storage the raw `&self.placement` field access
23970 // borrows from, byte-equal across every representative fixture in
23971 // the accept-set — the default `Placement` (the substrate seed
23972 // shape whose [`PlacementStrategy::default`] evaluates to
23973 // `SingleNode` with an empty `:clusters` pool and both
23974 // optional-scalar axes `None`), and every canonical strategy /
23975 // cluster-pool / optional-scalar combination the
23976 // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
23977 // three [`PlacementStrategy`] variants — `SingleNode`,
23978 // `Replicated`, `Sharded` — cross-projected with a non-empty
23979 // `:clusters` pool and, on the `Sharded` arm, a non-empty
23980 // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
23981 // canonical `three_member_spec` `Replicated` fixture's
23982 // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
23983 //
23984 // Pins against a future silent detour that returned a fresh-
23985 // cloned `Placement` copy (which would type-check via a `Clone`
23986 // impl but silently break every downstream caller that relied on
23987 // the reference sharing the composite's backing identity), a
23988 // reference to an operator-resolved overlay (the future per-
23989 // cluster `:placement-overrides` slot MESH-COMPOSITION §V
23990 // acknowledges — its resolution must land at exactly this
23991 // accessor body, not silently divert the raw slot away from a
23992 // second consumer), or an axis-shuffled projection (a future
23993 // detour that swapped `clusters` and `affinity` through the
23994 // accessor would silently split the paired `validate_placement`
23995 // per-axis bracket-dispatch's traversal input from the peer
23996 // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
23997 // programs.yaml distribution-annotation emitter's fan-out input
23998 // from the peer `feira app graph` per-Aplicacao print line's
23999 // input).
24000 //
24001 // Peer of the sibling M3
24002 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24003 // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
24004 // outer mesh-policy composite-reference axis, and of the sibling
24005 // slice-return `aplicacao_spec_membros_returns_membros_slice_
24006 // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
24007 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
24008 // across_permutations` (0dcc926) `&[WitContract]` pins — extends
24009 // the outer-accessor byte-equal-projection discipline onto the
24010 // outermost M3 mesh-slot type's per-Aplicacao distribution
24011 // composite-reference axis, the second `&Composite`-return
24012 // accessor on the outer [`AplicacaoSpec`] type.
24013 let fixtures: Vec<Placement> = vec![
24014 Placement::default(),
24015 Placement {
24016 estrategia: PlacementStrategy::SingleNode,
24017 clusters: vec!["rio".into()],
24018 affinity: None,
24019 shard_key: None,
24020 },
24021 Placement {
24022 estrategia: PlacementStrategy::Replicated,
24023 clusters: vec!["rio".into(), "mar".into()],
24024 affinity: None,
24025 shard_key: None,
24026 },
24027 Placement {
24028 estrategia: PlacementStrategy::Replicated,
24029 clusters: vec!["rio".into(), "mar".into()],
24030 affinity: Some("data-locality".into()),
24031 shard_key: None,
24032 },
24033 Placement {
24034 estrategia: PlacementStrategy::Sharded,
24035 clusters: vec!["rio".into(), "mar".into()],
24036 affinity: None,
24037 shard_key: Some("tenantId".into()),
24038 },
24039 Placement {
24040 estrategia: PlacementStrategy::Sharded,
24041 clusters: vec!["rio".into(), "mar".into(), "sol".into()],
24042 affinity: Some("low-latency".into()),
24043 shard_key: Some("metadata.tenantId".into()),
24044 },
24045 ];
24046 for placement in fixtures {
24047 let s = AplicacaoSpec {
24048 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24049 contratos: Vec::new(),
24050 politicas: MeshPolicy::default(),
24051 placement: placement.clone(),
24052 entrada: None,
24053 };
24054 assert_eq!(
24055 *s.placement(),
24056 placement,
24057 "AplicacaoSpec::placement must return :placement verbatim \
24058 (got {:?}, expected {:?})",
24059 s.placement(),
24060 placement,
24061 );
24062 assert!(
24063 std::ptr::eq(s.placement(), &s.placement),
24064 "AplicacaoSpec::placement accessor and &self.placement \
24065 field access must borrow the same backing storage — the \
24066 accessor is the substrate-primitive typed dispatch every \
24067 downstream distribution-composite consumer must route \
24068 through, and a reference-identity split would silently \
24069 break every consumer that relied on the borrow sharing \
24070 the composite's storage",
24071 );
24072 assert_eq!(
24073 s.placement().estrategia(),
24074 s.placement.estrategia,
24075 "AplicacaoSpec::placement().estrategia() must byte-equal \
24076 self.placement.estrategia — a strategy-drift would \
24077 silently split the paired `validate_placement` \
24078 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
24079 peer caixa-mesh programs.yaml `placement.estrategia` \
24080 emitter's key from the peer `feira app graph` printer's \
24081 strategy label",
24082 );
24083 assert_eq!(
24084 s.placement().clusters(),
24085 s.placement.clusters.as_slice(),
24086 "AplicacaoSpec::placement().clusters() must byte-equal \
24087 self.placement.clusters — a cluster-pool drift would \
24088 silently split the paired `validate_placement` \
24089 pre-flight `.is_empty()` refusal probe's traversal from \
24090 the peer caixa-mesh programs.yaml `placement.clusters` \
24091 emitter's fan-out from the peer `feira app graph` \
24092 printer's cluster list",
24093 );
24094 }
24095 }
24096
24097 #[test]
24098 fn validate_placement_reads_through_lifted_placement_accessor() {
24099 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
24100 // per-axis bracket-dispatch seed (`let p = self.placement();`,
24101 // followed by the per-axis fan-out `p.clusters()` /
24102 // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
24103 // lifted axis-level accessor family) must key off the lifted
24104 // outer accessor, so any future rebrand on the typed slot's
24105 // outer-composite reader shape lands at exactly one place. Pins
24106 // the multi-axis coherence by exercising each per-axis refusal
24107 // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
24108 // `:clusters` pool under the outer accessor's reference
24109 // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
24110 // strategy with a `None` `:shard-key` under the same projection,
24111 // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
24112 // with a `Some` `:shard-key` under the same projection, and
24113 // (4) the canonical `three_member_spec` `Replicated` fixture
24114 // passes `validate_placement` under the outer accessor's
24115 // reference projection — the accessor's reference-projection
24116 // reaches every per-axis branch (cluster-pool refusal, `Sharded`
24117 // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
24118 // without silently short-circuiting any.
24119 //
24120 // Peer of the sibling M3
24121 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24122 // (534dc21) multi-axis coherence pin on the per-`:politicas`
24123 // outer mesh-policy composite-reference axis — extends the
24124 // multi-consumer coherence discipline onto the outermost M3
24125 // mesh-slot type's per-Aplicacao distribution composite-
24126 // reference axis, the second `&Composite`-return accessor on
24127 // the outer [`AplicacaoSpec`] type.
24128
24129 // (1) `PlacementWithoutClusters` refusal under the outer
24130 // accessor's reference projection: an empty `:clusters` pool
24131 // must trip the pre-flight refusal probe. The bracket-dispatch's
24132 // first arm reads `p.clusters()` on the reference returned by
24133 // the outer accessor.
24134 let mut spec = three_member_spec();
24135 spec.placement.clusters = Vec::new();
24136 assert_eq!(
24137 spec.validate().unwrap_err(),
24138 AplicacaoError::PlacementWithoutClusters {
24139 estrategia: PlacementStrategy::Replicated,
24140 },
24141 );
24142 assert!(
24143 std::ptr::eq(spec.placement(), &spec.placement),
24144 "the `validate_placement` per-axis bracket-dispatch's \
24145 traversal input must be the same backing composite the \
24146 accessor's reference projection borrows from",
24147 );
24148
24149 // (2) `ShardedWithoutKey` refusal under the outer accessor's
24150 // reference projection: a `Sharded` strategy with a `None`
24151 // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
24152 // The bracket-dispatch's third arm reads `p.estrategia()` for
24153 // the match scrutinee then `p.shard_key()` for the cascade
24154 // scrutinee, both on the reference returned by the outer
24155 // accessor.
24156 let mut spec = three_member_spec();
24157 spec.placement.estrategia = PlacementStrategy::Sharded;
24158 spec.placement.shard_key = None;
24159 assert_eq!(
24160 spec.validate().unwrap_err(),
24161 AplicacaoError::ShardedWithoutKey,
24162 );
24163
24164 // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
24165 // reference projection: a non-`Sharded` strategy with a `Some`
24166 // `:shard-key` must trip the declared-but-inert refusal. The
24167 // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
24168 // + `p.estrategia()` for the diagnostic on the reference
24169 // returned by the outer accessor.
24170 let mut spec = three_member_spec();
24171 spec.placement.estrategia = PlacementStrategy::Replicated;
24172 spec.placement.shard_key = Some("tenantId".into());
24173 assert_eq!(
24174 spec.validate().unwrap_err(),
24175 AplicacaoError::ShardKeyOnNonSharded {
24176 estrategia: PlacementStrategy::Replicated,
24177 shard_key: "tenantId".into(),
24178 },
24179 );
24180
24181 // (4) Canonical `three_member_spec` `Replicated` fixture passes
24182 // `validate_placement` — every per-axis arm reaches the fall-
24183 // through `Ok(())` without any per-axis refusal firing under the
24184 // outer accessor's reference projection.
24185 let spec = three_member_spec();
24186 assert!(
24187 spec.validate().is_ok(),
24188 "the canonical Replicated placement fixture must pass \
24189 `validate_placement` — every per-axis arm short-circuits on \
24190 valid input under the outer accessor's reference projection",
24191 );
24192 assert_eq!(
24193 spec.placement().estrategia(),
24194 PlacementStrategy::Replicated,
24195 "the outer accessor's reference projection must be the \
24196 canonical Replicated fixture's strategy",
24197 );
24198 assert_eq!(
24199 spec.placement().clusters(),
24200 &["rio", "mar"],
24201 "the outer accessor's reference projection must be the \
24202 canonical Replicated fixture's cluster pool",
24203 );
24204 }
24205
24206 #[test]
24207 fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
24208 // The canonical per-`:entrada` outer-composite-optional-
24209 // reference-shape pin: [`AplicacaoSpec::entrada`] must return
24210 // the `:entrada` typed `Option<Entrada>` verbatim as an
24211 // `Option<&Entrada>` reference over the same backing storage
24212 // the raw `self.entrada.as_ref()` field access borrows from,
24213 // byte-equal across every representative fixture in the
24214 // accept-set — the author-omitted `None` shape (the
24215 // "internal-only mesh" partition every downstream external-
24216 // gateway emitter treats as "emit nothing"), the minimal
24217 // singleton `:entrada` composite (host + destination + empty
24218 // paths + default port), the paths-carrying composite (the
24219 // canonical `three_member_spec` fixture's ["/api" "/health"]
24220 // path-list shape every HTTPRoute per-rule fan-out emitter
24221 // reads), and the non-default port composite (the canonical
24222 // custom-port shape the port-fallback resolver reads).
24223 //
24224 // Pins against a future silent detour that returned a fresh-
24225 // cloned `Entrada` copy (which would type-check via a `Clone`
24226 // impl but silently break every downstream caller that
24227 // relied on the reference sharing the composite's backing
24228 // identity), a reference to an operator-resolved overlay
24229 // (the future per-cluster `:entrada-overrides` slot the
24230 // MESH-COMPOSITION §V federation roadmap acknowledges — its
24231 // resolution must land at exactly this accessor body, not
24232 // silently divert the raw slot away from a second consumer),
24233 // a `None` → `Some(Entrada::default)` cluster-default
24234 // projection (which would collapse the load-bearing
24235 // "author-omitted `:entrada` ⇒ internal-only mesh" partition
24236 // the peer `gateway_routes` early-return + `feira app graph`
24237 // internal-only-mesh partition both read), or an axis-
24238 // shuffled projection (a future detour that swapped
24239 // `host` and `para` through the accessor would silently
24240 // split the paired `validate` per-`:entrada` shape-and-
24241 // membership gate's traversal input from the peer
24242 // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
24243 // fan-out input from the peer `feira app graph` external-
24244 // gateway summary line).
24245 //
24246 // Peer of the sibling M3
24247 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24248 // (534dc21) `&MeshPolicy` byte-equal pin on the per-
24249 // `:politicas` outer mesh-policy composite-reference axis
24250 // and of the sibling M3
24251 // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
24252 // (9abb8f0) `&Placement` byte-equal pin on the per-
24253 // `:placement` outer distribution-composite composite-
24254 // reference axis — extends the outer-accessor byte-equal-
24255 // projection discipline onto the last unlifted outermost M3
24256 // mesh-slot type's per-Aplicacao external-gateway composite-
24257 // reference axis, the third and final `&Composite`-return
24258 // accessor on the outer [`AplicacaoSpec`] type.
24259 let fixtures: Vec<Option<Entrada>> = vec![
24260 None,
24261 Some(Entrada {
24262 host: "checkout.quero.cloud".into(),
24263 para: "cart".into(),
24264 paths: Vec::new(),
24265 port: DEFAULT_SERVICO_PORT,
24266 }),
24267 Some(Entrada {
24268 host: "checkout.quero.cloud".into(),
24269 para: "cart".into(),
24270 paths: vec!["/api".into(), "/health".into()],
24271 port: DEFAULT_SERVICO_PORT,
24272 }),
24273 Some(Entrada {
24274 host: "checkout.quero.cloud".into(),
24275 para: "cart".into(),
24276 paths: vec!["/api".into()],
24277 port: 9443,
24278 }),
24279 ];
24280 for entrada in fixtures {
24281 let s = AplicacaoSpec {
24282 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24283 contratos: Vec::new(),
24284 politicas: MeshPolicy::default(),
24285 placement: Placement::default(),
24286 entrada: entrada.clone(),
24287 };
24288 assert_eq!(
24289 s.entrada(),
24290 entrada.as_ref(),
24291 "AplicacaoSpec::entrada must return :entrada verbatim \
24292 (got {:?}, expected {:?})",
24293 s.entrada(),
24294 entrada.as_ref(),
24295 );
24296 match (s.entrada(), s.entrada.as_ref()) {
24297 (Some(a), Some(b)) => assert!(
24298 std::ptr::eq(a, b),
24299 "AplicacaoSpec::entrada accessor and \
24300 self.entrada.as_ref() field access must borrow \
24301 the same backing storage — the accessor is the \
24302 substrate-primitive typed dispatch every \
24303 downstream external-gateway composite consumer \
24304 must route through, and a reference-identity \
24305 split would silently break every consumer that \
24306 relied on the borrow sharing the composite's \
24307 storage",
24308 ),
24309 (None, None) => {}
24310 _ => panic!(
24311 "AplicacaoSpec::entrada presence bit must byte-\
24312 equal self.entrada.is_some() — a presence-bit \
24313 drift would silently split the paired `validate` \
24314 per-`:entrada` shape-and-membership gate's \
24315 traversal head from the peer \
24316 caixa-mesh gateway_routes early-return partition \
24317 from the peer `feira app graph` internal-only-\
24318 mesh partition",
24319 ),
24320 }
24321 assert_eq!(
24322 s.entrada().is_some(),
24323 s.entrada.is_some(),
24324 "AplicacaoSpec::entrada().is_some() must byte-equal \
24325 self.entrada.is_some() — a presence-bit drift would \
24326 silently split every downstream `Option<&Entrada>` \
24327 consumer's partition on the internal-only-mesh arm",
24328 );
24329 }
24330 }
24331
24332 #[test]
24333 fn validate_reads_through_lifted_entrada_accessor() {
24334 // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
24335 // per-`:entrada` shape-and-membership gate (`if let Some(e) =
24336 // self.entrada() { … }`, followed by the per-axis fan-out
24337 // `validate_entrada_para(&e.para)` /
24338 // `EntradaMemberMissing` membership lookup /
24339 // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
24340 // per-`e.paths` `validate_entrada_path` traversal) must key
24341 // off the lifted outer accessor, so any future rebrand on
24342 // the typed slot's outer-composite reader shape lands at
24343 // exactly one place. Pins the multi-axis coherence by
24344 // exercising each per-axis refusal end-to-end: (1) the
24345 // author-omitted `None` shape short-circuits past every
24346 // per-`:entrada` refusal (the internal-only mesh partition
24347 // the accessor's `None` arm names), (2) `EntradaMemberMissing`
24348 // fires on a well-shaped but phantom `:para` under the outer
24349 // accessor's reference projection, and (3) the canonical
24350 // `three_member_spec` `:entrada` fixture passes `validate`
24351 // under the outer accessor's reference projection.
24352 //
24353 // Peer of the sibling M3
24354 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24355 // (534dc21) multi-axis coherence pin on the per-`:politicas`
24356 // outer mesh-policy composite-reference axis and the sibling
24357 // M3
24358 // [`validate_placement_reads_through_lifted_placement_accessor`]
24359 // (9abb8f0) multi-axis coherence pin on the per-`:placement`
24360 // outer distribution-composite composite-reference axis —
24361 // extends the multi-consumer coherence discipline onto the
24362 // last unlifted outermost M3 mesh-slot type's per-Aplicacao
24363 // external-gateway composite-reference axis, the third and
24364 // final `&Composite`-return accessor on the outer
24365 // [`AplicacaoSpec`] type.
24366
24367 // (1) `None` :entrada — the internal-only-mesh partition
24368 // short-circuits past every per-`:entrada` refusal. The outer
24369 // accessor's reference projection reaches the fall-through
24370 // `Ok(())` on the `None` arm without any per-axis refusal
24371 // firing.
24372 let mut spec = three_member_spec();
24373 spec.entrada = None;
24374 assert!(
24375 spec.validate().is_ok(),
24376 "an author-omitted `:entrada` must pass `validate` — the \
24377 internal-only-mesh partition short-circuits past every \
24378 per-`:entrada` refusal under the outer accessor's \
24379 reference projection",
24380 );
24381 assert!(
24382 spec.entrada().is_none(),
24383 "the outer accessor's reference projection must name the \
24384 internal-only-mesh partition per the `None` fixture",
24385 );
24386
24387 // (2) `EntradaMemberMissing` refusal under the outer accessor's
24388 // reference projection: a well-shaped but phantom `:para` must
24389 // trip the membership-lookup refusal. The gate's second arm
24390 // reads `e.para` on the reference returned by the outer
24391 // accessor.
24392 let mut spec = three_member_spec();
24393 if let Some(e) = spec.entrada.as_mut() {
24394 e.para = "phantom".into();
24395 }
24396 assert_eq!(
24397 spec.validate().unwrap_err(),
24398 AplicacaoError::EntradaMemberMissing {
24399 para: "phantom".into(),
24400 },
24401 );
24402 match (spec.entrada(), spec.entrada.as_ref()) {
24403 (Some(a), Some(b)) => assert!(
24404 std::ptr::eq(a, b),
24405 "the `validate` per-`:entrada` gate's traversal head \
24406 must be the same backing composite the accessor's \
24407 reference projection borrows from",
24408 ),
24409 _ => panic!("fixture must carry Some(:entrada)"),
24410 }
24411
24412 // (3) Canonical `three_member_spec` `:entrada` fixture passes
24413 // `validate` — every per-axis arm reaches the fall-through
24414 // `Ok(())` without any per-axis refusal firing under the
24415 // outer accessor's reference projection.
24416 let spec = three_member_spec();
24417 assert!(
24418 spec.validate().is_ok(),
24419 "the canonical `:entrada` fixture must pass `validate` — \
24420 every per-axis arm short-circuits on valid input under \
24421 the outer accessor's reference projection",
24422 );
24423 assert!(
24424 spec.entrada().is_some(),
24425 "the outer accessor's reference projection must be the \
24426 canonical `:entrada` fixture's composite",
24427 );
24428 }
24429
24430 #[test]
24431 fn port_for_destination_reads_through_lifted_entrada_accessor() {
24432 // Peer coherence pin: the
24433 // [`AplicacaoSpec::port_for_destination`] per-destination
24434 // L4-port fallback resolver's composite-projection seed
24435 // (`self.entrada().filter(…).map_or(…)`) must key off the
24436 // lifted outer accessor. Pins the coherence by exercising
24437 // the resolver end-to-end: (1) the `None` `:entrada` shape
24438 // falls through to `DEFAULT_SERVICO_PORT` under the outer
24439 // accessor's reference projection, (2) a non-matching
24440 // destination falls through to `DEFAULT_SERVICO_PORT` under
24441 // the outer accessor's reference projection, and (3) the
24442 // matching destination resolves to the `:entrada :port`
24443 // value under the outer accessor's reference projection.
24444 //
24445 // Peer of the sibling
24446 // [`validate_reads_through_lifted_entrada_accessor`] multi-
24447 // consumer coherence pin on the same per-`:entrada` outer-
24448 // composite axis — extends the multi-consumer coherence
24449 // discipline onto the second per-`:entrada` production
24450 // consumer, the L4-port fallback resolver.
24451
24452 // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
24453 // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
24454 // arm under the outer accessor's reference projection.
24455 let mut spec = three_member_spec();
24456 spec.entrada = None;
24457 assert_eq!(
24458 spec.port_for_destination("cart"),
24459 DEFAULT_SERVICO_PORT,
24460 "the port-fallback resolver must fall through to \
24461 DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
24462 under the outer accessor's reference projection",
24463 );
24464
24465 // (2) Non-matching destination — the resolver's `filter(…)`
24466 // arm rejects a mismatched destination and falls through
24467 // to `DEFAULT_SERVICO_PORT` under the outer accessor's
24468 // reference projection.
24469 let mut spec = three_member_spec();
24470 if let Some(e) = spec.entrada.as_mut() {
24471 e.para = "cart".into();
24472 e.port = 9443;
24473 }
24474 assert_eq!(
24475 spec.port_for_destination("catalog"),
24476 DEFAULT_SERVICO_PORT,
24477 "the port-fallback resolver must fall through to \
24478 DEFAULT_SERVICO_PORT on a non-matching destination \
24479 under the outer accessor's reference projection",
24480 );
24481
24482 // (3) Matching destination — the resolver's `map_or(…)` arm
24483 // returns the `:entrada :port` value under the outer
24484 // accessor's reference projection.
24485 let mut spec = three_member_spec();
24486 if let Some(e) = spec.entrada.as_mut() {
24487 e.para = "cart".into();
24488 e.port = 9443;
24489 }
24490 assert_eq!(
24491 spec.port_for_destination("cart"),
24492 9443,
24493 "the port-fallback resolver must return the \
24494 `:entrada :port` value on a matching destination \
24495 under the outer accessor's reference projection",
24496 );
24497 }
24498
24499 #[test]
24500 fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
24501 // The canonical per-`:politicas` `:mtls-required` mTLS-
24502 // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
24503 // must return the `:politicas :mtls-required` typed bool
24504 // verbatim as an `Option<bool>`, byte-equal to the raw field
24505 // access across every value in the three-way accept-set —
24506 // `None` (cluster default applies), `Some(true)` (mTLS
24507 // handshake enforced — the sandboxing-by-default arm the
24508 // MeshPolicy's docstring names), `Some(false)` (handshake
24509 // skipped — the explicit debug-edge opt-out).
24510 //
24511 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24512 // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
24513 // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
24514 // shape — first `Option<Copy-T>`-return accessor on the M3
24515 // mesh-slot family. Pins against a future silent detour that
24516 // re-derived the toggle from a peer axis (an accidental
24517 // `.circuit_breaker.is_some()` collapse that assumed mTLS on
24518 // whenever a breaker is set), a `None` → `Some(false)` cluster-
24519 // default projection (the canonical `Option<bool>` → `bool`
24520 // collapse footgun the surrounding `is_empty()` predicate
24521 // guards on the peer emptiness axis), or a `Some(true)` /
24522 // `Some(false)` variant swap that landed on one consumer
24523 // without the other.
24524 for required in [None, Some(true), Some(false)] {
24525 let p = MeshPolicy {
24526 mtls_required: required,
24527 ..MeshPolicy::default()
24528 };
24529 assert_eq!(
24530 p.mtls_required(),
24531 required,
24532 "MeshPolicy::mtls_required must return :politicas \
24533 :mtls-required verbatim (got {:?}, expected {required:?})",
24534 p.mtls_required(),
24535 );
24536 assert_eq!(
24537 p.mtls_required(),
24538 p.mtls_required,
24539 "MeshPolicy::mtls_required must byte-equal the raw \
24540 .mtls_required field access across every value in the \
24541 three-way accept-set",
24542 );
24543 }
24544 }
24545
24546 #[test]
24547 fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
24548 // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
24549 // arm must key off [`MeshPolicy::mtls_required`], not the raw
24550 // `.mtls_required` field access. Structurally: toggling ONLY
24551 // the `mtls_required` slot on an otherwise-default MeshPolicy
24552 // must flip `is_empty()` from `true` (all-`None`) to `false`
24553 // (one axis carries a value); the flip must be observed for
24554 // both `Some(true)` and `Some(false)` since the emptiness
24555 // semantic reads "any axis carries a value" — not "any axis
24556 // carries a truthy value" — the same non-collapsing shape the
24557 // sibling M2 [`crate::LimitsSpec::is_empty`] /
24558 // [`crate::BehaviorSpec::is_empty`] predicates carry on their
24559 // peer `Option<T>`-typed slot surfaces.
24560 //
24561 // Pins against a future silent detour that re-derived the
24562 // emptiness predicate off a peer axis (an accidental
24563 // `.rate_limit.is_none()`-only chain that dropped the
24564 // `mtls_required` arm entirely), a `mtls_required == Some(_)`
24565 // collapse to a truthy-only check (which would silently
24566 // classify `Some(false)` as empty), or an accessor-side
24567 // detour that no longer names the substrate-primitive typed
24568 // dispatch (an accidental `self.mtls_required.unwrap_or(false)
24569 // == false` fallback in the accessor that would silently
24570 // classify both `None` and `Some(false)` as the same value).
24571 //
24572 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24573 // (7cd2a28) accessor-composition pin on the sibling optional-
24574 // scalar axis — same "the emptiness / shape-gate predicate
24575 // must route through the substrate-primitive typed dispatch"
24576 // discipline extended onto the peer per-`:politicas` emptiness
24577 // predicate.
24578 let empty = MeshPolicy::default();
24579 assert!(
24580 empty.is_empty(),
24581 "MeshPolicy::default() must be is_empty() — every axis \
24582 defaults to None",
24583 );
24584 for required in [Some(true), Some(false)] {
24585 let p = MeshPolicy {
24586 mtls_required: required,
24587 ..MeshPolicy::default()
24588 };
24589 assert!(
24590 !p.is_empty(),
24591 "MeshPolicy::is_empty must return false when \
24592 :mtls-required is {required:?} — the emptiness \
24593 predicate reads \"any axis carries a value\", not \
24594 \"any axis carries a truthy value\"",
24595 );
24596 assert_eq!(
24597 p.mtls_required().is_none(),
24598 p.is_empty(),
24599 "when :mtls-required is the only set axis, \
24600 is_empty() must equal mtls_required().is_none() — \
24601 the accessor and the emptiness predicate must \
24602 route through the same substrate-primitive typed \
24603 dispatch on the :mtls-required arm",
24604 );
24605 }
24606 }
24607
24608 #[test]
24609 fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
24610 // The by-copy pin: [`MeshPolicy::mtls_required`] returns
24611 // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
24612 // accessor must return by value, not by reference. Peer of the
24613 // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
24614 // borrow-invariant pin on the sibling `Option<String>` slot,
24615 // but extended onto the peer `Option<bool>` copy-invariant
24616 // shape — the accessor's returned `Option<bool>` must outlive
24617 // `&self` (multiple calls must return equal values from a
24618 // dropped-`&self` copy, since the returned Option carries no
24619 // borrow), and calling the accessor twice on the same
24620 // MeshPolicy must yield the same `Option<bool>` verbatim
24621 // (idempotent, no side effects on `&self`).
24622 //
24623 // Pins against a future silent detour that returned
24624 // `Option<&bool>` (which would type-check but silently break
24625 // every downstream caller — [`single_field_overlay`]'s first
24626 // parameter is `Option<T: Clone>`, and `&bool` would fold to a
24627 // detached copy at the call site), an accidental
24628 // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
24629 // would also type-check but return `Option<&bool>`), or a
24630 // one-arm-only accessor that reads `Some(*b)` in the Some arm
24631 // but reads a fresh Default::default() in the None arm.
24632 for required in [None, Some(true), Some(false)] {
24633 let p = MeshPolicy {
24634 mtls_required: required,
24635 ..MeshPolicy::default()
24636 };
24637 let first = p.mtls_required();
24638 let second = p.mtls_required();
24639 assert_eq!(
24640 first, second,
24641 "MeshPolicy::mtls_required must be idempotent — two \
24642 successive calls on the same &self must return the \
24643 same Option<bool>",
24644 );
24645 assert_eq!(
24646 first, required,
24647 "MeshPolicy::mtls_required must return :politicas \
24648 :mtls-required verbatim by copy — got {first:?}, \
24649 expected {required:?}",
24650 );
24651 }
24652 }
24653
24654 #[test]
24655 fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
24656 // The canonical per-`:politicas` `:retries` transient-failure-
24657 // retry-budget scalar pin: [`MeshPolicy::retries`] must return
24658 // the `:politicas :retries` typed `u32` verbatim as an
24659 // `Option<u32>`, byte-equal to the raw field access across every
24660 // representative value in the accept-set — `None` (cluster
24661 // default applies — typically "no retries beyond a single
24662 // dispatch attempt" the caixa-mesh `retry_overlay` builder
24663 // documents), `Some(1)` (the lower boundary of the
24664 // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
24665 // `AplicacaoSpec::validate_politicas` gate carves out on the
24666 // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
24667 // (the upper boundary the same gate carves out on the sibling
24668 // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
24669 // past-the-guard sentinel that pins the accessor doesn't perform
24670 // a silent bounds-collapse at the return path).
24671 //
24672 // Sibling of the peer per-`:politicas`
24673 // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
24674 // sibling `Option<Copy-T>` optional-scalar axis, extended to the
24675 // peer per-`:politicas` `Option<u32>` shape — second
24676 // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
24677 // Pins against a future silent detour that re-derived the retry
24678 // cap from a peer axis (an accidental `.circuit_breaker
24679 // .as_ref().map(|b| b.max_failures)` collapse that read the
24680 // breaker's max-failure count as a retry budget), a
24681 // `None → Some(0)` cluster-default projection (which would
24682 // silently re-introduce the `PolicyRetriesZero` refusal case at
24683 // the emit boundary), or a bounds-collapsing accessor that
24684 // clamped the return through `POLICY_RETRIES_MAX` (the
24685 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24686 // must ship the raw slot verbatim so a validate-time gate
24687 // regression surfaces at the emit boundary rather than being
24688 // silently absorbed).
24689 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24690 let p = MeshPolicy {
24691 retries,
24692 ..MeshPolicy::default()
24693 };
24694 assert_eq!(
24695 p.retries(),
24696 retries,
24697 "MeshPolicy::retries must return :politicas :retries \
24698 verbatim (got {:?}, expected {retries:?})",
24699 p.retries(),
24700 );
24701 assert_eq!(
24702 p.retries(),
24703 p.retries,
24704 "MeshPolicy::retries must byte-equal the raw .retries \
24705 field access across every value in the accept-set",
24706 );
24707 }
24708 }
24709
24710 #[test]
24711 fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
24712 // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
24713 // must key off [`MeshPolicy::retries`], not the raw `.retries`
24714 // field access. Structurally: toggling ONLY the `retries` slot
24715 // on an otherwise-default MeshPolicy must flip `is_empty()`
24716 // from `true` (all-`None`) to `false` (one axis carries a
24717 // value); the flip must be observed for every value in the
24718 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24719 // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
24720 // the emptiness semantic reads "any axis carries a value" —
24721 // not "any axis carries a value the validate gate accepts" —
24722 // the same non-collapsing shape the peer M2
24723 // [`crate::LimitsSpec::is_empty`] /
24724 // [`crate::BehaviorSpec::is_empty`] predicates carry.
24725 //
24726 // Pins against a future silent detour that re-derived the
24727 // emptiness predicate off a peer axis (an accidental
24728 // `.rate_limit.is_none()`-only chain that dropped the
24729 // `retries` arm entirely), a `retries == Some(_)` collapse
24730 // that key-off a validate-gate-clamped bounds check (which
24731 // would silently classify a past-the-guard `Some(u32::MAX)`
24732 // as empty because it fails the `1..=POLICY_RETRIES_MAX`
24733 // check), or an accessor-side detour that no longer names the
24734 // substrate-primitive typed dispatch.
24735 //
24736 // Sibling of the peer per-`:politicas`
24737 // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
24738 // pin on the sibling `Option<Copy-T>` optional-scalar axis —
24739 // same "the emptiness predicate must route through the
24740 // substrate-primitive typed dispatch" discipline extended onto
24741 // the peer per-`:politicas` `Option<u32>` axis.
24742 let empty = MeshPolicy::default();
24743 assert!(
24744 empty.is_empty(),
24745 "MeshPolicy::default() must be is_empty() — every axis \
24746 defaults to None",
24747 );
24748 for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
24749 let p = MeshPolicy {
24750 retries,
24751 ..MeshPolicy::default()
24752 };
24753 assert!(
24754 !p.is_empty(),
24755 "MeshPolicy::is_empty must return false when \
24756 :retries is {retries:?} — the emptiness \
24757 predicate reads \"any axis carries a value\", not \
24758 \"any axis carries a value the validate gate \
24759 accepts\"",
24760 );
24761 assert_eq!(
24762 p.retries().is_none(),
24763 p.is_empty(),
24764 "when :retries is the only set axis, is_empty() \
24765 must equal retries().is_none() — the accessor and \
24766 the emptiness predicate must route through the same \
24767 substrate-primitive typed dispatch on the :retries \
24768 arm",
24769 );
24770 }
24771 }
24772
24773 #[test]
24774 fn mesh_policy_retries_projects_option_u32_by_copy() {
24775 // The by-copy pin: [`MeshPolicy::retries`] returns
24776 // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
24777 // accessor must return by value, not by reference. Sibling of
24778 // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
24779 // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
24780 // extended onto the sibling `Option<u32>` copy-invariant
24781 // shape — the accessor's returned `Option<u32>` must outlive
24782 // `&self` (multiple calls must return equal values from a
24783 // dropped-`&self` copy, since the returned Option carries no
24784 // borrow), and calling the accessor twice on the same
24785 // MeshPolicy must yield the same `Option<u32>` verbatim
24786 // (idempotent, no side effects on `&self`).
24787 //
24788 // Pins against a future silent detour that returned
24789 // `Option<&u32>` (which would type-check but silently break
24790 // every downstream caller — [`crate::render::single_field_overlay`]'s
24791 // first parameter is `Option<T: Clone>`, and `&u32` would
24792 // fold to a detached copy at the call site), an accidental
24793 // `Option::as_ref()` projection (`self.retries.as_ref()` would
24794 // also type-check but return `Option<&u32>`), or a one-arm-
24795 // only accessor that reads `Some(*n)` in the Some arm but
24796 // reads a fresh `Default::default()` (`0_u32`) in the None
24797 // arm.
24798 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24799 let p = MeshPolicy {
24800 retries,
24801 ..MeshPolicy::default()
24802 };
24803 let first = p.retries();
24804 let second = p.retries();
24805 assert_eq!(
24806 first, second,
24807 "MeshPolicy::retries must be idempotent — two \
24808 successive calls on the same &self must return the \
24809 same Option<u32>",
24810 );
24811 assert_eq!(
24812 first, retries,
24813 "MeshPolicy::retries must return :politicas :retries \
24814 verbatim by copy — got {first:?}, expected {retries:?}",
24815 );
24816 }
24817 }
24818
24819 #[test]
24820 fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
24821 // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
24822 // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
24823 // return the `:politicas :timeout` typed [`Duration`] verbatim
24824 // as an `Option<Duration>`, byte-equal to the raw field access
24825 // across every representative value in the accept-set — `None`
24826 // (cluster default applies — typically the gateway class's
24827 // implementation-side per-request wall-clock cap the caixa-mesh
24828 // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
24829 // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
24830 // set the surrounding `AplicacaoSpec::validate_politicas` gate
24831 // carves out on the sibling `PolicyTimeoutZero` /
24832 // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
24833 // (the upper boundary the same gate carves out on the sibling
24834 // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
24835 // (a past-the-guard sentinel that pins the accessor doesn't
24836 // perform a silent bounds-collapse into `None` on the zero-
24837 // Duration arm — validate rejects zero but the accessor must
24838 // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
24839 // past-the-guard sentinel that pins the accessor doesn't
24840 // perform a silent bounds-collapse at the return path).
24841 //
24842 // Sibling of the peer per-`:politicas`
24843 // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
24844 // `Option<u32>` optional-scalar axis and the peer per-
24845 // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
24846 // pin on the sibling `Option<bool>` optional-scalar axis,
24847 // extended onto the peer per-`:politicas` `Option<Duration>`
24848 // shape — third `Option<Copy-T>`-return accessor on the M3
24849 // mesh-slot family. Pins against a future silent detour that
24850 // re-derived the per-call cap from a peer axis (an accidental
24851 // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
24852 // read the breaker's rolling-window duration as a per-call
24853 // deadline), a `None → Some(Duration::MAX)` cluster-default
24854 // projection (which would silently re-introduce the
24855 // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
24856 // blocking" arm at the emit boundary), or a bounds-collapsing
24857 // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
24858 // (the `AplicacaoSpec::validate` gate owns the bounds; the
24859 // accessor must ship the raw slot verbatim so a validate-time
24860 // gate regression surfaces at the emit boundary rather than
24861 // being silently absorbed).
24862 for timeout in [
24863 None,
24864 Some(Duration::from_millis(1)),
24865 Some(POLICY_TIMEOUT_MAX),
24866 Some(Duration::ZERO),
24867 Some(Duration::MAX),
24868 ] {
24869 let p = MeshPolicy {
24870 timeout,
24871 ..MeshPolicy::default()
24872 };
24873 assert_eq!(
24874 p.timeout(),
24875 timeout,
24876 "MeshPolicy::timeout must return :politicas :timeout \
24877 verbatim (got {:?}, expected {timeout:?})",
24878 p.timeout(),
24879 );
24880 assert_eq!(
24881 p.timeout(),
24882 p.timeout,
24883 "MeshPolicy::timeout must byte-equal the raw .timeout \
24884 field access across every value in the accept-set",
24885 );
24886 }
24887 }
24888
24889 #[test]
24890 fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
24891 // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
24892 // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
24893 // field access. Structurally: toggling ONLY the `timeout` slot
24894 // on an otherwise-default MeshPolicy must flip `is_empty()`
24895 // from `true` (all-`None`) to `false` (one axis carries a
24896 // value); the flip must be observed for every value in the
24897 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24898 // gate accepts (`Some(Duration::from_millis(1))`,
24899 // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
24900 // reads "any axis carries a value" — not "any axis carries a
24901 // value the validate gate accepts" — the same non-collapsing
24902 // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
24903 // [`crate::BehaviorSpec::is_empty`] predicates carry.
24904 //
24905 // Pins against a future silent detour that re-derived the
24906 // emptiness predicate off a peer axis (an accidental
24907 // `.rate_limit.is_none()`-only chain that dropped the
24908 // `timeout` arm entirely), a `timeout == Some(_)` collapse
24909 // that key-off a validate-gate-clamped bounds check (which
24910 // would silently classify a past-the-guard `Some(Duration::MAX)`
24911 // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
24912 // check), or an accessor-side detour that no longer names the
24913 // substrate-primitive typed dispatch.
24914 //
24915 // Sibling of the peer per-`:politicas`
24916 // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
24917 // the sibling `Option<u32>` optional-scalar axis and the peer
24918 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
24919 // accessor-composition pin on the sibling `Option<bool>`
24920 // optional-scalar axis — same "the emptiness predicate must
24921 // route through the substrate-primitive typed dispatch"
24922 // discipline extended onto the peer per-`:politicas`
24923 // `Option<Duration>` axis.
24924 let empty = MeshPolicy::default();
24925 assert!(
24926 empty.is_empty(),
24927 "MeshPolicy::default() must be is_empty() — every axis \
24928 defaults to None",
24929 );
24930 for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
24931 let p = MeshPolicy {
24932 timeout,
24933 ..MeshPolicy::default()
24934 };
24935 assert!(
24936 !p.is_empty(),
24937 "MeshPolicy::is_empty must return false when \
24938 :timeout is {timeout:?} — the emptiness \
24939 predicate reads \"any axis carries a value\", not \
24940 \"any axis carries a value the validate gate \
24941 accepts\"",
24942 );
24943 assert_eq!(
24944 p.timeout().is_none(),
24945 p.is_empty(),
24946 "when :timeout is the only set axis, is_empty() \
24947 must equal timeout().is_none() — the accessor and \
24948 the emptiness predicate must route through the same \
24949 substrate-primitive typed dispatch on the :timeout \
24950 arm",
24951 );
24952 }
24953 }
24954
24955 #[test]
24956 fn mesh_policy_timeout_projects_option_duration_by_copy() {
24957 // The by-copy pin: [`MeshPolicy::timeout`] returns
24958 // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
24959 // and the accessor must return by value, not by reference.
24960 // Sibling of the peer per-`:politicas`
24961 // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
24962 // sibling `Option<u32>` optional-scalar axis and the peer
24963 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
24964 // by-copy pin on the sibling `Option<bool>` optional-scalar
24965 // axis, extended onto the peer per-`:politicas`
24966 // `Option<Duration>` copy-invariant shape — the accessor's
24967 // returned `Option<Duration>` must outlive `&self` (multiple
24968 // calls must return equal values from a dropped-`&self`
24969 // copy, since the returned Option carries no borrow), and
24970 // calling the accessor twice on the same MeshPolicy must
24971 // yield the same `Option<Duration>` verbatim (idempotent, no
24972 // side effects on `&self`).
24973 //
24974 // Pins against a future silent detour that returned
24975 // `Option<&Duration>` (which would type-check but silently
24976 // break every downstream caller — [`crate::render::single_field_overlay`]'s
24977 // first parameter is `Option<T: Clone>`, and `&Duration`
24978 // would fold to a detached copy at the call site), an
24979 // accidental `Option::as_ref()` projection
24980 // (`self.timeout.as_ref()` would also type-check but return
24981 // `Option<&Duration>`), or a one-arm-only accessor that
24982 // reads `Some(*d)` in the Some arm but reads a fresh
24983 // `Default::default()` (`Duration::ZERO`) in the None arm
24984 // (which would silently re-classify every unset `:timeout`
24985 // as the `PolicyTimeoutZero`-refused zero-Duration value at
24986 // the accessor boundary).
24987 for timeout in [
24988 None,
24989 Some(Duration::from_millis(1)),
24990 Some(POLICY_TIMEOUT_MAX),
24991 Some(Duration::ZERO),
24992 Some(Duration::MAX),
24993 ] {
24994 let p = MeshPolicy {
24995 timeout,
24996 ..MeshPolicy::default()
24997 };
24998 let first = p.timeout();
24999 let second = p.timeout();
25000 assert_eq!(
25001 first, second,
25002 "MeshPolicy::timeout must be idempotent — two \
25003 successive calls on the same &self must return the \
25004 same Option<Duration>",
25005 );
25006 assert_eq!(
25007 first, timeout,
25008 "MeshPolicy::timeout must return :politicas :timeout \
25009 verbatim by copy — got {first:?}, expected {timeout:?}",
25010 );
25011 }
25012 }
25013
25014 #[test]
25015 fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
25016 // The canonical per-`:politicas` `:rate-limit` Envoy-
25017 // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
25018 // [`MeshPolicy::rate_limit`] must return the `:politicas
25019 // :rate-limit` typed [`RateLimit`] verbatim as an
25020 // `Option<RateLimit>`, byte-equal to the raw field access
25021 // across every representative value in the accept-set — `None`
25022 // (cluster default applies — no per-Aplicacao rate declaration,
25023 // the gateway-class per-listener default arm the future caixa-
25024 // mesh `local_rate_limit_overlay` emitter documents),
25025 // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
25026 // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
25027 // accept-set the surrounding
25028 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25029 // sibling `PolicyRateLimitZero` refusal, paired with the
25030 // canonical-window "1 second" arm of the three-unit
25031 // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
25032 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
25033 // (the upper boundary the same gate carves out on the sibling
25034 // `PolicyRateLimitExceedsCap` refusal, paired with the
25035 // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
25036 // (a past-the-guard sentinel that pins the accessor doesn't
25037 // perform a silent bounds-collapse into `None` on the
25038 // zero-rate/zero-window arm — validate rejects zero but the
25039 // accessor must ship the raw slot verbatim so a validate-time
25040 // gate regression surfaces at the emit boundary rather than
25041 // being silently absorbed), and
25042 // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
25043 // (a past-the-guard sentinel that pins the accessor doesn't
25044 // perform a silent bounds-collapse at the return path).
25045 //
25046 // First `Option<Copy-composite-T>`-return accessor pin on the
25047 // M3 mesh-slot family (peer of the sibling per-`:politicas`
25048 // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
25049 // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
25050 // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
25051 // Copy accessor pins, extended onto the peer per-`:politicas`
25052 // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
25053 // and the accessor returns by value). Pins against a future
25054 // silent detour that re-derived the rate declaration from a
25055 // peer axis (an accidental
25056 // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
25057 // collapse that read the breaker's trip threshold + rolling
25058 // window as a rate declaration), a `None → Some(default())`
25059 // cluster-default projection (which would silently re-
25060 // introduce a "cluster default is 0/s" arm the emit boundary
25061 // would take as "declared but inert" — the canonical
25062 // declared-but-inert footgun the sibling
25063 // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
25064 // amplification-shape axis), a bounds-collapsing accessor
25065 // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
25066 // clamped `rl.window` through [`is_canonical_rate_limit_window`]
25067 // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
25068 // accessor must ship the raw slot verbatim), or a
25069 // by-reference detour (`Option<&RateLimit>`) that broke every
25070 // downstream consumer keying off `Option<RateLimit>` by-copy.
25071 for rl in [
25072 None,
25073 Some(RateLimit {
25074 rate: 1,
25075 window: Duration::from_secs(1),
25076 }),
25077 Some(RateLimit {
25078 rate: POLICY_RATE_LIMIT_MAX,
25079 window: Duration::from_secs(3600),
25080 }),
25081 Some(RateLimit {
25082 rate: 0,
25083 window: Duration::ZERO,
25084 }),
25085 Some(RateLimit {
25086 rate: u32::MAX,
25087 window: Duration::MAX,
25088 }),
25089 ] {
25090 let p = MeshPolicy {
25091 rate_limit: rl,
25092 ..MeshPolicy::default()
25093 };
25094 assert_eq!(
25095 p.rate_limit(),
25096 rl,
25097 "MeshPolicy::rate_limit must return :politicas :rate-limit \
25098 verbatim (got {:?}, expected {rl:?})",
25099 p.rate_limit(),
25100 );
25101 assert_eq!(
25102 p.rate_limit(),
25103 p.rate_limit,
25104 "MeshPolicy::rate_limit must byte-equal the raw \
25105 .rate_limit field access across every value in the \
25106 accept-set",
25107 );
25108 }
25109 }
25110
25111 #[test]
25112 fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
25113 // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
25114 // must key off [`MeshPolicy::rate_limit`], not the raw
25115 // `.rate_limit` field access. Structurally: toggling ONLY the
25116 // `rate_limit` slot on an otherwise-default MeshPolicy must
25117 // flip `is_empty()` from `true` (all-`None`) to `false` (one
25118 // axis carries a value); the flip must be observed for every
25119 // representative value in the accept-set the surrounding
25120 // [`AplicacaoSpec::validate_politicas`] gate accepts
25121 // (`Some(RateLimit { rate: 1, window: 1s })`,
25122 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
25123 // since the emptiness semantic reads "any axis carries a
25124 // value" — not "any axis carries a value the validate gate
25125 // accepts" — the same non-collapsing shape the peer M2
25126 // [`crate::LimitsSpec::is_empty`] /
25127 // [`crate::BehaviorSpec::is_empty`] predicates carry.
25128 //
25129 // Pins against a future silent detour that re-derived the
25130 // emptiness predicate off a peer axis (an accidental
25131 // `.timeout.is_none()`-only chain that dropped the
25132 // `rate_limit` arm entirely — the last unlifted inline field
25133 // access on `is_empty` before this lift), a `rate_limit ==
25134 // Some(_)` collapse that key-off a validate-gate-clamped
25135 // bounds check (which would silently classify a past-the-
25136 // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
25137 // because it fails the value-shape gate), or an accessor-
25138 // side detour that no longer names the substrate-primitive
25139 // typed dispatch.
25140 //
25141 // Fourth "the emptiness predicate must route through the
25142 // substrate-primitive typed dispatch" composition pin on the
25143 // M3 mesh-slot family — closes the last unlifted composition
25144 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25145 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25146 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25147 // 7073d0f is_empty-composition pins on the sibling primitive-
25148 // Copy axes, extended onto the peer per-`:politicas`
25149 // composite-Copy `Option<RateLimit>` axis).
25150 let empty = MeshPolicy::default();
25151 assert!(
25152 empty.is_empty(),
25153 "MeshPolicy::default() must be is_empty() — every axis \
25154 defaults to None",
25155 );
25156 for rl in [
25157 RateLimit {
25158 rate: 1,
25159 window: Duration::from_secs(1),
25160 },
25161 RateLimit {
25162 rate: POLICY_RATE_LIMIT_MAX,
25163 window: Duration::from_secs(3600),
25164 },
25165 ] {
25166 let p = MeshPolicy {
25167 rate_limit: Some(rl),
25168 ..MeshPolicy::default()
25169 };
25170 assert!(
25171 !p.is_empty(),
25172 "MeshPolicy::is_empty must return false when \
25173 :rate-limit is {rl:?} — the emptiness predicate \
25174 reads \"any axis carries a value\", not \"any axis \
25175 carries a value the validate gate accepts\"",
25176 );
25177 assert_eq!(
25178 p.rate_limit().is_none(),
25179 p.is_empty(),
25180 "when :rate-limit is the only set axis, is_empty() \
25181 must equal rate_limit().is_none() — the accessor \
25182 and the emptiness predicate must route through the \
25183 same substrate-primitive typed dispatch on the \
25184 :rate-limit arm",
25185 );
25186 }
25187 }
25188
25189 #[test]
25190 fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
25191 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25192 // `:rate-limit` value-shape gate must key off
25193 // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
25194 // field bind. Structurally: a `MeshPolicy` whose only set
25195 // axis is a `Some(RateLimit { rate: 0, .. })` must surface
25196 // the `PolicyRateLimitZero` refusal exactly, and the same
25197 // MeshPolicy with the rate at the canonical lower boundary
25198 // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
25199 // The pair jointly pins the accessor + validate-gate
25200 // composition: any future silent detour that had the accessor
25201 // omit the `Some(RateLimit { rate: 0, .. })` arm (a
25202 // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
25203 // silently absorb the `PolicyRateLimitZero` refusal at the
25204 // accessor boundary — the composition pin catches that at
25205 // caixa-core build time.
25206 //
25207 // Sibling of the peer [`validate_politicas`]
25208 // `:mtls-required` / `:retries` / `:timeout` composition pins
25209 // on the sibling primitive-Copy optional-scalar axes — same
25210 // "the validate / shape-gate predicate must route through the
25211 // substrate-primitive typed dispatch" discipline extended
25212 // onto the peer per-`:politicas` composite-Copy
25213 // `Option<RateLimit>` axis. Second composition-with-accessor
25214 // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
25215 // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
25216 let mut spec = three_member_spec();
25217 spec.politicas = MeshPolicy {
25218 rate_limit: Some(RateLimit {
25219 rate: 0,
25220 window: Duration::from_secs(1),
25221 }),
25222 ..MeshPolicy::default()
25223 };
25224 assert!(
25225 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
25226 "validate_politicas must reject rate == 0 with \
25227 PolicyRateLimitZero — the accessor and the validate gate \
25228 must route through the same substrate-primitive typed \
25229 dispatch on the :rate-limit zero-floor arm",
25230 );
25231 spec.politicas = MeshPolicy {
25232 rate_limit: Some(RateLimit {
25233 rate: 1,
25234 window: Duration::from_secs(1),
25235 }),
25236 ..MeshPolicy::default()
25237 };
25238 assert!(
25239 spec.validate().is_ok(),
25240 "validate_politicas must accept rate == 1 (the canonical \
25241 lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
25242 set) with a canonical 1s window",
25243 );
25244 }
25245
25246 #[test]
25247 fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
25248 // The canonical per-`:politicas` `:circuit-breaker` Envoy-
25249 // `outlier_detection`-mesh consecutive-failure-ejection scalar
25250 // pin: [`MeshPolicy::circuit_breaker`] must return the
25251 // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
25252 // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
25253 // raw field access across every representative value in the
25254 // accept-set — `None` (cluster default applies — no
25255 // per-Aplicacao breaker declaration, the gateway-class per-
25256 // listener default arm the future caixa-mesh
25257 // `outlier_detection_overlay` emitter documents),
25258 // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
25259 // (the lower boundary of the accept-set the surrounding
25260 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25261 // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
25262 // refusals),
25263 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
25264 // (the upper boundary the same gate carves out on the sibling
25265 // `PolicyBreakerMaxFailuresExceedsCap` /
25266 // `PolicyBreakerWindowExceedsCap` refusals),
25267 // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
25268 // (a past-the-guard sentinel that pins the accessor doesn't
25269 // perform a silent bounds-collapse into `None` on the
25270 // zero-failures/zero-window arm — validate rejects zero but
25271 // the accessor must ship the raw slot verbatim so a validate-
25272 // time gate regression surfaces at the emit boundary rather
25273 // than being silently absorbed), and
25274 // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
25275 // (a past-the-guard sentinel that pins the accessor doesn't
25276 // perform a silent bounds-collapse at the return path).
25277 //
25278 // Second `Option<Copy-composite-T>`-return accessor pin on the
25279 // M3 mesh-slot family (peer of the sibling per-`:politicas`
25280 // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
25281 // composite-Copy accessor pin, and of the sibling per-
25282 // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
25283 // [`MeshPolicy::retries`] bdfb399 /
25284 // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
25285 // accessor pins). Pins against a future silent detour that
25286 // re-derived the breaker declaration from a peer axis (an
25287 // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
25288 // collapse that read the rate-limit's bucket capacity + refill
25289 // period as a breaker declaration), a `None → Some(default())`
25290 // cluster-default projection (which would silently re-
25291 // introduce the `PolicyBreakerZeroFailures` /
25292 // `PolicyBreakerZeroWindow` refusal cases at the emit
25293 // boundary), a bounds-collapsing accessor that clamped
25294 // `cb.max_failures` through
25295 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
25296 // through [`POLICY_BREAKER_WINDOW_MAX`] (the
25297 // [`AplicacaoSpec::validate`] gate owns the bounds; the
25298 // accessor must ship the raw slot verbatim), or a
25299 // by-reference detour (`Option<&CircuitBreaker>`) that broke
25300 // every downstream consumer keying off `Option<CircuitBreaker>`
25301 // by-copy.
25302 for cb in [
25303 None,
25304 Some(CircuitBreaker {
25305 max_failures: 1,
25306 window: Duration::from_millis(1),
25307 }),
25308 Some(CircuitBreaker {
25309 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25310 window: POLICY_BREAKER_WINDOW_MAX,
25311 }),
25312 Some(CircuitBreaker {
25313 max_failures: 0,
25314 window: Duration::ZERO,
25315 }),
25316 Some(CircuitBreaker {
25317 max_failures: u32::MAX,
25318 window: Duration::MAX,
25319 }),
25320 ] {
25321 let p = MeshPolicy {
25322 circuit_breaker: cb,
25323 ..MeshPolicy::default()
25324 };
25325 assert_eq!(
25326 p.circuit_breaker(),
25327 cb,
25328 "MeshPolicy::circuit_breaker must return :politicas \
25329 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
25330 p.circuit_breaker(),
25331 );
25332 assert_eq!(
25333 p.circuit_breaker(),
25334 p.circuit_breaker,
25335 "MeshPolicy::circuit_breaker must byte-equal the raw \
25336 .circuit_breaker field access across every value in \
25337 the accept-set",
25338 );
25339 }
25340 }
25341
25342 #[test]
25343 fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
25344 // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
25345 // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
25346 // `.circuit_breaker` field access. Structurally: toggling ONLY
25347 // the `circuit_breaker` slot on an otherwise-default MeshPolicy
25348 // must flip `is_empty()` from `true` (all-`None`) to `false`
25349 // (one axis carries a value); the flip must be observed for
25350 // every representative value in the accept-set the surrounding
25351 // [`AplicacaoSpec::validate_politicas`] gate accepts
25352 // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
25353 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
25354 // since the emptiness semantic reads "any axis carries a
25355 // value" — not "any axis carries a value the validate gate
25356 // accepts" — the same non-collapsing shape the peer M2
25357 // [`crate::LimitsSpec::is_empty`] /
25358 // [`crate::BehaviorSpec::is_empty`] predicates carry.
25359 //
25360 // Pins against a future silent detour that re-derived the
25361 // emptiness predicate off a peer axis (an accidental
25362 // `.rate_limit.is_none()`-only chain that dropped the
25363 // `circuit_breaker` arm entirely — the last unlifted inline
25364 // field access on `is_empty` before this lift), a
25365 // `circuit_breaker == Some(_)` collapse that key-off a
25366 // validate-gate-clamped bounds check (which would silently
25367 // classify a past-the-guard `Some(CircuitBreaker { max_failures:
25368 // 0, window: 0s })` as empty because it fails the value-shape
25369 // gate), or an accessor-side detour that no longer names the
25370 // substrate-primitive typed dispatch.
25371 //
25372 // Fifth "the emptiness predicate must route through the
25373 // substrate-primitive typed dispatch" composition pin on the
25374 // M3 mesh-slot family — closes the last unlifted composition
25375 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25376 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25377 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25378 // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
25379 // composition pins on the sibling primitive-Copy + composite-
25380 // Copy axes, extended onto the peer per-`:politicas`
25381 // composite-Copy `Option<CircuitBreaker>` axis).
25382 let empty = MeshPolicy::default();
25383 assert!(
25384 empty.is_empty(),
25385 "MeshPolicy::default() must be is_empty() — every axis \
25386 defaults to None",
25387 );
25388 for cb in [
25389 CircuitBreaker {
25390 max_failures: 1,
25391 window: Duration::from_millis(1),
25392 },
25393 CircuitBreaker {
25394 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25395 window: POLICY_BREAKER_WINDOW_MAX,
25396 },
25397 ] {
25398 let p = MeshPolicy {
25399 circuit_breaker: Some(cb),
25400 ..MeshPolicy::default()
25401 };
25402 assert!(
25403 !p.is_empty(),
25404 "MeshPolicy::is_empty must return false when \
25405 :circuit-breaker is {cb:?} — the emptiness predicate \
25406 reads \"any axis carries a value\", not \"any axis \
25407 carries a value the validate gate accepts\"",
25408 );
25409 assert_eq!(
25410 p.circuit_breaker().is_none(),
25411 p.is_empty(),
25412 "when :circuit-breaker is the only set axis, \
25413 is_empty() must equal circuit_breaker().is_none() — \
25414 the accessor and the emptiness predicate must route \
25415 through the same substrate-primitive typed dispatch \
25416 on the :circuit-breaker arm",
25417 );
25418 }
25419 }
25420
25421 #[test]
25422 fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
25423 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25424 // `:circuit-breaker` value-shape gate must key off
25425 // [`MeshPolicy::circuit_breaker`], not the raw
25426 // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
25427 // whose only set axis is a `Some(CircuitBreaker { max_failures:
25428 // 0, .. })` must surface the `PolicyBreakerZeroFailures`
25429 // refusal exactly, and the same MeshPolicy with the breaker at
25430 // the canonical lower boundary
25431 // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
25432 // pass validate. The pair jointly pins the accessor +
25433 // validate-gate composition: any future silent detour that had
25434 // the accessor omit the `Some(CircuitBreaker { max_failures:
25435 // 0, .. })` arm (a
25436 // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
25437 // collapse) would silently absorb the
25438 // `PolicyBreakerZeroFailures` refusal at the accessor
25439 // boundary — the composition pin catches that at caixa-core
25440 // build time.
25441 //
25442 // Sibling of the peer [`validate_politicas`]
25443 // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
25444 // composition pins on the sibling primitive-Copy + composite-
25445 // Copy optional-scalar axes — same "the validate / shape-gate
25446 // predicate must route through the substrate-primitive typed
25447 // dispatch" discipline extended onto the peer per-`:politicas`
25448 // composite-Copy `Option<CircuitBreaker>` axis. Second
25449 // composition-with-accessor pin on the M3 mesh-slot
25450 // `Option<CircuitBreaker>` arm alongside the
25451 // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
25452 let mut spec = three_member_spec();
25453 spec.politicas = MeshPolicy {
25454 circuit_breaker: Some(CircuitBreaker {
25455 max_failures: 0,
25456 window: Duration::from_millis(1),
25457 }),
25458 ..MeshPolicy::default()
25459 };
25460 assert!(
25461 matches!(
25462 spec.validate(),
25463 Err(AplicacaoError::PolicyBreakerZeroFailures)
25464 ),
25465 "validate_politicas must reject max_failures == 0 with \
25466 PolicyBreakerZeroFailures — the accessor and the validate \
25467 gate must route through the same substrate-primitive \
25468 typed dispatch on the :circuit-breaker zero-floor arm",
25469 );
25470 spec.politicas = MeshPolicy {
25471 circuit_breaker: Some(CircuitBreaker {
25472 max_failures: 1,
25473 window: Duration::from_millis(1),
25474 }),
25475 ..MeshPolicy::default()
25476 };
25477 assert!(
25478 spec.validate().is_ok(),
25479 "validate_politicas must accept a CircuitBreaker at the \
25480 canonical lower boundary (max_failures = 1, window = \
25481 1ms) — the accessor and the validate gate must route \
25482 through the same substrate-primitive typed dispatch on \
25483 the :circuit-breaker arm",
25484 );
25485 }
25486
25487 #[test]
25488 fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
25489 // The canonical per-`:politicas :circuit-breaker` `:max-failures`
25490 // Envoy-outlier-detection trip-threshold scalar pin:
25491 // [`CircuitBreaker::max_failures`] must return the
25492 // `:politicas :circuit-breaker :max-failures` typed `u32`
25493 // verbatim, byte-equal to the raw field access across every
25494 // representative value in the accept-set — `1` (the lower
25495 // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
25496 // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
25497 // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
25498 // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
25499 // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
25500 // refusal), `0` (a past-the-guard sentinel that pins the accessor
25501 // doesn't perform a silent bounds-collapse into `1` on the zero
25502 // arm — validate rejects zero but the accessor must ship the
25503 // raw slot verbatim so a validate-time gate regression surfaces
25504 // at the emit boundary rather than being silently absorbed),
25505 // `u32::MAX` (a past-the-guard sentinel that pins the accessor
25506 // doesn't perform a silent bounds-collapse through
25507 // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
25508 //
25509 // First sub-struct required-scalar accessor pin on the M3
25510 // mesh-slot family — sibling in shape to the peer per-`:membros`
25511 // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
25512 // (a40b0e3) required-`String`-carry accessor pins and the peer
25513 // per-`:contratos` [`WitContract::source`] /
25514 // [`WitContract::destination`] (7f0fd43) required-`String`-carry
25515 // accessor pins, extended onto the peer per-`CircuitBreaker`
25516 // required-`u32` scalar-value axis. Pins against a future silent
25517 // detour that re-derived the trip threshold from a peer axis (an
25518 // accidental `self.window.as_secs() as u32` collapse that read
25519 // the breaker's rolling-window duration as a failure count), a
25520 // `0 → 1` cluster-default projection (which would silently absorb
25521 // the `PolicyBreakerZeroFailures` refusal case at the accessor
25522 // boundary), or a bounds-collapsing accessor that clamped the
25523 // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
25524 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25525 // must ship the raw slot verbatim).
25526 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25527 let cb = CircuitBreaker {
25528 max_failures,
25529 window: Duration::from_secs(60),
25530 };
25531 assert_eq!(
25532 cb.max_failures(),
25533 max_failures,
25534 "CircuitBreaker::max_failures must return :politicas \
25535 :circuit-breaker :max-failures verbatim (got {}, \
25536 expected {max_failures})",
25537 cb.max_failures(),
25538 );
25539 assert_eq!(
25540 cb.max_failures(),
25541 cb.max_failures,
25542 "CircuitBreaker::max_failures must byte-equal the raw \
25543 .max_failures field access across every value in the \
25544 u32 accept-set",
25545 );
25546 }
25547 }
25548
25549 #[test]
25550 fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
25551 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25552 // `:circuit-breaker :max-failures` zero-floor arm must key off
25553 // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
25554 // field access. Structurally: a `CircuitBreaker { max_failures:
25555 // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
25556 // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
25557 // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
25558 // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
25559 // pass validate. The pair jointly pins the accessor +
25560 // validate-gate composition: any future silent detour that had
25561 // the accessor return a fresh `1` on the zero arm (a
25562 // `.max_failures().max(1)` collapse) would silently absorb the
25563 // `PolicyBreakerZeroFailures` refusal at the accessor boundary
25564 // and the validate gate would accept a struct-literal
25565 // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
25566 // catches that at caixa-core build time.
25567 //
25568 // Peer of the sibling per-`:politicas`
25569 // [`MeshPolicy::mtls_required`] (c0110f1) /
25570 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25571 // (7073d0f) accessor-composition pins on the sibling optional-
25572 // scalar axes — same "the validate / shape-gate predicate must
25573 // route through the substrate-primitive typed dispatch"
25574 // discipline extended onto the peer per-`CircuitBreaker`
25575 // required-scalar composition axis.
25576 let mut spec = three_member_spec();
25577 spec.politicas = MeshPolicy {
25578 circuit_breaker: Some(CircuitBreaker {
25579 max_failures: 0,
25580 window: Duration::from_secs(60),
25581 }),
25582 ..MeshPolicy::default()
25583 };
25584 assert!(
25585 matches!(
25586 spec.validate(),
25587 Err(AplicacaoError::PolicyBreakerZeroFailures)
25588 ),
25589 "validate_politicas must reject max_failures == 0 with \
25590 PolicyBreakerZeroFailures — the accessor and the validate \
25591 gate must route through the same substrate-primitive typed \
25592 dispatch on the :max-failures zero-floor arm",
25593 );
25594 spec.politicas = MeshPolicy {
25595 circuit_breaker: Some(CircuitBreaker {
25596 max_failures: 1,
25597 window: Duration::from_secs(60),
25598 }),
25599 ..MeshPolicy::default()
25600 };
25601 assert!(
25602 spec.validate().is_ok(),
25603 "validate_politicas must accept max_failures == 1 (the \
25604 lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
25605 accept-set)",
25606 );
25607 }
25608
25609 #[test]
25610 fn circuit_breaker_max_failures_projects_u32_by_copy() {
25611 // The by-copy pin: [`CircuitBreaker::max_failures`] returns
25612 // `u32` by copy — `u32` is `Copy` and the accessor must return
25613 // by value, not by reference. Peer of the sibling
25614 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
25615 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25616 // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
25617 // optional-scalar axes, extended onto the peer
25618 // per-`CircuitBreaker` required-`u32` copy-invariant shape —
25619 // the accessor's returned `u32` must outlive `&self` (multiple
25620 // calls must return equal values from a dropped-`&self` copy,
25621 // since the returned scalar carries no borrow), and calling
25622 // the accessor twice on the same CircuitBreaker must yield the
25623 // same `u32` verbatim (idempotent, no side effects on `&self`).
25624 //
25625 // Pins against a future silent detour that returned `&u32`
25626 // (which would type-check but silently break every downstream
25627 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
25628 // first parameter is `u32`, and `&u32` would fold to a detached
25629 // copy at the call site with a `*` deref the sibling accessors
25630 // don't need), an accidental `.max_failures.wrapping_add(0)`
25631 // detour that returned a fresh copy through an arithmetic
25632 // no-op (breaking a future `const fn` regression), or a
25633 // one-arm-only accessor that returned a saturating value on
25634 // some sentinel input (breaking the pass-through invariant the
25635 // sibling required-scalar accessors carry).
25636 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25637 let cb = CircuitBreaker {
25638 max_failures,
25639 window: Duration::from_secs(60),
25640 };
25641 let first = cb.max_failures();
25642 let second = cb.max_failures();
25643 assert_eq!(
25644 first, second,
25645 "CircuitBreaker::max_failures must be idempotent — two \
25646 successive calls on the same &self must return the \
25647 same u32",
25648 );
25649 assert_eq!(
25650 first, max_failures,
25651 "CircuitBreaker::max_failures must return :politicas \
25652 :circuit-breaker :max-failures verbatim by copy — \
25653 got {first}, expected {max_failures}",
25654 );
25655 }
25656 }
25657
25658 #[test]
25659 fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
25660 // The canonical per-`:politicas :circuit-breaker` `:window`
25661 // Envoy-outlier-detection rolling-observation-interval scalar
25662 // pin: [`CircuitBreaker::window`] must return the
25663 // `:politicas :circuit-breaker :window` typed `Duration`
25664 // verbatim, byte-equal to the raw field access across every
25665 // representative value in the accept-set — `Duration::from_millis(1)`
25666 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25667 // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
25668 // gate carves out on the sibling `PolicyBreakerZeroWindow`
25669 // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
25670 // same gate carves out on the sibling
25671 // `PolicyBreakerWindowExceedsCap` refusal),
25672 // `Duration::ZERO` (a past-the-guard sentinel that pins the
25673 // accessor doesn't perform a silent bounds-collapse into
25674 // `Duration::from_millis(1)` on the zero arm — validate rejects
25675 // zero but the accessor must ship the raw slot verbatim so a
25676 // validate-time gate regression surfaces at the emit boundary
25677 // rather than being silently absorbed),
25678 // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
25679 // far above the 1h cap — that pins the accessor doesn't perform
25680 // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
25681 // at the return path).
25682 //
25683 // Second sub-struct required-scalar accessor pin on the M3
25684 // mesh-slot family — sibling in shape to the just-landed
25685 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25686 // (3a74062) required-`u32` accessor pin on the peer
25687 // per-`CircuitBreaker` required-axis, extended onto the
25688 // per-sub-struct required-`Duration` axis. Pins against a
25689 // future silent detour that re-derived the observation window
25690 // from a peer axis (an accidental
25691 // `Duration::from_secs(self.max_failures as u64)` collapse that
25692 // read the breaker's trip count as an observation-interval
25693 // duration), a `Duration::ZERO → Duration::from_millis(1)`
25694 // cluster-default projection (which would silently absorb the
25695 // `PolicyBreakerZeroWindow` refusal case at the accessor
25696 // boundary), or a bounds-collapsing accessor that clamped the
25697 // return through `POLICY_BREAKER_WINDOW_MAX` (the
25698 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25699 // must ship the raw slot verbatim).
25700 for window in [
25701 Duration::from_millis(1),
25702 POLICY_BREAKER_WINDOW_MAX,
25703 Duration::ZERO,
25704 Duration::from_secs(86_400),
25705 ] {
25706 let cb = CircuitBreaker {
25707 max_failures: 5,
25708 window,
25709 };
25710 assert_eq!(
25711 cb.window(),
25712 window,
25713 "CircuitBreaker::window must return :politicas \
25714 :circuit-breaker :window verbatim (got {:?}, \
25715 expected {window:?})",
25716 cb.window(),
25717 );
25718 assert_eq!(
25719 cb.window(),
25720 cb.window,
25721 "CircuitBreaker::window must byte-equal the raw \
25722 .window field access across every value in the \
25723 Duration accept-set",
25724 );
25725 }
25726 }
25727
25728 #[test]
25729 fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
25730 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25731 // `:circuit-breaker :window` zero-floor arm must key off
25732 // [`CircuitBreaker::window`], not the raw `.window` field
25733 // access. Structurally: a `CircuitBreaker { window:
25734 // Duration::ZERO, .. }` embedded in a
25735 // `:politicas :circuit-breaker` slot must surface the
25736 // `PolicyBreakerZeroWindow` refusal exactly, and a
25737 // `CircuitBreaker { window: Duration::from_millis(1), .. }`
25738 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25739 // accept-set) must pass validate. The pair jointly pins the
25740 // accessor + validate-gate composition: any future silent
25741 // detour that had the accessor return a fresh
25742 // `Duration::from_millis(1)` on the zero arm (a
25743 // `.window().max(Duration::from_millis(1))` collapse) would
25744 // silently absorb the `PolicyBreakerZeroWindow` refusal at the
25745 // accessor boundary and the validate gate would accept a
25746 // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
25747 // — the composition pin catches that at caixa-core build time.
25748 //
25749 // Peer of the sibling per-`CircuitBreaker`
25750 // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
25751 // pin on the peer required-scalar `:max-failures` axis — same
25752 // "the validate / shape-gate predicate must route through the
25753 // substrate-primitive typed dispatch" discipline extended onto
25754 // the peer per-`CircuitBreaker` required-`Duration` composition
25755 // axis.
25756 let mut spec = three_member_spec();
25757 spec.politicas = MeshPolicy {
25758 circuit_breaker: Some(CircuitBreaker {
25759 max_failures: 5,
25760 window: Duration::ZERO,
25761 }),
25762 ..MeshPolicy::default()
25763 };
25764 assert!(
25765 matches!(
25766 spec.validate(),
25767 Err(AplicacaoError::PolicyBreakerZeroWindow)
25768 ),
25769 "validate_politicas must reject window == Duration::ZERO \
25770 with PolicyBreakerZeroWindow — the accessor and the \
25771 validate gate must route through the same substrate-\
25772 primitive typed dispatch on the :window zero-floor arm",
25773 );
25774 spec.politicas = MeshPolicy {
25775 circuit_breaker: Some(CircuitBreaker {
25776 max_failures: 5,
25777 window: Duration::from_millis(1),
25778 }),
25779 ..MeshPolicy::default()
25780 };
25781 assert!(
25782 spec.validate().is_ok(),
25783 "validate_politicas must accept window == \
25784 Duration::from_millis(1) (the lower boundary of the \
25785 1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
25786 );
25787 }
25788
25789 #[test]
25790 fn circuit_breaker_window_projects_duration_by_copy() {
25791 // The by-copy pin: [`CircuitBreaker::window`] returns
25792 // `Duration` by copy — `Duration` is `Copy` and the accessor
25793 // must return by value, not by reference. Peer of the sibling
25794 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25795 // (3a74062) by-copy pin on the peer required-scalar
25796 // `:max-failures` axis, extended onto the peer
25797 // per-`CircuitBreaker` required-`Duration` copy-invariant shape
25798 // — the accessor's returned `Duration` must outlive `&self`
25799 // (multiple calls must return equal values from a
25800 // dropped-`&self` copy, since the returned scalar carries no
25801 // borrow), and calling the accessor twice on the same
25802 // CircuitBreaker must yield the same `Duration` verbatim
25803 // (idempotent, no side effects on `&self`).
25804 //
25805 // Pins against a future silent detour that returned
25806 // `&Duration` (which would type-check but silently break every
25807 // downstream `Duration`-by-value consumer —
25808 // [`crate::render::require_positive_canonical_bounded_duration`]'s
25809 // first parameter is `Duration`, and `&Duration` would fold to
25810 // a detached copy at the call site with a `*` deref the sibling
25811 // accessors don't need), an accidental `.window + Duration::ZERO`
25812 // detour that returned a fresh copy through an arithmetic
25813 // no-op (breaking a future `const fn` regression), or a
25814 // one-arm-only accessor that returned a saturating value on
25815 // some sentinel input (breaking the pass-through invariant the
25816 // sibling required-scalar accessors carry).
25817 for window in [
25818 Duration::from_millis(1),
25819 POLICY_BREAKER_WINDOW_MAX,
25820 Duration::ZERO,
25821 Duration::from_secs(86_400),
25822 ] {
25823 let cb = CircuitBreaker {
25824 max_failures: 5,
25825 window,
25826 };
25827 let first = cb.window();
25828 let second = cb.window();
25829 assert_eq!(
25830 first, second,
25831 "CircuitBreaker::window must be idempotent — two \
25832 successive calls on the same &self must return the \
25833 same Duration",
25834 );
25835 assert_eq!(
25836 first, window,
25837 "CircuitBreaker::window must return :politicas \
25838 :circuit-breaker :window verbatim by copy — \
25839 got {first:?}, expected {window:?}",
25840 );
25841 }
25842 }
25843
25844 #[test]
25845 fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
25846 // Apex-identity pair-invariant pin composing both substrate-
25847 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
25848 // and [`WitContract::destination`] — at the emit-side call shape
25849 // every per-`(:de, :para)` CNP L4 port reader now takes. The
25850 // invariant, evaluated per-edge:
25851 //
25852 // spec.port_for_destination(c.destination()) == expected_port
25853 //
25854 // where `expected_port` is `entrada.port` when
25855 // `c.destination() == entrada.destination()` and
25856 // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
25857 // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
25858 // pin on the per-`:entrada` axis — that pin encodes the apex
25859 // ingress L4 identity via `entrada.destination()`; this pin
25860 // encodes the per-edge L4 identity via `c.destination()`, and
25861 // both compose on the same substrate-primitive resolver so a
25862 // future refactor that silently split either accessor's apex
25863 // behavior surfaces at caixa-core build time.
25864 let mut spec = three_member_spec();
25865 if let Some(e) = spec.entrada.as_mut() {
25866 e.para = "cart".into();
25867 e.port = 8443;
25868 }
25869 let apex_contract = WitContract {
25870 de: "checkout".into(),
25871 para: "cart".into(),
25872 wit: "wasi:http/proxy".into(),
25873 endpoint: Some("/hello".into()),
25874 subject: None,
25875 slot: None,
25876 };
25877 assert_eq!(
25878 spec.port_for_destination(apex_contract.destination()),
25879 8443,
25880 "`spec.port_for_destination(c.destination())` must equal \
25881 `entrada.port` when the contract callee names the ingress \
25882 apex — the CNP per-edge L4 port and the HTTPRoute apex \
25883 backendRef port share this substrate-primitive resolver.",
25884 );
25885 let non_apex_contract = WitContract {
25886 de: "cart".into(),
25887 para: "payment".into(),
25888 wit: "wasi:http/proxy".into(),
25889 endpoint: Some("/charge".into()),
25890 subject: None,
25891 slot: None,
25892 };
25893 assert_eq!(
25894 spec.port_for_destination(non_apex_contract.destination()),
25895 DEFAULT_SERVICO_PORT,
25896 "`spec.port_for_destination(c.destination())` must fall back \
25897 to the substrate-canonical port floor when the contract \
25898 callee is not the ingress apex — the resolver's non-apex \
25899 arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
25900 );
25901 }
25902
25903 #[test]
25904 fn membro_key_consts_are_lower_camel_case_shape() {
25905 // Shape-pin: every `MEMBRO_KEY_*` const must be a
25906 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25907 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25908 // leading capital, no whitespace / dots) — the canonical shape
25909 // the `#[serde(rename_all = "camelCase")]` derive produces on
25910 // [`Membro`]. A future flip to a non-camelCase attribute at
25911 // the derive surfaces both here (this test fails on the
25912 // stale-constant shape) and at
25913 // `membro_serde_keys_match_lifted_membro_key_consts` (that test
25914 // fails on the mismatch between const and derive). Peer with
25915 // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
25916 // on the sibling `SupervisorSpec` top-level axis.
25917 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
25918 assert!(
25919 !key.is_empty(),
25920 "MEMBRO_KEY_* must be non-empty (got {key:?})"
25921 );
25922 let first = key.chars().next().unwrap();
25923 assert!(
25924 first.is_ascii_lowercase(),
25925 "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
25926 (got {key:?}, leads with {first:?})",
25927 );
25928 assert!(
25929 key.chars().all(|c| c.is_ascii_alphanumeric()),
25930 "MEMBRO_KEY_* must be ASCII-alphanumeric only \
25931 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25932 );
25933 }
25934 }
25935
25936 // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
25937
25938 #[test]
25939 fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
25940 // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
25941 // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
25942 // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
25943 // keys the `#[serde(rename_all = "camelCase")]` attribute on
25944 // [`WitContract`] emits for the required-triad. The three
25945 // sibling payload-arm keys already pin under
25946 // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
25947 // `STORE_FIELD_NAME` — pin all six alongside so a future
25948 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25949 // verbatim-field-name flip at the derive attribute (any of which
25950 // would silently break every downstream JSON consumer that
25951 // reaches for one of the six via `Value::get(...)`) surfaces
25952 // here as a build-time test failure at `aplicacao.rs`, not as an
25953 // apply-time `.get(<stale-canonical-const>)` returning `None`
25954 // far from the derive-attr drift's commit. Peer with the sibling
25955 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25956 // pin on the M3 `:membros` per-entry axis — same discipline the
25957 // `Membro` per-entry lift established, extended here to the
25958 // sibling M3 `WitContract` per-`:contratos` entry axis, the last
25959 // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
25960 // axis on the Aplicacao surface without a lifted serde-key peer.
25961 let c = WitContract {
25962 de: "cart".into(),
25963 para: "catalog".into(),
25964 wit: "wasi:http/proxy".into(),
25965 endpoint: Some("/lookup".into()),
25966 subject: None,
25967 slot: None,
25968 };
25969 let json = serde_json::to_string(&c).unwrap();
25970 for key in [
25971 crate::CONTRATO_KEY_DE,
25972 crate::CONTRATO_KEY_PARA,
25973 crate::CONTRATO_KEY_WIT,
25974 WitTarget::HTTP_FIELD_NAME,
25975 ] {
25976 let quoted = format!("\"{key}\"");
25977 assert!(
25978 json.contains("ed),
25979 "serialized WitContract must carry the lifted \
25980 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
25981 {quoted} verbatim in the JSON emission (got: {json})",
25982 );
25983 }
25984
25985 // Pin the two remaining payload-arm keys by round-tripping a
25986 // `WitContract` under each payload-shape (pub-sub, store) — the
25987 // required-triad appears on every emission but the payload arms
25988 // only surface when their `Option<String>` field is `Some`.
25989 let pubsub = WitContract {
25990 de: "cart".into(),
25991 para: "events".into(),
25992 wit: "nats:pub-sub".into(),
25993 endpoint: None,
25994 subject: Some("orders.placed".into()),
25995 slot: None,
25996 };
25997 let pubsub_json = serde_json::to_string(&pubsub).unwrap();
25998 let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
25999 assert!(
26000 pubsub_json.contains(&pubsub_quoted),
26001 "serialized pub-sub WitContract must carry the lifted \
26002 WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
26003 verbatim in the JSON emission (got: {pubsub_json})",
26004 );
26005 let store = WitContract {
26006 de: "cart".into(),
26007 para: "sessions".into(),
26008 wit: "wasi:keyvalue/store".into(),
26009 endpoint: None,
26010 subject: None,
26011 slot: Some("cart/$id".into()),
26012 };
26013 let store_json = serde_json::to_string(&store).unwrap();
26014 let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
26015 assert!(
26016 store_json.contains(&store_quoted),
26017 "serialized store WitContract must carry the lifted \
26018 WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
26019 verbatim in the JSON emission (got: {store_json})",
26020 );
26021 }
26022
26023 #[test]
26024 fn contrato_key_consts_are_pairwise_distinct() {
26025 // Cross-axis drift-detection pin: a future collapse of the six
26026 // canonical [`WitContract`] per-entry byte-strings onto the same
26027 // value (e.g. an accidental copy-paste flip of
26028 // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
26029 // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
26030 // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
26031 // every downstream probe on one axis onto the sibling axis's
26032 // overlay entry and pass every propagation-probe test that
26033 // expected only the stale axis's value. Peer of the sibling
26034 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
26035 // widened here to the six-way axis the `WitContract`
26036 // required-triad + `WitTarget` payload-triad jointly cover.
26037 let all = [
26038 crate::CONTRATO_KEY_DE,
26039 crate::CONTRATO_KEY_PARA,
26040 crate::CONTRATO_KEY_WIT,
26041 WitTarget::HTTP_FIELD_NAME,
26042 WitTarget::PUBSUB_FIELD_NAME,
26043 WitTarget::STORE_FIELD_NAME,
26044 ];
26045 for (i, a) in all.iter().enumerate() {
26046 for b in all.iter().skip(i + 1) {
26047 assert_ne!(
26048 a, b,
26049 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
26050 must be pairwise-distinct canonical byte-sequences \
26051 — got `{a}` == `{b}`",
26052 );
26053 }
26054 }
26055 }
26056
26057 #[test]
26058 fn contrato_key_consts_are_lower_camel_case_shape() {
26059 // Shape-pin: every `CONTRATO_KEY_*` (and every peer
26060 // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
26061 // byte-sequence (no `snake_case` underscores, no `kebab-case`
26062 // hyphens, no leading colon, no `PascalCase` leading capital, no
26063 // whitespace / dots) — the canonical shape the
26064 // `#[serde(rename_all = "camelCase")]` derive produces on
26065 // [`WitContract`]. A future flip to a non-camelCase attribute at
26066 // the derive surfaces both here (this test fails on the
26067 // stale-constant shape) and at
26068 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26069 // (that test fails on the mismatch between const and derive).
26070 // Peer with `membro_key_consts_are_lower_camel_case_shape`
26071 // (ce80ca0) on the sibling `Membro` per-entry axis.
26072 for key in [
26073 crate::CONTRATO_KEY_DE,
26074 crate::CONTRATO_KEY_PARA,
26075 crate::CONTRATO_KEY_WIT,
26076 WitTarget::HTTP_FIELD_NAME,
26077 WitTarget::PUBSUB_FIELD_NAME,
26078 WitTarget::STORE_FIELD_NAME,
26079 ] {
26080 assert!(
26081 !key.is_empty(),
26082 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26083 non-empty (got {key:?})"
26084 );
26085 let first = key.chars().next().unwrap();
26086 assert!(
26087 first.is_ascii_lowercase(),
26088 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
26089 with an ASCII-lowercase byte (got {key:?}, leads with \
26090 {first:?})",
26091 );
26092 assert!(
26093 key.chars().all(|c| c.is_ascii_alphanumeric()),
26094 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26095 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
26096 whitespace (got {key:?})",
26097 );
26098 }
26099 }
26100
26101 // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
26102
26103 #[test]
26104 fn entrada_serde_keys_match_lifted_entrada_key_consts() {
26105 // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
26106 // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
26107 // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
26108 // name the exact camelCase JSON keys the
26109 // `#[serde(rename_all = "camelCase")]` attribute on
26110 // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
26111 // pin that each canonical byte-sequence appears verbatim in the
26112 // JSON — a future accidental `rename_all = "snake_case"` /
26113 // `"kebab-case"` / verbatim-field-name flip at the derive
26114 // attribute (any of which would silently break every downstream
26115 // JSON consumer that reaches for one of the four consts via
26116 // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
26117 // emitter's per-Aplicacao hostname/paths/port projection, the
26118 // future `app-operator` reconciler's per-Aplicacao ingress
26119 // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
26120 // materializer's admission-time cross-check) surfaces here as
26121 // a build-time test failure at `aplicacao.rs`, not as an
26122 // apply-time `.get(<stale-canonical-const>)` returning `None`
26123 // far from the derive-attr drift's commit. Peer with the
26124 // sibling
26125 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26126 // (ca463a4) and
26127 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26128 // pins on the M3 collection-slot atom axes — same discipline
26129 // both collection-slot lifts established, extended here to the
26130 // singleton `:entrada` mesh-slot atom axis, the last M3
26131 // typed-struct top-level `#[serde(rename_all = "camelCase")]`
26132 // axis on the Aplicacao surface without a lifted serde-key
26133 // peer.
26134 let e = Entrada {
26135 host: "checkout.quero.cloud".into(),
26136 para: "cart".into(),
26137 paths: vec!["/cart".into()],
26138 port: 8080,
26139 };
26140 let json = serde_json::to_string(&e).unwrap();
26141 for key in [
26142 crate::ENTRADA_KEY_HOST,
26143 crate::ENTRADA_KEY_PARA,
26144 crate::ENTRADA_KEY_PATHS,
26145 crate::ENTRADA_KEY_PORT,
26146 ] {
26147 let quoted = format!("\"{key}\"");
26148 assert!(
26149 json.contains("ed),
26150 "serialized Entrada must carry the lifted ENTRADA_KEY_* \
26151 byte-sequence {quoted} verbatim in the JSON emission \
26152 (got: {json})",
26153 );
26154 }
26155 }
26156
26157 #[test]
26158 fn entrada_key_consts_are_pairwise_distinct() {
26159 // Cross-axis drift-detection pin: a future collapse of the four
26160 // canonical [`Entrada`] singleton byte-strings onto the same
26161 // value (e.g. an accidental copy-paste flip of
26162 // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
26163 // silently reroute every downstream probe on one axis onto the
26164 // sibling axis's overlay entry and pass every propagation-probe
26165 // test that expected only the stale axis's value — the
26166 // Gateway/HTTPRoute emitter would read the hostname string
26167 // where the destination-Servico name was expected (or vice
26168 // versa), the admission-webhook cross-check would compare the
26169 // wrong pair of values, and the resulting Gateway resource
26170 // would either be admitted with garbage or rejected at the
26171 // controller far from the rebrand commit's source. Peer of the
26172 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
26173 // tetrad (40cc4e5), the two-way distinct pin on the
26174 // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
26175 // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
26176 // triad (ca463a4).
26177 let all = [
26178 crate::ENTRADA_KEY_HOST,
26179 crate::ENTRADA_KEY_PARA,
26180 crate::ENTRADA_KEY_PATHS,
26181 crate::ENTRADA_KEY_PORT,
26182 ];
26183 for (i, a) in all.iter().enumerate() {
26184 for b in all.iter().skip(i + 1) {
26185 assert_ne!(
26186 a, b,
26187 "ENTRADA_KEY_* consts must be pairwise-distinct \
26188 canonical byte-sequences — got `{a}` == `{b}`",
26189 );
26190 }
26191 }
26192 }
26193
26194 #[test]
26195 fn entrada_key_consts_are_lower_camel_case_shape() {
26196 // Shape-pin: every `ENTRADA_KEY_*` const must be a
26197 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26198 // `kebab-case` hyphens, no leading colon, no `PascalCase`
26199 // leading capital, no whitespace / dots) — the canonical shape
26200 // the `#[serde(rename_all = "camelCase")]` derive produces on
26201 // [`Entrada`]. A future flip to a non-camelCase attribute at
26202 // the derive surfaces both here (this test fails on the
26203 // stale-constant shape) and at
26204 // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
26205 // test fails on the mismatch between const and derive). Peer
26206 // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
26207 // and `contrato_key_consts_are_lower_camel_case_shape`
26208 // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
26209 // entry axes.
26210 for key in [
26211 crate::ENTRADA_KEY_HOST,
26212 crate::ENTRADA_KEY_PARA,
26213 crate::ENTRADA_KEY_PATHS,
26214 crate::ENTRADA_KEY_PORT,
26215 ] {
26216 assert!(
26217 !key.is_empty(),
26218 "ENTRADA_KEY_* must be non-empty (got {key:?})"
26219 );
26220 let first = key.chars().next().unwrap();
26221 assert!(
26222 first.is_ascii_lowercase(),
26223 "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
26224 (got {key:?}, leads with {first:?})",
26225 );
26226 assert!(
26227 key.chars().all(|c| c.is_ascii_alphanumeric()),
26228 "ENTRADA_KEY_* must be ASCII-alphanumeric only \
26229 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26230 );
26231 }
26232 }
26233
26234 // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
26235
26236 #[test]
26237 fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
26238 // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
26239 // ([`crate::POLITICAS_KEY_TIMEOUT`] /
26240 // [`crate::POLITICAS_KEY_RETRIES`] /
26241 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
26242 // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
26243 // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
26244 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
26245 // on [`MeshPolicy`] emits. Three of the five axes
26246 // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
26247 // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
26248 // camelCase transforms — the derive-attribute is load-bearing
26249 // on those, unlike the sibling `Entrada` / `Membro` /
26250 // `WitContract` structs whose fields are all lowercase-single-
26251 // word and where the derive is a no-op on every axis.
26252 // Serialize a fully-populated [`MeshPolicy`] (every axis
26253 // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
26254 // on none of the five slots) and pin that each canonical
26255 // byte-sequence appears verbatim in the JSON — a future
26256 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26257 // verbatim-field-name flip at the derive attribute (any of
26258 // which would silently break every downstream JSON consumer
26259 // that reaches for one of the five consts via
26260 // `Value::get(...)` — the future M4 per-edge `:politicas`
26261 // overlay projection onto Cilium `L7Rules` and Gateway API
26262 // `HTTPRoute` backend timeouts, the future
26263 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26264 // admission-time mesh-policy cross-check, the future
26265 // `feira lint` per-`:politicas` bound-check gate) surfaces here
26266 // as a build-time test failure at `aplicacao.rs`, not as an
26267 // apply-time `.get(<stale-canonical-const>)` returning `None`
26268 // far from the derive-attr drift's commit. Peer with the
26269 // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
26270 // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26271 // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
26272 // (ce80ca0) pins on the M3 collection-slot / singleton-slot
26273 // atom axes — same discipline every M3 sibling lift
26274 // established, extended here to the singleton `:politicas`
26275 // mesh-slot atom axis, closing the last M3 typed-struct
26276 // top-level `#[serde(rename_all = "camelCase")]` axis on the
26277 // Aplicacao surface without a lifted serde-key peer.
26278 let p = MeshPolicy {
26279 timeout: Some(Duration::from_secs(30)),
26280 retries: Some(3),
26281 circuit_breaker: Some(CircuitBreaker {
26282 max_failures: 5,
26283 window: Duration::from_secs(60),
26284 }),
26285 mtls_required: Some(true),
26286 rate_limit: Some(RateLimit {
26287 rate: 100,
26288 window: Duration::from_secs(1),
26289 }),
26290 };
26291 let json = serde_json::to_string(&p).unwrap();
26292 for key in [
26293 crate::POLITICAS_KEY_TIMEOUT,
26294 crate::POLITICAS_KEY_RETRIES,
26295 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26296 crate::POLITICAS_KEY_MTLS_REQUIRED,
26297 crate::POLITICAS_KEY_RATE_LIMIT,
26298 ] {
26299 let quoted = format!("\"{key}\"");
26300 assert!(
26301 json.contains("ed),
26302 "serialized MeshPolicy must carry the lifted \
26303 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
26304 JSON emission (got: {json})",
26305 );
26306 }
26307 }
26308
26309 #[test]
26310 fn politicas_key_consts_are_pairwise_distinct() {
26311 // Cross-axis drift-detection pin: a future collapse of the five
26312 // canonical [`MeshPolicy`] singleton byte-strings onto the same
26313 // value (e.g. an accidental copy-paste flip of
26314 // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
26315 // would silently reroute every downstream probe on one axis
26316 // onto the sibling axis's overlay entry and pass every
26317 // propagation-probe test that expected only the stale axis's
26318 // value — the M4 per-edge `:politicas` overlay projection would
26319 // read the retry-count string where the timeout duration was
26320 // expected (or vice versa), the CR materializer's admission
26321 // cross-check would compare the wrong pair of values, and the
26322 // resulting mesh reconciler would either bind the wrong axis
26323 // or reject the resource at reconcile far from the rebrand
26324 // commit's source. Peer of the sibling four-way distinct pin
26325 // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
26326 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26327 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
26328 // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26329 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26330 let all = [
26331 crate::POLITICAS_KEY_TIMEOUT,
26332 crate::POLITICAS_KEY_RETRIES,
26333 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26334 crate::POLITICAS_KEY_MTLS_REQUIRED,
26335 crate::POLITICAS_KEY_RATE_LIMIT,
26336 ];
26337 for (i, a) in all.iter().enumerate() {
26338 for b in all.iter().skip(i + 1) {
26339 assert_ne!(
26340 a, b,
26341 "POLITICAS_KEY_* consts must be pairwise-distinct \
26342 canonical byte-sequences — got `{a}` == `{b}`",
26343 );
26344 }
26345 }
26346 }
26347
26348 #[test]
26349 fn politicas_key_consts_are_lower_camel_case_shape() {
26350 // Shape-pin: every `POLITICAS_KEY_*` const must be a
26351 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26352 // `kebab-case` hyphens, no leading colon, no `PascalCase`
26353 // leading capital, no whitespace / dots) — the canonical shape
26354 // the `#[serde(rename_all = "camelCase")]` derive produces on
26355 // [`MeshPolicy`]. A future flip to a non-camelCase attribute
26356 // at the derive surfaces both here (this test fails on the
26357 // stale-constant shape) and at
26358 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26359 // (that test fails on the mismatch between const and derive).
26360 // Peer with `entrada_key_consts_are_lower_camel_case_shape`
26361 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26362 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26363 // (ca463a4) on the sibling M3 typed-struct axes.
26364 for key in [
26365 crate::POLITICAS_KEY_TIMEOUT,
26366 crate::POLITICAS_KEY_RETRIES,
26367 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26368 crate::POLITICAS_KEY_MTLS_REQUIRED,
26369 crate::POLITICAS_KEY_RATE_LIMIT,
26370 ] {
26371 assert!(
26372 !key.is_empty(),
26373 "POLITICAS_KEY_* must be non-empty (got {key:?})"
26374 );
26375 let first = key.chars().next().unwrap();
26376 assert!(
26377 first.is_ascii_lowercase(),
26378 "POLITICAS_KEY_* must lead with an ASCII-lowercase \
26379 byte (got {key:?}, leads with {first:?})",
26380 );
26381 assert!(
26382 key.chars().all(|c| c.is_ascii_alphanumeric()),
26383 "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
26384 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26385 );
26386 }
26387 }
26388
26389 // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
26390
26391 #[test]
26392 fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
26393 // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
26394 // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
26395 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
26396 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26397 // [`CircuitBreaker`] emits inside the
26398 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
26399 // two axes (`max_failures` → `maxFailures`) is a non-trivial
26400 // camelCase transform — the derive-attribute is load-bearing on
26401 // that axis, unlike the sibling `window` field where the derive
26402 // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
26403 // pin that each canonical byte-sequence appears verbatim in the
26404 // JSON — a future accidental `rename_all = "snake_case"` /
26405 // `"kebab-case"` / verbatim-field-name flip at the derive
26406 // attribute (any of which would silently break every downstream
26407 // JSON consumer that reaches for one of the two consts via
26408 // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
26409 // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
26410 // per-edge `:politicas` overlay projection onto the mesh's
26411 // per-backend consecutive-failure-counter tripping threshold, the
26412 // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26413 // admission-time breaker cross-check, the future `feira lint`
26414 // per-`:politicas :circuit-breaker` bound-check gate) surfaces
26415 // here as a build-time test failure at `aplicacao.rs`, not as an
26416 // apply-time `.get(<stale-canonical-const>)` returning `None`
26417 // far from the derive-attr drift's commit. Peer with the sibling
26418 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26419 // (b55cca7) parent-axis pin — that test pins the outer
26420 // sub-block key the derive on [`MeshPolicy`] emits, this test
26421 // pins the inner keys the derive on the payload type emits, so
26422 // the two together lock the whole [`MeshPolicy`] breaker-tuning
26423 // shape end-to-end at build time.
26424 let cb = CircuitBreaker {
26425 max_failures: 5,
26426 window: Duration::from_secs(60),
26427 };
26428 let json = serde_json::to_string(&cb).unwrap();
26429 for key in [
26430 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26431 crate::CIRCUIT_BREAKER_KEY_WINDOW,
26432 ] {
26433 let quoted = format!("\"{key}\"");
26434 assert!(
26435 json.contains("ed),
26436 "serialized CircuitBreaker must carry the lifted \
26437 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
26438 in the JSON emission (got: {json})",
26439 );
26440 }
26441 }
26442
26443 #[test]
26444 fn circuit_breaker_key_consts_are_pairwise_distinct() {
26445 // Cross-axis drift-detection pin: a future collapse of the two
26446 // canonical [`CircuitBreaker`] sub-block byte-strings onto the
26447 // same value (e.g. an accidental copy-paste flip of
26448 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
26449 // `"maxFailures"`) would silently reroute every downstream
26450 // probe on one axis onto the sibling axis's overlay entry and
26451 // pass every propagation-probe test that expected only the
26452 // stale axis's value — the M4 per-edge `:politicas` overlay
26453 // projection would read the failure-count where the window
26454 // duration was expected (or vice versa), the CR materializer's
26455 // admission cross-check would compare the wrong pair of values,
26456 // and the resulting mesh reconciler would either bind the wrong
26457 // axis or reject the resource at reconcile far from the rebrand
26458 // commit's source. Peer of the sibling five-way distinct pin on
26459 // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
26460 // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
26461 // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
26462 // six-way distinct pin on the `CONTRATO_KEY_*` triad +
26463 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26464 let all = [
26465 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26466 crate::CIRCUIT_BREAKER_KEY_WINDOW,
26467 ];
26468 for (i, a) in all.iter().enumerate() {
26469 for b in all.iter().skip(i + 1) {
26470 assert_ne!(
26471 a, b,
26472 "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
26473 canonical byte-sequences — got `{a}` == `{b}`",
26474 );
26475 }
26476 }
26477 }
26478
26479 #[test]
26480 fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
26481 // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
26482 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26483 // `kebab-case` hyphens, no leading colon, no `PascalCase`
26484 // leading capital, no whitespace / dots) — the canonical shape
26485 // the `#[serde(rename_all = "camelCase")]` derive produces on
26486 // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
26487 // at the derive surfaces both here (this test fails on the
26488 // stale-constant shape) and at
26489 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26490 // (that test fails on the mismatch between const and derive).
26491 // Peer with `politicas_key_consts_are_lower_camel_case_shape`
26492 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26493 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26494 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26495 // (ca463a4) on the sibling M3 typed-struct axes.
26496 for key in [
26497 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26498 crate::CIRCUIT_BREAKER_KEY_WINDOW,
26499 ] {
26500 assert!(
26501 !key.is_empty(),
26502 "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
26503 );
26504 let first = key.chars().next().unwrap();
26505 assert!(
26506 first.is_ascii_lowercase(),
26507 "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
26508 byte (got {key:?}, leads with {first:?})",
26509 );
26510 assert!(
26511 key.chars().all(|c| c.is_ascii_alphanumeric()),
26512 "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
26513 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26514 );
26515 }
26516 }
26517
26518 // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
26519
26520 #[test]
26521 fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
26522 // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
26523 // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
26524 // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
26525 // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
26526 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
26527 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26528 // [`Placement`] emits. One of the four axes (`shard_key` →
26529 // `shardKey`) is a non-trivial camelCase transform — the
26530 // derive-attribute is load-bearing on that axis, unlike the
26531 // sibling `estrategia` / `clusters` / `affinity` axes whose
26532 // source-side field names carry no `_` and where the derive is a
26533 // no-op. Serialize a fully-populated [`Placement`] (both
26534 // `Option`-carrying axes `Some(_)` so
26535 // `skip_serializing_if = "Option::is_none"` fires on neither of
26536 // the two optional slots) and pin that each canonical
26537 // byte-sequence appears verbatim in the JSON — a future
26538 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26539 // verbatim-field-name flip at the derive attribute (any of which
26540 // would silently break every downstream consumer that reaches
26541 // for one of the four consts via
26542 // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
26543 // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
26544 // aggregator's per-cluster fanout filter keying off
26545 // `placement.clusters`, the M3 shard-pool dispatch materializer
26546 // keying off `placement.shardKey`, the M3 Adaptive compression
26547 // pass weighting off `placement.affinity`, every downstream
26548 // dispatcher branching on `placement.estrategia`, the future
26549 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26550 // admission-time placement cross-check, the future `feira lint`
26551 // per-`:placement` bound-check gate) surfaces here as a
26552 // build-time test failure at `aplicacao.rs`, not as an
26553 // apply-time `.get(<stale-canonical-const>)` returning `None`
26554 // far from the derive-attr drift's commit. Peer with the sibling
26555 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26556 // (b55cca7),
26557 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26558 // (468e959),
26559 // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
26560 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26561 // (ca463a4), and
26562 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26563 // pins on the M3 collection-slot / singleton-slot atom axes —
26564 // closes the last M3 typed-struct top-level
26565 // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
26566 // surface without a drift-detection pin.
26567 let p = Placement {
26568 estrategia: PlacementStrategy::Sharded,
26569 clusters: vec!["rio".into(), "mar".into()],
26570 affinity: Some("data-locality".into()),
26571 shard_key: Some("$tenantId".into()),
26572 };
26573 let json = serde_json::to_string(&p).unwrap();
26574 for key in [
26575 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26576 crate::M3_PLACEMENT_KEY_CLUSTERS,
26577 crate::M3_PLACEMENT_KEY_AFFINITY,
26578 crate::M3_PLACEMENT_KEY_SHARD_KEY,
26579 ] {
26580 let quoted = format!("\"{key}\"");
26581 assert!(
26582 json.contains("ed),
26583 "serialized Placement must carry the lifted \
26584 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
26585 the JSON emission (got: {json})",
26586 );
26587 }
26588 }
26589
26590 #[test]
26591 fn m3_placement_key_consts_are_pairwise_distinct() {
26592 // Cross-axis drift-detection pin: a future collapse of the four
26593 // canonical [`Placement`] sub-block byte-strings onto the same
26594 // value (e.g. an accidental copy-paste flip of
26595 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
26596 // `"affinity"`) would silently reroute every downstream probe on
26597 // one axis onto the sibling axis's overlay entry and pass every
26598 // propagation-probe test that expected only the stale axis's
26599 // value — the M3 shard-pool dispatch materializer would read the
26600 // affinity placement-hint where the shard-selection template was
26601 // expected (or vice versa), the M3 Adaptive compression pass's
26602 // cross-check would compare the wrong pair of values, and the
26603 // resulting placement engine would either bind the wrong axis or
26604 // reject the resource at reconcile far from the rebrand commit's
26605 // source. Peer of the sibling two-way distinct pin on the
26606 // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
26607 // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
26608 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26609 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
26610 // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26611 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26612 let all = [
26613 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26614 crate::M3_PLACEMENT_KEY_CLUSTERS,
26615 crate::M3_PLACEMENT_KEY_AFFINITY,
26616 crate::M3_PLACEMENT_KEY_SHARD_KEY,
26617 ];
26618 for (i, a) in all.iter().enumerate() {
26619 for b in all.iter().skip(i + 1) {
26620 assert_ne!(
26621 a, b,
26622 "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
26623 canonical byte-sequences — got `{a}` == `{b}`",
26624 );
26625 }
26626 }
26627 }
26628
26629 #[test]
26630 fn m3_placement_key_consts_are_lower_camel_case_shape() {
26631 // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
26632 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26633 // `kebab-case` hyphens, no leading colon, no `PascalCase`
26634 // leading capital, no whitespace / dots) — the canonical shape
26635 // the `#[serde(rename_all = "camelCase")]` derive produces on
26636 // [`Placement`]. A future flip to a non-camelCase attribute at
26637 // the derive surfaces both here (this test fails on the stale-
26638 // constant shape) and at
26639 // `placement_serde_keys_match_lifted_m3_placement_key_consts`
26640 // (that test fails on the mismatch between const and derive).
26641 // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
26642 // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
26643 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26644 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26645 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26646 // (ca463a4) on the sibling M3 typed-struct axes.
26647 for key in [
26648 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26649 crate::M3_PLACEMENT_KEY_CLUSTERS,
26650 crate::M3_PLACEMENT_KEY_AFFINITY,
26651 crate::M3_PLACEMENT_KEY_SHARD_KEY,
26652 ] {
26653 assert!(
26654 !key.is_empty(),
26655 "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
26656 );
26657 let first = key.chars().next().unwrap();
26658 assert!(
26659 first.is_ascii_lowercase(),
26660 "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
26661 byte (got {key:?}, leads with {first:?})",
26662 );
26663 assert!(
26664 key.chars().all(|c| c.is_ascii_alphanumeric()),
26665 "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
26666 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26667 );
26668 }
26669 }
26670
26671 // ── AplicacaoSpec::port_for_destination — the substrate-canonical
26672 // destination-facing L4 port resolver every per-Aplicacao renderer
26673 // reaching for a per-destination Servico TCP port axis routes
26674 // through. The four pin tests below fix the four-way accept-set
26675 // the resolver must always honor: (:entrada-para-matches,
26676 // :entrada-para-mismatches, :entrada-none-so-fallback,
26677 // :entrada-port-non-default-honored) — drift on any arm surfaces
26678 // at caixa-core build time rather than at cluster-apply time.
26679
26680 #[test]
26681 fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
26682 // The typed `:entrada` block's `:para "cart"` matches the
26683 // queried destination, so the resolver returns the author-
26684 // declared `:port` scalar verbatim — the canonical "the
26685 // destination Servico IS the ingress apex, honor the typed
26686 // listener port" arm of the port-resolution dispatch.
26687 let mut spec = three_member_spec();
26688 if let Some(e) = spec.entrada.as_mut() {
26689 e.para = "cart".into();
26690 e.port = 9090;
26691 }
26692 assert_eq!(
26693 spec.port_for_destination("cart"),
26694 9090,
26695 "port_for_destination(entrada.para) must return entrada.port \
26696 verbatim, not the DEFAULT_SERVICO_PORT fallback"
26697 );
26698 }
26699
26700 #[test]
26701 fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
26702 // The typed `:entrada` block names `:para "cart"`, but the
26703 // queried destination is `"payment"` — a Servico that
26704 // participates in the mesh graph but is not the ingress apex.
26705 // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
26706 // canonical port floor, closing the "non-apex destination reads
26707 // the substrate default" arm. Same fixture the peer
26708 // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
26709 // pin at caixa-mesh exercises through the CNP emit-side path;
26710 // this pin exercises the shared underlying resolver directly.
26711 let spec = three_member_spec();
26712 assert_eq!(
26713 spec.port_for_destination("payment"),
26714 DEFAULT_SERVICO_PORT,
26715 "port_for_destination(non-apex-destination) must route \
26716 through the lifted DEFAULT_SERVICO_PORT canonical port floor"
26717 );
26718 }
26719
26720 #[test]
26721 fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
26722 // Internal-only Aplicacao — no `:entrada` block declared. Every
26723 // per-destination port query falls back to the lifted
26724 // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
26725 // the Aplicacao surface admits `:entrada None` (internal mesh
26726 // with no external gateway); every downstream renderer's per-
26727 // destination port axis must still resolve to a well-defined
26728 // scalar even without an ingress apex.
26729 let mut spec = three_member_spec();
26730 spec.entrada = None;
26731 assert_eq!(
26732 spec.port_for_destination("cart"),
26733 DEFAULT_SERVICO_PORT,
26734 "port_for_destination on an internal-only Aplicacao must \
26735 fall back to the lifted DEFAULT_SERVICO_PORT floor for \
26736 every destination"
26737 );
26738 assert_eq!(
26739 spec.port_for_destination("payment"),
26740 DEFAULT_SERVICO_PORT,
26741 "port_for_destination on an internal-only Aplicacao must \
26742 fall back uniformly across every destination — the fallback \
26743 is not entrada-shape-conditional"
26744 );
26745 }
26746
26747 #[test]
26748 fn port_for_destination_honors_non_default_entrada_port_verbatim() {
26749 // Structural pin against a hypothetical future refactor that
26750 // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
26751 // the resolver (a "normalize to the default when the author's
26752 // port matches the substrate default" collapse) — that would
26753 // break renderer sites that carry meaning on the emitted port
26754 // value beyond bare equality (a future per-cluster listener-
26755 // audit that keys off the author-declared port, not the
26756 // resolved-with-fallback port). Pin that a non-default
26757 // entrada.port is returned verbatim so drift here surfaces at
26758 // caixa-core build time.
26759 let mut spec = three_member_spec();
26760 if let Some(e) = spec.entrada.as_mut() {
26761 e.para = "cart".into();
26762 e.port = 8443;
26763 }
26764 assert_ne!(
26765 8443, DEFAULT_SERVICO_PORT,
26766 "test fixture must probe a port distinct from \
26767 DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
26768 );
26769 assert_eq!(
26770 spec.port_for_destination("cart"),
26771 8443,
26772 "port_for_destination(entrada.para) must return entrada.port \
26773 verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
26774 );
26775 }
26776
26777 #[test]
26778 fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
26779 // Apex-identity pair-invariant pin composing both substrate-
26780 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26781 // and [`Entrada::destination`] — at the emit-side call shape
26782 // every per-Aplicacao renderer's ingress-apex L4 port reader
26783 // now takes. The invariant:
26784 //
26785 // spec.port_for_destination(entrada.destination()) == entrada.port
26786 //
26787 // holds by construction under today's single-destination
26788 // `:entrada` slot (`destination()` returns `entrada.para`, and
26789 // the resolver's apex arm matches `para == destination` and
26790 // returns `entrada.port`), and every downstream consumer that
26791 // composes the two accessors at the ingress apex — the
26792 // `caixa_mesh::gateway_routes` HTTPRoute per-rule
26793 // `backendRefs[0].port` emit-site path, the peer future M4 CR
26794 // materializer's admission-webhook that promotes the scalar to
26795 // a per-CR override overlay, every future per-Aplicacao snapshot
26796 // renderer's apex-facing L4 port reader — reaches through the
26797 // same composition. Pin the identity across four permutations
26798 // (`:para` × `:port` including a non-default port to exercise
26799 // the honor-verbatim arm and a non-cart `:para` to exercise
26800 // destination-agnostic identity) so a future refactor that
26801 // silently split either accessor's apex behavior surfaces at
26802 // caixa-core build time — a subtle `destination()` renaming
26803 // that returned `entrada.host.as_str()` instead of
26804 // `entrada.para.as_str()` would blow this pin loudly, closing
26805 // the last quiet failure mode the two lifts admit in composition.
26806 //
26807 // Peer discipline with the sibling caixa-mesh cross-crate pin
26808 // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
26809 // on the two-renderer pair-invariant axis; this pin encodes the
26810 // same two-consumer coherence rule at the substrate-primitive
26811 // level so the invariant survives even if every renderer is
26812 // deleted.
26813 for (para, port) in [
26814 ("cart", DEFAULT_SERVICO_PORT),
26815 ("cart", 8443u16),
26816 ("payment", 9090u16),
26817 ("catalog", 443u16),
26818 ] {
26819 let mut spec = three_member_spec();
26820 if let Some(e) = spec.entrada.as_mut() {
26821 e.para = para.into();
26822 e.port = port;
26823 }
26824 let expected_port = spec
26825 .entrada()
26826 .expect("three_member_spec carries a typed `:entrada` block")
26827 .port();
26828 let composed_port = {
26829 let entrada = spec.entrada().expect("entrada present");
26830 spec.port_for_destination(entrada.destination())
26831 };
26832 assert_eq!(
26833 composed_port, expected_port,
26834 "`spec.port_for_destination(entrada.destination())` must \
26835 equal `entrada.port` under today's single-destination \
26836 `:entrada` slot — this is the apex-identity contract \
26837 every downstream ingress-apex L4 port reader relies on. \
26838 Input :entrada :para: {para:?}, :entrada :port: {port}"
26839 );
26840 }
26841 }
26842
26843 #[test]
26844 fn port_for_destination_apex_arm_routes_through_destination_accessor() {
26845 // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
26846 // per-`:entrada` apex-arm membership probe must key off
26847 // [`Entrada::destination`], not the raw `.para` field access.
26848 // Structurally: setting ONLY the `:entrada :para` field to a
26849 // fresh non-cart destination on an otherwise-well-formed
26850 // Aplicacao must (1) leave `e.destination()` byte-equal to
26851 // `e.para.as_str()` (the accessor is byte-projective by
26852 // definition), and (2) cause the resolver's apex arm to fire
26853 // and return `entrada.port` at exactly that new destination
26854 // while every other destination string falls through to
26855 // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
26856 // membership check. Pins against a future silent detour that
26857 // (a) re-derived the apex-arm membership probe off
26858 // `e.para == destination` in `port_for_destination` instead of
26859 // `e.destination() == destination`, silently disagreeing with
26860 // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
26861 // consumers (`entrada.destination()` at
26862 // caixa-mesh/src/lib.rs:3173, `c.destination()` at
26863 // caixa-mesh/src/lib.rs:2739) that already reach through the
26864 // accessor, (b) accessor-side introduced a per-tenant alias
26865 // arm the caller was unaware of, silently rewriting an
26866 // author-declared `:para "cart"` value to a canary-aliased
26867 // form — the raw-field-access resolver would fall through to
26868 // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
26869 // while the peer emit-site consumers landed on the aliased
26870 // destination, splitting the ingress-apex L4 port at
26871 // cluster-apply time.
26872 //
26873 // Peer of the sibling
26874 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
26875 // (d0de220) composition pin on the per-`:membros` refusal-arm
26876 // axis — same "the shape-gate predicate must route through the
26877 // substrate-primitive typed dispatch" discipline extended onto
26878 // the per-`:entrada` apex-arm membership-probe axis. Closes
26879 // the last unlifted `.para` production-code read site on
26880 // `Entrada` in `caixa-core` — after this converge every
26881 // `caixa-core` `.para` field access outside the accessor's own
26882 // body and outside the `WitContract` per-`:contratos` sibling
26883 // axis is either a test-side field-setter or a doc-comment
26884 // reference.
26885 for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
26886 let mut spec = three_member_spec();
26887 if let Some(e) = spec.entrada.as_mut() {
26888 e.para = para.into();
26889 e.port = port;
26890 }
26891 let e = spec
26892 .entrada
26893 .as_ref()
26894 .expect("three_member_spec carries a typed `:entrada` block");
26895 assert_eq!(
26896 e.destination(),
26897 e.para.as_str(),
26898 "Entrada::destination must byte-equal the .para field \
26899 access — an accessor-side detour that no longer \
26900 projects the raw field would silently split this \
26901 drift-detection test from the port_for_destination \
26902 apex-arm membership probe",
26903 );
26904 assert_eq!(
26905 spec.port_for_destination(para),
26906 port,
26907 "port_for_destination must key off the accessor-projected \
26908 destination and return `entrada.port` on the apex arm — \
26909 input :entrada :para: {para:?}, :entrada :port: {port}",
26910 );
26911 assert_eq!(
26912 spec.port_for_destination("ghost-destination-never-a-member"),
26913 DEFAULT_SERVICO_PORT,
26914 "port_for_destination must fall through to \
26915 DEFAULT_SERVICO_PORT on a non-matching destination \
26916 under the accessor-projected membership check — input \
26917 :entrada :para: {para:?}, :entrada :port: {port}",
26918 );
26919 }
26920 }
26921
26922 #[test]
26923 fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
26924 // The canonical per-`:politicas :rate-limit` `:rate`
26925 // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
26926 // [`RateLimit::rate`] must return the `:politicas :rate-limit`
26927 // typed `u32` verbatim, byte-equal to the raw field access
26928 // across every representative value in the accept-set — `1` (the
26929 // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
26930 // the surrounding [`AplicacaoSpec::validate_politicas`] gate
26931 // carves out on the sibling `PolicyRateLimitZero` refusal),
26932 // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
26933 // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
26934 // `0` (a past-the-guard sentinel that pins the accessor doesn't
26935 // perform a silent bounds-collapse into `1` on the zero arm —
26936 // validate rejects zero but the accessor must ship the raw slot
26937 // verbatim so a validate-time gate regression surfaces at the
26938 // emit boundary rather than being silently absorbed), `u32::MAX`
26939 // (a past-the-guard sentinel that pins the accessor doesn't
26940 // perform a silent bounds-collapse through
26941 // `POLICY_RATE_LIMIT_MAX` at the return path).
26942 //
26943 // First sub-struct required-scalar accessor pin on the
26944 // `RateLimit` axis — sibling in shape to the peer
26945 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
26946 // required-`u32` accessor pin on the peer per-sub-struct
26947 // required-axis. Pins against a future silent detour that
26948 // re-derived the token capacity from a peer axis (an accidental
26949 // `self.window.as_secs() as u32` collapse that read the
26950 // rate-limit window duration as a token count), a `0 → 1`
26951 // cluster-default projection (which would silently absorb the
26952 // `PolicyRateLimitZero` refusal case at the accessor boundary),
26953 // or a bounds-collapsing accessor that clamped the return
26954 // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
26955 // gate owns the bounds; the accessor must ship the raw slot
26956 // verbatim).
26957 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
26958 let rl = RateLimit {
26959 rate,
26960 window: Duration::from_secs(1),
26961 };
26962 assert_eq!(
26963 rl.rate(),
26964 rate,
26965 "RateLimit::rate must return :politicas :rate-limit :rate \
26966 verbatim (got {}, expected {rate})",
26967 rl.rate(),
26968 );
26969 assert_eq!(
26970 rl.rate(),
26971 rl.rate,
26972 "RateLimit::rate must byte-equal the raw .rate field \
26973 access across every value in the u32 accept-set",
26974 );
26975 }
26976 }
26977
26978 #[test]
26979 fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
26980 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26981 // `:rate-limit :rate` zero-floor arm must key off
26982 // [`RateLimit::rate`], not the raw `.rate` field access.
26983 // Structurally: a `RateLimit { rate: 0, window:
26984 // Duration::from_secs(1) }` embedded in a `:politicas
26985 // :rate-limit` slot must surface the `PolicyRateLimitZero`
26986 // refusal exactly, and a `RateLimit { rate: 1, window:
26987 // Duration::from_secs(1) }` (the lower boundary of the
26988 // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
26989 // The pair jointly pins the accessor + validate-gate composition:
26990 // any future silent detour that had the accessor return a fresh
26991 // `1` on the zero arm (a `.rate().max(1)` collapse) would
26992 // silently absorb the `PolicyRateLimitZero` refusal at the
26993 // accessor boundary and the validate gate would accept a
26994 // struct-literal `RateLimit { rate: 0, .. }` — the composition
26995 // pin catches that at caixa-core build time.
26996 //
26997 // Peer of the sibling per-`CircuitBreaker`
26998 // [`CircuitBreaker::max_failures`] (3a74062) /
26999 // [`CircuitBreaker::window`] (373957f) accessor-composition
27000 // pins on the peer required-scalar axes — same "the validate /
27001 // shape-gate predicate must route through the substrate-primitive
27002 // typed dispatch" discipline extended onto the peer
27003 // per-`RateLimit` required-`u32` composition axis.
27004 let mut spec = three_member_spec();
27005 spec.politicas = MeshPolicy {
27006 rate_limit: Some(RateLimit {
27007 rate: 0,
27008 window: Duration::from_secs(1),
27009 }),
27010 ..MeshPolicy::default()
27011 };
27012 assert!(
27013 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
27014 "validate_politicas must reject rate == 0 with \
27015 PolicyRateLimitZero — the accessor and the validate gate \
27016 must route through the same substrate-primitive typed \
27017 dispatch on the :rate zero-floor arm",
27018 );
27019 spec.politicas = MeshPolicy {
27020 rate_limit: Some(RateLimit {
27021 rate: 1,
27022 window: Duration::from_secs(1),
27023 }),
27024 ..MeshPolicy::default()
27025 };
27026 assert!(
27027 spec.validate().is_ok(),
27028 "validate_politicas must accept rate == 1 (the lower \
27029 boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
27030 );
27031 }
27032
27033 #[test]
27034 fn rate_limit_rate_projects_u32_by_copy() {
27035 // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
27036 // `u32` is `Copy` and the accessor must return by value, not by
27037 // reference. Peer of the sibling per-`CircuitBreaker`
27038 // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
27039 // peer required-scalar `:max-failures` axis, extended onto the
27040 // peer per-`RateLimit` required-`u32` copy-invariant shape —
27041 // the accessor's returned `u32` must outlive `&self` (multiple
27042 // calls must return equal values from a dropped-`&self` copy,
27043 // since the returned scalar carries no borrow), and calling the
27044 // accessor twice on the same RateLimit must yield the same
27045 // `u32` verbatim (idempotent, no side effects on `&self`).
27046 //
27047 // Pins against a future silent detour that returned `&u32`
27048 // (which would type-check but silently break every downstream
27049 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
27050 // first parameter is `u32`, and `&u32` would fold to a detached
27051 // copy at the call site with a `*` deref the sibling accessors
27052 // don't need), an accidental `.rate.wrapping_add(0)` detour that
27053 // returned a fresh copy through an arithmetic no-op (breaking a
27054 // future `const fn` regression), or a one-arm-only accessor
27055 // that returned a saturating value on some sentinel input
27056 // (breaking the pass-through invariant the sibling required-
27057 // scalar accessors carry).
27058 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27059 let rl = RateLimit {
27060 rate,
27061 window: Duration::from_secs(1),
27062 };
27063 let first = rl.rate();
27064 let second = rl.rate();
27065 assert_eq!(
27066 first, second,
27067 "RateLimit::rate must be idempotent — two successive \
27068 calls on the same &self must return the same u32",
27069 );
27070 assert_eq!(
27071 first, rate,
27072 "RateLimit::rate must return :politicas :rate-limit :rate \
27073 verbatim by copy — got {first}, expected {rate}",
27074 );
27075 }
27076 }
27077
27078 #[test]
27079 fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
27080 // The canonical per-`:politicas :rate-limit` `:window`
27081 // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
27082 // pin: [`RateLimit::window`] must return the
27083 // `:politicas :rate-limit :window` typed `Duration` verbatim,
27084 // byte-equal to the raw field access across every
27085 // representative value in the accept-set — `Duration::from_secs(1)`
27086 // (the `"s"` canonical window, the lower row of
27087 // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
27088 // [`AplicacaoSpec::validate_politicas`] gate accepts via
27089 // [`is_canonical_rate_limit_window`]),
27090 // `Duration::from_secs(60)` (the `"m"` canonical window, the
27091 // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
27092 // window, the upper row), `Duration::ZERO` (a past-the-guard
27093 // sentinel that pins the accessor doesn't perform a silent
27094 // bounds-collapse into `Duration::from_secs(1)` on the zero
27095 // arm — validate rejects an off-set window through
27096 // `PolicyRateLimitWindowNotCanonical` but the accessor must
27097 // ship the raw slot verbatim so a validate-time gate
27098 // regression surfaces at the emit boundary rather than being
27099 // silently absorbed), `Duration::from_millis(500)` (a
27100 // sub-canonical past-the-guard sentinel that pins the accessor
27101 // doesn't silently normalize a non-canonical fractional
27102 // magnitude onto the nearest canonical row).
27103 //
27104 // Second sub-struct required-scalar accessor pin on the
27105 // `RateLimit` axis — sibling in shape to the just-landed
27106 // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
27107 // accessor pin on the peer per-sub-struct required-axis,
27108 // extended onto the per-`RateLimit` required-`Duration` axis.
27109 // Pins against a future silent detour that re-derived the
27110 // refill period from a peer axis (an accidental
27111 // `Duration::from_secs(self.rate as u64)` collapse that read
27112 // the rate-limit token capacity as a refill-interval
27113 // duration), a `Duration::ZERO → Duration::from_secs(1)`
27114 // canonical-default projection (which would silently absorb
27115 // the `PolicyRateLimitWindowNotCanonical` refusal case at the
27116 // accessor boundary), or a canonical-set-collapsing accessor
27117 // that clamped the return through [`rate_limit_window_unit`]
27118 // (the `AplicacaoSpec::validate` gate owns the canonical-set
27119 // membership; the accessor must ship the raw slot verbatim).
27120 for window in [
27121 Duration::from_secs(1),
27122 Duration::from_secs(60),
27123 Duration::from_secs(3600),
27124 Duration::ZERO,
27125 Duration::from_millis(500),
27126 ] {
27127 let rl = RateLimit { rate: 100, window };
27128 assert_eq!(
27129 rl.window(),
27130 window,
27131 "RateLimit::window must return :politicas :rate-limit :window \
27132 verbatim (got {:?}, expected {window:?})",
27133 rl.window(),
27134 );
27135 assert_eq!(
27136 rl.window(),
27137 rl.window,
27138 "RateLimit::window must byte-equal the raw .window field \
27139 access across every value in the Duration accept-set",
27140 );
27141 }
27142 }
27143
27144 #[test]
27145 fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
27146 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27147 // `:rate-limit :window` canonical-set arm must key off
27148 // [`RateLimit::window`], not the raw `.window` field access.
27149 // Structurally: a `RateLimit { window: Duration::from_millis(500),
27150 // .. }` embedded in a `:politicas :rate-limit` slot must
27151 // surface the `PolicyRateLimitWindowNotCanonical` refusal
27152 // exactly (with the sub-canonical `Duration::from_millis(500)`
27153 // magnitude carried through verbatim), and a `RateLimit
27154 // { window: Duration::from_secs(1), .. }` (the lower row of
27155 // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
27156 // The pair jointly pins the accessor + validate-gate
27157 // composition: any future silent detour that had the accessor
27158 // normalize the off-set window to the nearest canonical row
27159 // (a `.window().max(Duration::from_secs(1))` collapse, or a
27160 // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
27161 // collapse) would silently absorb the
27162 // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
27163 // boundary — including a drift in the error's `window` payload
27164 // (the emit-side diagnostic reader keys off the offending
27165 // magnitude verbatim, so a normalization at the accessor
27166 // boundary would silently pin the wrong magnitude in the
27167 // refusal). The composition pin catches that at caixa-core
27168 // build time.
27169 //
27170 // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
27171 // (7f81a60) accessor-composition pin on the peer required-
27172 // scalar `:rate` axis — same "the validate / shape-gate
27173 // predicate must route through the substrate-primitive typed
27174 // dispatch, and the error payload must project through the
27175 // same accessor" discipline extended onto the peer
27176 // per-`RateLimit` required-`Duration` composition axis.
27177 let mut spec = three_member_spec();
27178 spec.politicas = MeshPolicy {
27179 rate_limit: Some(RateLimit {
27180 rate: 100,
27181 window: Duration::from_millis(500),
27182 }),
27183 ..MeshPolicy::default()
27184 };
27185 match spec.validate() {
27186 Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
27187 assert_eq!(
27188 window,
27189 Duration::from_millis(500),
27190 "PolicyRateLimitWindowNotCanonical must carry the \
27191 offending :window magnitude verbatim through the \
27192 accessor — got {window:?}, expected 500ms",
27193 );
27194 }
27195 other => panic!(
27196 "validate_politicas must reject non-canonical :window \
27197 with PolicyRateLimitWindowNotCanonical — the accessor \
27198 and the validate gate must route through the same \
27199 substrate-primitive typed dispatch on the :window \
27200 canonical-set arm; got {other:?}",
27201 ),
27202 }
27203 spec.politicas = MeshPolicy {
27204 rate_limit: Some(RateLimit {
27205 rate: 100,
27206 window: Duration::from_secs(1),
27207 }),
27208 ..MeshPolicy::default()
27209 };
27210 assert!(
27211 spec.validate().is_ok(),
27212 "validate_politicas must accept window == Duration::from_secs(1) \
27213 (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
27214 );
27215 }
27216
27217 #[test]
27218 fn rate_limit_window_projects_duration_by_copy() {
27219 // The by-copy pin: [`RateLimit::window`] returns `Duration`
27220 // by copy — `Duration` is `Copy` and the accessor must return
27221 // by value, not by reference. Peer of the sibling per-`RateLimit`
27222 // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
27223 // required-scalar `:rate` axis, extended onto the peer
27224 // per-`RateLimit` required-`Duration` copy-invariant shape —
27225 // the accessor's returned `Duration` must outlive `&self`
27226 // (multiple calls must return equal values from a
27227 // dropped-`&self` copy, since the returned scalar carries no
27228 // borrow), and calling the accessor twice on the same
27229 // RateLimit must yield the same `Duration` verbatim
27230 // (idempotent, no side effects on `&self`).
27231 //
27232 // Pins against a future silent detour that returned
27233 // `&Duration` (which would type-check but silently break every
27234 // downstream `Duration`-by-value consumer —
27235 // [`is_canonical_rate_limit_window`]'s first parameter is
27236 // `Duration`, and `&Duration` would fold to a detached copy at
27237 // the call site with a `*` deref the sibling accessors don't
27238 // need), an accidental `.window + Duration::ZERO` detour that
27239 // returned a fresh copy through an arithmetic no-op (breaking
27240 // a future `const fn` regression), or a one-arm-only accessor
27241 // that returned a canonical fallback on some sentinel input
27242 // (breaking the pass-through invariant the sibling required-
27243 // scalar accessors carry).
27244 for window in [
27245 Duration::from_secs(1),
27246 Duration::from_secs(60),
27247 Duration::from_secs(3600),
27248 Duration::ZERO,
27249 Duration::from_millis(500),
27250 ] {
27251 let rl = RateLimit { rate: 100, window };
27252 let first = rl.window();
27253 let second = rl.window();
27254 assert_eq!(
27255 first, second,
27256 "RateLimit::window must be idempotent — two successive \
27257 calls on the same &self must return the same Duration",
27258 );
27259 assert_eq!(
27260 first, window,
27261 "RateLimit::window must return :politicas :rate-limit :window \
27262 verbatim by copy — got {first:?}, expected {window:?}",
27263 );
27264 }
27265 }
27266
27267 #[test]
27268 fn placement_estrategia_default_pins_m3_canonical_value() {
27269 // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
27270 // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
27271 // active-active-across-every-named-cluster arm, the closest
27272 // canonical M3 production reference the substrate carries and
27273 // the arm the caixa-mesh `programs.yaml` fan-out already keys off
27274 // for every un-`:placement`-declared Aplicacao. Pinning the arm
27275 // here surfaces a future rebrand of the M3-canonical
27276 // distribution default (a widening to `Sharded` once the
27277 // substrate discovers hash-keyed distribution as the more
27278 // common production shape, a tightening to `SingleNode` for
27279 // stateful Erlang/OTP distributed-app-takeover semantics
27280 // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
27281 // operator pins through a future `:placement-overrides` slot)
27282 // as a deliberate test edit, not a silent contract migration.
27283 // Peer of the sibling M2 per-supervisor value pins
27284 // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
27285 // /
27286 // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
27287 // extended onto the M3 mesh-primitive-defining `:placement
27288 // :estrategia` axis.
27289 assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
27290 }
27291
27292 #[test]
27293 fn placement_strategy_default_routes_through_lifted_default() {
27294 // Composition pin: the [`Default for PlacementStrategy`] impl's
27295 // return arm must route through the substrate-canonical
27296 // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
27297 // a raw `Self::Replicated` arm. Prior to the lift the impl
27298 // carried an inline `Self::Replicated` arm with no compile-time
27299 // link back to the shared M3-canonical `Replicated` arm the
27300 // paired [`Default for Placement`] impl's struct-literal
27301 // `estrategia` field, the serde-side `#[serde(default)]` on
27302 // [`Placement::estrategia`] that resolves an author-omitted
27303 // wire-form `:placement :estrategia` scalar through the impl,
27304 // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
27305 // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
27306 // routes through [`Placement::default`] which routes through the
27307 // strategy default) all key off — so a future rebrand of the
27308 // M3-canonical distribution default would have had to be threaded
27309 // through the `Default` impl and the three peer routes in
27310 // lockstep or the four consumers would silently split. Byte-
27311 // parity against the lifted constant closes the split. Peer of
27312 // the sibling
27313 // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
27314 // /
27315 // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
27316 // composition pins on the M2 per-supervisor axes.
27317 assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
27318 }
27319
27320 #[test]
27321 fn placement_default_estrategia_routes_through_lifted_default() {
27322 // Composition pin: the [`Default for Placement`] impl's
27323 // struct-literal `estrategia` field must route through the
27324 // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
27325 // `pub const` (either directly, or via the [`PlacementStrategy::default`]
27326 // impl that the sibling
27327 // `placement_strategy_default_routes_through_lifted_default` pin
27328 // already routes onto the constant). Structurally: every
27329 // `Placement::default()` call must yield an `estrategia` field
27330 // byte-equal to the lifted constant so the two paired defaults —
27331 // the [`Default for PlacementStrategy`] impl arm and the
27332 // struct-literal default arm here — cannot silently split on any
27333 // future M3-canonical distribution-default rebrand. Peer of the
27334 // sibling M2
27335 // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
27336 // byte-parity pin on the [`Default for SupervisorSpec`]
27337 // struct-literal `estrategia` field extended onto the M3
27338 // mesh-primitive-defining slot family.
27339 assert_eq!(
27340 Placement::default().estrategia,
27341 PLACEMENT_ESTRATEGIA_DEFAULT,
27342 );
27343 }
27344
27345 #[test]
27346 fn placement_serde_default_estrategia_routes_through_lifted_default() {
27347 // Composition pin: the serde-side `#[serde(default)]` on
27348 // [`Placement::estrategia`] — the wire-format author-omitted
27349 // `:placement :estrategia` arm — must resolve onto the substrate-
27350 // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
27351 // (via the [`Default for PlacementStrategy`] impl the sibling
27352 // `placement_strategy_default_routes_through_lifted_default` pin
27353 // already routes onto the constant). Structurally: a `Placement`
27354 // deserialized from a payload that omits the `estrategia` key
27355 // must yield an `estrategia` field byte-equal to the lifted
27356 // constant, so the wire-format author-omitted arm and the
27357 // [`PlacementStrategy::default`] impl arm cannot silently split
27358 // on any future M3-canonical distribution-default rebrand. Peer
27359 // of the sibling M2
27360 // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
27361 // byte-parity pin on the wire-format author-omitted `:children
27362 // :restart` scalar extended onto the M3 mesh-primitive-defining
27363 // slot family.
27364 let omitted: Placement = serde_json::from_str("{}")
27365 .expect("Placement must deserialize with the estrategia key omitted");
27366 assert_eq!(
27367 omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27368 "an author-omitted :placement :estrategia slot must degrade onto \
27369 the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
27370 {:?}, expected {:?})",
27371 omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27372 );
27373 }
27374}