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 matches!(WitShape::classify(wit), WitShape::Http)
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 matches!(WitShape::classify(wit), WitShape::PubSub)
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 matches!(WitShape::classify(wit), WitShape::Store)
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 matches!(WitShape::classify(wit), WitShape::Capability)
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
361/// Closed 4-arm typed classification of a raw `:contratos :wit` value's
362/// WIT-shape membership — the single-dispatch typed source of truth for
363/// the four-arm partition the free-function classifier family
364/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
365/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) opens on the
366/// raw `&str` axis. Every peer free predicate now routes through
367/// [`Self::classify`] via a `matches!` arm-check, so the raw `&str →
368/// WIT-shape-arm` dispatch lives at one substrate primitive rather than
369/// four open-coded prefix probes plus a triplet negation.
370///
371/// # Compounding
372///
373/// The free predicates fan out to four independent bodies, three of
374/// which read one [`WIT_*_SHAPE_PREFIXES`] const each and one of which
375/// re-negates the trio. A future fifth WIT-shape arm (a hypothetical
376/// `wasi:sockets/*` / `tcp:*` transport-layer shape, an `oci:*`
377/// capability-import carrier, per the sibling [`wit_shape_matches`]
378/// docstring's trajectory bullet) previously required:
379/// 1. one new [`WIT_*_SHAPE_PREFIXES`] const,
380/// 2. one new `wit_shape_is_<name>` free predicate,
381/// 3. an edit to [`wit_shape_is_capability`]'s negation to add the
382/// new arm — which a future author can silently forget, at which
383/// point every downstream capability-shape reader would
384/// misclassify the new arm as capability without a compile-time
385/// signal.
386///
387/// After this lift the third step becomes a compiler-checked
388/// exhaustiveness error: adding a fifth [`WitShape`] variant without
389/// growing [`Self::classify`]'s `match` fails at caixa-core build time
390/// (unhandled arm), and the sibling accessors ([`Self::as_str`], the
391/// [`std::fmt::Display`] and [`AsRef<str>`] impls, the
392/// [`gen_platform::IsVariant`]-derived per-arm predicates) refuse to
393/// compile until the new arm carries a body. The free predicate for
394/// the new arm is then a thin one-line `matches!` on the classifier's
395/// result, and [`wit_shape_is_capability`]'s definition stays a
396/// zero-line delta.
397///
398/// # Peers
399///
400/// Peer of the closed-set typed enums the caixa surface already
401/// carries on adjacent axes:
402/// - [`crate::CaixaKind`] on the top-level `:kind` axis
403/// - [`crate::dialeto::CaixaDialeto`] on the dialect-classification axis
404/// - [`PlacementStrategy`] on the `:placement :estrategia` axis
405/// - [`RateLimitUnit`] on the `:politicas :rate-limit :window` axis
406/// - [`crate::supervisor::RestartStrategy`] /
407/// [`crate::supervisor::RestartPolicy`] on the supervisor-strategy
408/// axes
409///
410/// Distinct from [`WitTarget`] on the same overall `:contratos` slot:
411/// [`WitTarget`] is the *post-validation* payload-carrying view (each
412/// arm carries the payload field its shape requires — an endpoint, a
413/// subject, a slot); [`WitShape`] is the *pre-validation* raw-`&str`
414/// classification (four unit arms — a witness of "which arm would the
415/// downstream validate consume this as?" without materializing the
416/// payload). Both surfaces carry an [`gen_platform::IsVariant`]-derived
417/// arm-predicate family and a `Capability` arm, so any downstream
418/// consumer that pairs a raw `&str` shape witness with a validated
419/// [`WitTarget`] view reads through matched per-arm predicates on both
420/// sides.
421///
422/// # Not a validator
423///
424/// Purely syntactic classification on the raw `:contratos :wit` prefix
425/// set — unlike [`WitContract::target`], which additionally rejects
426/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
427/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
428/// payload-shape mismatches. An empty or structurally malformed `wit`
429/// string classifies here as [`Self::Capability`] (the prefix set
430/// matches nothing), and the surrounding validate-side gate cascade is
431/// where the [`AplicacaoError::EmptyWit`] /
432/// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
433/// enum is the classifier, not the validator.
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant)]
435pub enum WitShape {
436 /// HTTP-shaped WIT world — the raw `:contratos :wit` value starts
437 /// with any prefix in [`WIT_HTTP_SHAPE_PREFIXES`] (`wasi:http/`,
438 /// `http:`). Peer of [`WitTarget::Http`] on the paired
439 /// post-validation payload-carrying view.
440 Http,
441 /// Pub-sub-shaped WIT world — the raw `:contratos :wit` value
442 /// starts with any prefix in [`WIT_PUBSUB_SHAPE_PREFIXES`]
443 /// (`nats:`, `kafka:`). Peer of [`WitTarget::PubSub`] on the paired
444 /// post-validation payload-carrying view.
445 ///
446 /// The `IsVariant` derive would auto-name the predicate
447 /// `is_pub_sub` (`discriminant_to_snake("PubSub") == "pub_sub"`);
448 /// the explicit `#[is_variant(name = "pubsub")]` override keeps the
449 /// emitted method name byte-identical to the sibling
450 /// [`WitTarget::is_pubsub`] and [`WitContract::is_pubsub`]
451 /// predicates so all three arm-discriminator axes — raw-`&str`,
452 /// post-validation payload view, and pre-projection `WitContract`
453 /// surface — reach every downstream consumer through the same
454 /// `is_pubsub()` name.
455 #[is_variant(name = "pubsub")]
456 PubSub,
457 /// Key/value-store-shaped WIT world — the raw `:contratos :wit`
458 /// value starts with any prefix in [`WIT_STORE_SHAPE_PREFIXES`]
459 /// (`wasi:keyvalue/`, `kv:`). Peer of [`WitTarget::Store`] on the
460 /// paired post-validation payload-carrying view.
461 Store,
462 /// Payload-less capability edge — none of the three payload-arm
463 /// prefix sets match. Peer of [`WitTarget::Capability`] on the
464 /// paired post-validation view; the fallback arm that catches
465 /// everything the payload-arm probes miss, including the empty
466 /// string and every structurally-malformed `:wit` value the
467 /// surrounding [`WitContract::target`] validator rejects
468 /// downstream.
469 Capability,
470}
471
472impl WitShape {
473 /// Exhaustive iteration surface for every consumer that walks the
474 /// closed four-arm [`WitShape`] partition — a future
475 /// `feira app graph --by-wit-shape` histogram column, the future M4
476 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
477 /// admission-webhook rejection body naming the accepted-shape set,
478 /// any future round-trip fuzz harness that sweeps every arm's
479 /// canonical accept-set. A future variant addition (a hypothetical
480 /// `wasi:sockets/*` transport-layer shape, an `oci:*`
481 /// capability-import carrier per the sibling [`wit_shape_matches`]
482 /// docstring's trajectory bullet) extends this slice as one edit
483 /// and every consumer picks up the new entry through the shared
484 /// iteration; the compiler-checked exhaustiveness on the sibling
485 /// method `match` arms ([`Self::classify`] / [`Self::as_str`]) is
486 /// the build-time guarantee that no arm forgets to grow.
487 ///
488 /// Peer of the sibling closed-set typed enums'
489 /// [`crate::CaixaKind::ALL`] /
490 /// [`crate::dialeto::CaixaDialeto::ALL`] /
491 /// [`PlacementStrategy::ALL`] / [`RateLimitUnit::ALL`] /
492 /// [`crate::supervisor::RestartStrategy::ALL`] /
493 /// [`crate::supervisor::RestartPolicy::ALL`] /
494 /// [`crate::dep::DepList::ALL`] exhaustive-iteration surfaces —
495 /// the next closed-set typed enum on the caixa surface to converge
496 /// onto the same one-canonical-arm-list-per-enum discipline, and
497 /// the first WIT-shape-classification axis (as distinct from an
498 /// OTP-shape M2 slot or an M3 mesh slot) to reach it. Order matches
499 /// variant declaration order verbatim (`Http` → `PubSub` → `Store`
500 /// → `Capability`) so the slice is the canonical ordering every
501 /// listing / rendering consumer defers to, and matches the arm
502 /// preference [`Self::classify`] dispatches on.
503 pub const ALL: &'static [Self] = &[Self::Http, Self::PubSub, Self::Store, Self::Capability];
504
505 /// Classify a raw `:contratos :wit` value into its closed four-arm
506 /// WIT-shape partition — the single canonical dispatch every free
507 /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
508 /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] predicate
509 /// routes through via a `matches!` arm-check, and the single
510 /// canonical dispatch every future consumer that needs the full
511 /// four-arm answer (rather than a per-arm boolean) reaches for.
512 ///
513 /// Arm preference is `Http` → `PubSub` → `Store` → `Capability`,
514 /// matching the declaration order pinned in [`Self::ALL`]. Under
515 /// the disjointness pins immediately above the impl block
516 /// (`const _: () = assert!(!wit_shape_is_http("nats:events"))` and
517 /// peers), the preference order is unobservable — no `:wit` value
518 /// satisfies more than one payload-arm prefix set. If a future
519 /// prefix-set edit accidentally overlaps two arms (e.g. a `kv:`
520 /// prefix accidentally re-emitted under
521 /// [`WIT_HTTP_SHAPE_PREFIXES`]), the sibling `const _: () =
522 /// assert!(!wit_shape_is_http("kv:cache"))` pin trips at
523 /// caixa-core build time before the preference-order behavior
524 /// becomes observable at any consumer site.
525 ///
526 /// # Const-eval posture
527 ///
528 /// Declared `pub const fn` — routes through the peer `pub const
529 /// fn` [`wit_shape_matches`] combinator on each of the three
530 /// payload-arm prefix-set probes, so every substrate-side
531 /// `const`-context WIT-shape-arm-classifier consumer (any future
532 /// M4 admission-webhook `const fn` per-`:contratos :wit`
533 /// arm-resolver over a raw `&str`, any future `const fn`
534 /// per-`:contratos`-edge WIT-registry prefix-set overlay resolver
535 /// that fans on the classified arm at compile time) reaches
536 /// through the same typed dispatch on the substrate primitive at
537 /// const-eval time as at runtime. Pinned load-bearing by the
538 /// [`tests::wit_shape_classify_is_const_fn`] test's `const fn`
539 /// wrapper — any future accidental downgrade to non-`const` fails
540 /// with E0015 at the wrapper call site at caixa-core build time,
541 /// strictly stronger than a runtime `assert!`.
542 #[must_use]
543 pub const fn classify(wit: &str) -> Self {
544 if wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES) {
545 Self::Http
546 } else if wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES) {
547 Self::PubSub
548 } else if wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES) {
549 Self::Store
550 } else {
551 Self::Capability
552 }
553 }
554
555 /// Canonical short kebab byte-string every consumer that formats a
556 /// [`WitShape`] as census-facing text lands on — returns
557 /// `"http"` / `"pubsub"` / `"store"` / `"capability"`, the same
558 /// byte-strings the [`std::fmt::Display`] and [`AsRef<str>`] impls
559 /// route through and every future histogram-column /
560 /// audit-report / admission-rejection-body reader reads.
561 ///
562 /// Peer of the sibling closed-set typed enums'
563 /// [`crate::CaixaKind::as_str`] /
564 /// [`crate::dialeto::CaixaDialeto::as_str`] /
565 /// [`PlacementStrategy::as_str`] /
566 /// [`RateLimitUnit::as_suffix`] /
567 /// [`crate::supervisor::RestartStrategy::as_str`] /
568 /// [`crate::supervisor::RestartPolicy::as_str`] canonical-projection
569 /// accessors on the sibling closed-set typed-enum discriminator
570 /// axes.
571 #[must_use]
572 pub const fn as_str(self) -> &'static str {
573 match self {
574 Self::Http => "http",
575 Self::PubSub => "pubsub",
576 Self::Store => "store",
577 Self::Capability => "capability",
578 }
579 }
580
581 /// Reverse projection on the [`WitShape`] closed-set enum's
582 /// canonical-projection axis — parses a `"http"` / `"pubsub"` /
583 /// `"store"` / `"capability"` census-label byte-string back to the
584 /// typed enum, or returns [`None`] when `s` lies outside the four-
585 /// arm accept-set [`Self::as_str`] emits. The single `&str → Self`
586 /// projection every future re-entry point on the [`WitShape`]
587 /// census-label axis dispatches through (a future
588 /// `feira app graph --by-wit-shape=<http|pubsub|store|capability>`
589 /// CLI arg-parse that binds the wire byte-string into the typed
590 /// enum before dispatching to the per-arm histogram column, a
591 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook
592 /// rejection body re-parsing a prior emission's per-arm audit-column
593 /// tag back to the typed enum for accepted-shape policy classification,
594 /// a `tracing::field::Value::Str`-arm structured-log re-loader binding
595 /// a prior [`std::fmt::Display`]-formatted [`WitShape`] output back to the
596 /// typed enum for cross-run shape-flavor histogram diff) would have
597 /// had to re-inline a four-arm `match s` cascade that expressed no
598 /// compile-time link back to the substrate primitive.
599 ///
600 /// Distinct axis from the peer [`Self::classify`] total classifier,
601 /// which takes the *raw* `:contratos :wit` identifier (`"wasi:http/proxy"`,
602 /// `"nats:events"`, `"wasi:keyvalue/store"`, everything else) and
603 /// returns the arm the payload-arm prefix-set dispatch resolves to —
604 /// a total function on the WIT-identifier axis. [`Self::from_wire`]
605 /// takes the *census-label* byte-string (`"http"` / `"pubsub"` /
606 /// `"store"` / `"capability"`, the paired output of [`Self::as_str`])
607 /// and returns the arm — a partial function on the closed four-string
608 /// census-label axis. The two axes carry different accept-sets by
609 /// design, not drift: [`Self::classify`] accepts every `&str` and
610 /// falls through to [`Self::Capability`] on the empty and every
611 /// structurally-malformed input; [`Self::from_wire`] accepts exactly
612 /// the four census labels [`Self::as_str`] emits and rejects
613 /// everything else (including every raw WIT identifier [`Self::classify`]
614 /// would classify — so a caller who accidentally routes a raw
615 /// `:contratos :wit` value through [`Self::from_wire`] instead of
616 /// [`Self::classify`] observes [`None`] rather than a plausibly-wrong
617 /// arm silently). The paired axis discipline mirrors the sibling
618 /// [`crate::CaixaKind::as_str`] / [`crate::CaixaKind::from_wire`]
619 /// pair on the top-level `:kind` axis.
620 ///
621 /// Same closed-set-reverse-projection discipline the sibling
622 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
623 /// [`crate::dialeto::CaixaDialeto::from_wire`] (d0e65ea) /
624 /// [`crate::supervisor::RestartStrategy::from_wire`] (4eec29c) /
625 /// [`crate::supervisor::RestartPolicy::from_wire`] (dd32ccf) /
626 /// [`PlacementStrategy::from_wire`] (18c7342) /
627 /// [`crate::dep::DepList::from_wire`] (45ee563) /
628 /// [`crate::render::PathShapeViolation::from_wire`] (aebd9c6) /
629 /// `caixa_arch::invariants::InvariantKind::from_wire` (b9e4e61) /
630 /// `caixa_arch::report::ArchVerdict::from_wire` (6afe564) /
631 /// `caixa_lint::diagnostic::Severity::from_wire` (5afff0e) /
632 /// `caixa_lint::diagnostic::FixSafety::from_wire` (bd505a1) /
633 /// `caixa_theme::style::Semantic::from_wire` (e7bca7b) /
634 /// `caixa_provedor::ferrite::FerriteRuntime::from_wire` (1e4cc81)
635 /// typed enums carry on the peer wire-side `str → Self` axes —
636 /// extends the substrate-wide `(as_str, from_wire)` round-trip
637 /// family onto the first `:contratos :wit` raw-classification
638 /// axis to converge on the reverse-projection discipline, matching
639 /// the same two-way `str ↔ Self` round-trip every sibling closed-
640 /// set enum already carries. Method-named `from_wire` (not
641 /// `from_str`) to match the peer shapes verbatim and side-step a
642 /// `clippy::should_implement_trait` lint that a plain `from_str`
643 /// name would otherwise trigger without paired [`std::str::FromStr`]
644 /// impl scaffolding this axis does not carry today. Returns
645 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
646 /// shapes: the caller picks the diagnostic form appropriate for its
647 /// use site (a future `feira app graph --by-wit-shape` CLI arg-parse
648 /// renders its own per-verb error message; a future admission-webhook
649 /// rejection body wraps the [`None`] outcome with the accepted-set
650 /// enumeration `WitShape::ALL.iter().map(WitShape::as_str)` for
651 /// operator diagnostics).
652 ///
653 /// Pinned load-bearing at the substrate-primitive level by
654 /// [`tests::wit_shape_from_wire_accepts_every_as_str_output`]
655 /// (round-trip witness against the peer [`Self::as_str`] axis) and
656 /// [`tests::wit_shape_from_wire_rejects_unknown_byte_strings`]
657 /// (rejection witness against silent accept-set widening,
658 /// including the raw `:contratos :wit` identifiers [`Self::classify`]
659 /// consumes on the sibling axis — so a caller who confuses the two
660 /// axes trips the pin at caixa-core build time rather than at a
661 /// downstream consumer's silent misclassification).
662 #[must_use]
663 pub fn from_wire(s: &str) -> Option<Self> {
664 match s {
665 "http" => Some(Self::Http),
666 "pubsub" => Some(Self::PubSub),
667 "store" => Some(Self::Store),
668 "capability" => Some(Self::Capability),
669 _ => None,
670 }
671 }
672}
673
674/// Route [`std::fmt::Display`] through [`WitShape::as_str`], so every
675/// consumer that formats a [`WitShape`] as user-facing text (future
676/// histogram column headers on `feira app graph --by-wit-shape`,
677/// future admission-webhook rejection bodies enumerating the accepted
678/// shape set, future audit-report per-arm column headers) lands on the
679/// same `"http"` / `"pubsub"` / `"store"` / `"capability"` byte-string
680/// the paired [`AsRef<str>`] impl also routes through. Same
681/// canonical-projection discipline the sibling
682/// [`std::fmt::Display for crate::CaixaKind`] /
683/// [`std::fmt::Display for crate::dialeto::CaixaDialeto`] /
684/// [`std::fmt::Display for PlacementStrategy`] /
685/// [`std::fmt::Display for RateLimitUnit`] impls carry — every text
686/// projection on this closed-set typed enum's dispatch surface reaches
687/// through one accessor.
688impl std::fmt::Display for WitShape {
689 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
690 f.write_str(self.as_str())
691 }
692}
693
694/// Route [`AsRef<str>`] through [`WitShape::as_str`], so every
695/// consumer that borrows a [`WitShape`] as `&str` (a future
696/// `HashMap<&str, _>` keyed lookup, a `&str`-bounded generic that
697/// takes a shape tag) lands on the same byte-string the sibling
698/// [`std::fmt::Display`] impl routes through. Peer of the sibling
699/// closed-set typed enums' [`AsRef<str>`] impls carrying the same
700/// discipline.
701impl AsRef<str> for WitShape {
702 fn as_ref(&self) -> &str {
703 self.as_str()
704 }
705}
706
707/// Standard-library trait-idiomatic reverse projection on the
708/// [`WitShape`] closed-set typed enum. Routes byte-for-byte through the
709/// paired substrate-primitive [`WitShape::from_wire`] `Option<Self>`
710/// accessor so `s.try_into::<WitShape>()` /
711/// `WitShape::try_from(&s)` reaches the same four-arm `"http"` /
712/// `"pubsub"` / `"store"` / `"capability"` census-label accept-set the
713/// sibling method-named resolver dispatches through and the sibling
714/// [`WitShape::as_str`] emits.
715///
716/// `type Error = ()` — matches the sibling [`WitShape::from_wire`]'s
717/// `Option<Self>` return-shape's deliberate deferral of error typing:
718/// the caller picks the diagnostic form appropriate for its use site (a
719/// future `feira app graph --by-wit-shape <arm>` CLI arg-parse composes
720/// its own per-verb "unknown wit-shape: <arg> — accepted: {…}" message
721/// enumerating [`WitShape::ALL`], a future M4
722/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook wraps
723/// `Err(())` with a per-CR structured refusal body enumerating the
724/// four-arm census set, a `Result::map_err` at the call site lifts the
725/// unit-error to a per-verb error type). Same shape the sibling
726/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
727/// [`PlacementStrategy`] (6fd00cd), [`crate::supervisor::RestartStrategy`]
728/// (5b828ed), and [`crate::supervisor::RestartPolicy`] (6fdd0d9)
729/// `TryFrom<&str>` impls carry.
730///
731/// Chosen over [`std::str::FromStr`] to sidestep both
732/// `clippy::should_implement_trait` on the method-named
733/// [`WitShape::from_wire`] and the two-axis discipline the paired
734/// [`WitShape::classify`] total function keeps on the *raw* WIT
735/// identifier axis — the sibling
736/// `wit_shape_from_wire_and_classify_partition_the_axis` pin makes this
737/// two-axis split load-bearing, and a `FromStr` impl on the census-label
738/// axis would obscure which of the two axes a plain
739/// `s.parse::<WitShape>()` reaches. `TryFrom<&str>` keeps the trait-
740/// idiomatic reverse projection anchored to the same census-label axis
741/// [`WitShape::from_wire`] resolves through, leaving the raw
742/// [`WitShape::classify`] axis untouched.
743///
744/// The paired [`WitShape::from_wire`] resolver's accept-set is shared by
745/// construction, so any future arm addition (a hypothetical
746/// `wasi:sockets/*` transport-layer shape or `oci:*` capability-import
747/// carrier the sibling [`wit_shape_matches`] docstring names as a
748/// trajectory item) grows the trait-idiomatic axis by construction —
749/// one caixa-core edit on [`WitShape::from_wire`] extends both the
750/// method-named reverse projection every existing consumer keys off and
751/// the trait-idiomatic reverse projection this impl exposes, without a
752/// coordinated rewrite across every future `TryFrom<&str>`-bound
753/// consumer's arm-set.
754///
755/// Extends the substrate-wide closed-set-enum trait-idiomatic reverse-
756/// projection family ([`crate::CaixaKind`] via 3c83606,
757/// [`crate::CaixaDialeto`] via bf33136, [`PlacementStrategy`] via
758/// 6fd00cd, [`crate::supervisor::RestartStrategy`] via 5b828ed,
759/// [`crate::supervisor::RestartPolicy`] via 6fdd0d9) onto the second
760/// M3-mesh-primitive-defining slot enum on the caixa surface — the
761/// `:contratos :wit` census-label closed set the caixa-mesh renderer
762/// keys off end-to-end for per-edge programs.yaml fan-out.
763///
764/// Pinned load-bearing by
765/// [`tests::wit_shape_try_from_str_routes_through_from_wire_accessor`]
766/// (byte-parity pin against [`WitShape::from_wire`] across the four-arm
767/// accept-set),
768/// [`tests::wit_shape_try_from_str_rejects_unknown_byte_strings`]
769/// (rejection witness against silent accept-set widening), and
770/// [`tests::wit_shape_try_from_str_and_from_wire_partition_the_accept_set`]
771/// (cross-axis partition pin locking trait and method-named projections
772/// to the same `Option<Self>` output on every input).
773impl TryFrom<&str> for WitShape {
774 type Error = ();
775
776 fn try_from(s: &str) -> Result<Self, Self::Error> {
777 Self::from_wire(s).ok_or(())
778 }
779}
780
781/// Standard-library trait-idiomatic forward projection on the
782/// [`WitShape`] closed-set typed enum. Routes byte-for-byte through the
783/// paired substrate-primitive [`WitShape::as_str`] `pub const fn`
784/// accessor so `<&'static str>::from(shape)` / `shape.into::<&'static
785/// str>()` reaches the same four-arm `"http"` / `"pubsub"` / `"store"`
786/// / `"capability"` census-label emit-set the sibling method-named
787/// accessor dispatches through and the sibling
788/// [`std::fmt::Display for WitShape`] / [`AsRef<str> for WitShape`]
789/// impls also route through.
790///
791/// Extends the substrate-wide closed-set-enum trait-idiomatic
792/// forward-projection family
793/// ([`crate::supervisor::RestartStrategy`] via 523157d,
794/// [`crate::supervisor::RestartPolicy`] via 9fb37d0,
795/// [`crate::CaixaKind`] via edb827b,
796/// [`crate::CaixaDialeto`] via c189a6f,
797/// [`PlacementStrategy`] via afa3562) onto the second
798/// M3-mesh-primitive-defining slot enum on the caixa surface — the
799/// `:contratos :wit` census-label closed set the caixa-mesh renderer
800/// keys off end-to-end for per-edge programs.yaml fan-out. Pairs with
801/// the sibling [`TryFrom<&str> for WitShape`] impl (5472902) to close
802/// the two-way `Self ↔ &'static str` round-trip on the trait-idiomatic
803/// axis pair, mirroring the pre-existing method-named
804/// [`WitShape::as_str`] + [`WitShape::from_wire`] pair on the
805/// substrate-primitive axis pair.
806///
807/// The paired [`WitShape::as_str`] accessor's four-arm emit-set is the
808/// single source of truth — every future arm addition (a hypothetical
809/// `wasi:sockets/*` transport-layer shape or `oci:*` capability-import
810/// carrier the sibling [`wit_shape_matches`] docstring's trajectory
811/// bullet names) grows the trait-idiomatic forward axis by
812/// construction: one caixa-core edit on [`WitShape::as_str`] extends
813/// every one of the sibling forward-projection paths
814/// ([`std::fmt::Display`], [`AsRef<str>`], [`WitShape::as_str`]
815/// itself, and this [`From<Self> for &'static str`]) without a
816/// coordinated rewrite across every future `Into<&'static str>`-bound
817/// consumer's arm-set.
818///
819/// Pinned load-bearing by
820/// [`tests::wit_shape_from_into_static_str_routes_through_as_str_accessor`]
821/// (byte-parity pin against [`WitShape::as_str`] across the four-arm
822/// emit-set, plus a `const`-context materialization witness for the
823/// `&'static str` lifetime promise routed through the paired
824/// [`WitShape::as_str`] `pub const fn` accessor, plus a paired
825/// `.into()` shape assertion covering the blanket-derived
826/// `Into<&'static str>` shape) and
827/// [`tests::wit_shape_from_into_static_str_and_as_str_partition_the_emit_set`]
828/// (partition pin asserting `<&'static str as From<WitShape>>::from`
829/// and [`WitShape::as_str`] agree on every arm, plus a two-way direct
830/// round-trip witness through the paired trait-idiomatic
831/// [`TryFrom<&str>`] axis that closes the two-way `Self ↔ &'static
832/// str` round-trip on the trait-idiomatic axis pair — the emit-side
833/// [`WitShape::as_str`] and the parse-side [`WitShape::from_wire`]
834/// dispatch on the same four inline census-label byte-strings by
835/// construction, so round-tripping composes the two trait impls
836/// directly).
837impl From<WitShape> for &'static str {
838 fn from(shape: WitShape) -> &'static str {
839 shape.as_str()
840 }
841}
842
843impl WitContract {
844 /// Substrate-canonical per-`:contratos` caller-Servico scalar
845 /// accessor every consumer that reads the edge's source endpoint
846 /// keys off — returns the author-declared `:contratos :de`
847 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
848 /// own [`String`] storage.
849 ///
850 /// The `:contratos :de` slot names the caller-side member Servico
851 /// on a typed inter-Servico edge (validated by
852 /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
853 /// Aplicacao declares — a stray `:de` that doesn't name a member is
854 /// [`AplicacaoError::ContratoMemberMissing`], not a silent
855 /// caller-attachment miss at cluster-apply time). Peer of the
856 /// sibling [`WitContract::destination`] accessor on the same
857 /// per-`:contratos` entry — the pair `( source(), destination() )`
858 /// jointly names the typed edge every renderer that fans on the
859 /// caller-callee identity keys off (the
860 /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
861 /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
862 /// map, the per-edge dedup key, the per-edge membership-lookup
863 /// diagnostic).
864 ///
865 /// Prior to this lift the `.de` byte-string was accessed inline at
866 /// four caixa-core sites (the two validate-side membership lookups
867 /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
868 /// tuple's caller-arm at
869 /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
870 /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
871 /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
872 /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
873 /// — five open-coded `.de.as_str()` field-accesses that expressed
874 /// no compile-time link back to the typed slot. A future extension
875 /// of the `:contratos :de` axis to a richer author surface (a
876 /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
877 /// canary flow, a per-cluster caller-alias table the operator pins
878 /// through a future `:placement`-scoped slot, the M4
879 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
880 /// admission-webhook that promotes the scalar to a caller-set
881 /// projection) would have had to be threaded through every
882 /// open-coded copy in lockstep or one consumer would silently
883 /// disagree with the peers on which caller Servico a given edge
884 /// resolves to. Lifting the resolution rule to a typed method on
885 /// the substrate primitive means every downstream caller-facing
886 /// consumer reaches for one typed dispatch — the resolver's
887 /// accept-set migrates as a unit on any future axis addition.
888 ///
889 /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
890 /// (6db982c) accessor on the analogous per-ingress-Servico scalar
891 /// axis — same "one typed dispatch on the substrate primitive,
892 /// thin projections at each consumer" discipline extended onto the
893 /// per-`:contratos` caller-Servico byte-string axis.
894 ///
895 /// Declared `pub const fn` — the body composes exclusively through
896 /// the `pub const fn` [`String::as_str`] projection (const-stable
897 /// since Rust 1.87, well within the workspace MSRV), so every
898 /// downstream `const`-context consumer of the per-`:contratos`
899 /// caller-Servico byte-string reaches through the same substrate-
900 /// primitive dispatch at const-eval time as at runtime. Peer of
901 /// the sibling `pub const fn` [`Self::destination`] /
902 /// [`Self::world_ref`] scalar accessors on the same
903 /// per-`:contratos` byte-string trio (the family closure the
904 /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
905 /// locks load-bearing), and mirror on the method-surface of the
906 /// sibling free-function [`wit_shape_matches`] +
907 /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
908 /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
909 /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
910 /// dispatch family.
911 #[must_use]
912 pub const fn source(&self) -> &str {
913 self.de.as_str()
914 }
915
916 /// Substrate-canonical per-`:contratos` callee-Servico scalar
917 /// accessor every consumer that reads the edge's destination
918 /// endpoint keys off — returns the author-declared
919 /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
920 /// from the typed slot's own [`String`] storage.
921 ///
922 /// The `:contratos :para` slot names the callee-side member Servico
923 /// on a typed inter-Servico edge (validated by
924 /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
925 /// Aplicacao declares — a stray `:para` that doesn't name a member
926 /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
927 /// callee-attachment miss at cluster-apply time). Callee-side twin
928 /// of the sibling [`WitContract::source`] accessor — the pair
929 /// jointly names the typed edge every renderer that fans on the
930 /// caller-callee identity keys off, and this accessor is also the
931 /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
932 /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
933 /// composes with `destination()` at every emit site that projects a
934 /// per-edge destination Servico's L4 listener port.
935 ///
936 /// Prior to this lift the `.para` byte-string was accessed inline
937 /// at five sites — four caixa-core (the validate-side membership
938 /// lookup at `!names.contains(c.para.as_str())`, the per-edge
939 /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
940 /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
941 /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
942 /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
943 /// — with no compile-time link back to the typed slot. A future
944 /// extension of the `:contratos :para` axis to a richer author
945 /// surface (a multi-callee weighted-fan-out overlay for canary /
946 /// blue-green routing on typed edges, a per-cluster callee-alias
947 /// table the operator pins through a future `:placement`-scoped
948 /// slot, the M4 CR materializer's per-CR admission-webhook that
949 /// promotes the scalar to a callee-set projection) would have had
950 /// to be threaded through every open-coded copy in lockstep or one
951 /// consumer would silently disagree on which callee Servico a given
952 /// edge resolves to (a per-CNP `endpointSelector` that names a
953 /// different destination than its L4 port resolver reads for, a
954 /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
955 /// as distinct while the adjacency map collapses them, or vice
956 /// versa). Lifting to a typed method on the substrate primitive
957 /// means every downstream callee-facing consumer reaches for one
958 /// typed dispatch.
959 ///
960 /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
961 /// (6db982c) accessor — both name the "destination-Servico
962 /// byte-string" concept on their respective mesh-slot atoms (per-
963 /// ingress apex vs. per-typed-edge callee), and both extend the
964 /// substrate-primitive-owns-the-resolver discipline onto the
965 /// per-slot destination-Servico scalar axis. Composes with
966 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
967 /// emit-side per-edge L4 port reader — the composition
968 /// `spec.port_for_destination(c.destination())` pins the CNP per-
969 /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
970 /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
971 /// `spec.port_for_destination(entrada.destination())`.
972 ///
973 /// Declared `pub const fn` — sibling in `const`-eval posture to the
974 /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
975 /// per-`:contratos` byte-string scalar accessors, all three
976 /// projecting through the `pub const fn` [`String::as_str`]
977 /// (const-stable since Rust 1.87). See [`Self::source`] for the
978 /// family-closure rationale.
979 #[must_use]
980 pub const fn destination(&self) -> &str {
981 self.para.as_str()
982 }
983
984 /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
985 /// accessor every consumer that reads the edge's WIT world
986 /// discriminator keys off — returns the author-declared
987 /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
988 /// the typed slot's own [`String`] storage.
989 ///
990 /// The `:contratos :wit` slot names the WIT world the typed edge
991 /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
992 /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
993 /// be a well-shaped WIT world reference via
994 /// [`crate::render::is_wit_world_ref`] and by
995 /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
996 /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
997 /// [`WitContract::source`] / [`WitContract::destination`] accessors
998 /// on the same per-`:contratos` entry — the triple
999 /// `( source(), destination(), world_ref() )` jointly names the
1000 /// typed edge every renderer that fans on the caller-callee-shape
1001 /// identity keys off (the per-edge dedup key at
1002 /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
1003 /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
1004 /// [`caixa_mesh::cilium_network_policies`], the
1005 /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
1006 /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
1007 /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
1008 ///
1009 /// Prior to this lift the `.wit` byte-string was accessed inline at
1010 /// five sites — three caixa-core (the `WitContract::is_*` shape-
1011 /// dispatch predicates' `&self.wit` arg, the validate-side empty
1012 /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
1013 /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
1014 /// printer's `{}` format-slot at `c.wit`) — five open-coded
1015 /// `.wit` field-accesses that expressed no compile-time link back to
1016 /// the typed slot. A future extension of the `:contratos :wit` axis
1017 /// to a richer author surface (an M4 promotion from `String` to a
1018 /// typed WIT-world enum once the WIT registry stabilizes in tatara-
1019 /// lisp per this struct's own `:wit` field docstring, a per-cluster
1020 /// WIT-alias table the operator pins through a future
1021 /// `:placement`-scoped slot, a canonicalization pass that lowercases
1022 /// `wasi:*` prefixes) would have had to be threaded through every
1023 /// open-coded copy in lockstep or one consumer would silently
1024 /// disagree with the peers on which WIT shape a given edge resolves
1025 /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
1026 /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
1027 /// empty-check that missed a whitespace-only string a peer accessor
1028 /// stripped, or vice versa). Lifting to a typed method on the
1029 /// substrate primitive means every downstream WIT-shape-facing
1030 /// consumer reaches for one typed dispatch — the resolver's
1031 /// accept-set migrates as a unit on any future axis addition.
1032 ///
1033 /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
1034 /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
1035 /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
1036 /// 6db982c), per-`:membros` [`Membro::nome`] /
1037 /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
1038 /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
1039 /// on the substrate primitive, thin projections at each consumer"
1040 /// discipline extended onto the last unlifted per-`:contratos`
1041 /// scalar (the WIT-world-reference arm).
1042 ///
1043 /// [fag]: caixa-feira/src/cmd/app.rs
1044 ///
1045 /// Declared `pub const fn` — sibling in `const`-eval posture to the
1046 /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
1047 /// per-`:contratos` byte-string scalar accessors on the trio, and
1048 /// the load-bearing enabler for the paired `pub const fn`
1049 /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1050 /// [`Self::is_capability`] WIT-shape-predicate family (each
1051 /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
1052 /// the `const`-eval posture by construction once this accessor
1053 /// carries it). See [`Self::source`] for the family-closure
1054 /// rationale and the paired
1055 /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1056 /// for the load-bearing witness.
1057 #[must_use]
1058 pub const fn world_ref(&self) -> &str {
1059 self.wit.as_str()
1060 }
1061
1062 /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
1063 /// payload-target scalar accessor every consumer that reads the
1064 /// edge's L7 HTTP request path payload keys off — returns the
1065 /// author-declared `:contratos :endpoint` byte-string verbatim as
1066 /// an `Option<&str>`, borrowed from the typed slot's own
1067 /// `Option<String>` storage; `None` when the slot is absent (the
1068 /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
1069 /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
1070 /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
1071 /// [`WitTarget::Capability`] edge carries none of the three).
1072 ///
1073 /// The `:contratos :endpoint` slot carries the HTTP request path
1074 /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
1075 /// — same shape required of `:entrada :paths`, gated by the shared
1076 /// [`crate::render::is_gateway_api_http_path`] predicate) that
1077 /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
1078 /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
1079 /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
1080 /// downstream consumer that reads the payload keys off this scalar
1081 /// (the [`WitContract::target`] Http-arm payload extraction that
1082 /// materializes [`WitTarget::Http { endpoint }`] under the paired
1083 /// [`WitTarget::HTTP_FIELD_NAME`] label, the
1084 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1085 /// key's endpoint arm that pins the payload as part of the six-tuple
1086 /// dedup key alongside the sibling `:subject`/`:slot` arms, the
1087 /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
1088 /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
1089 /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
1090 /// emission path that lands the payload verbatim as a Cilium L7
1091 /// `path:` rule).
1092 ///
1093 /// Prior to this lift the `.endpoint` field was accessed inline at
1094 /// two production sites in `caixa-core/src/aplicacao.rs` — the
1095 /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
1096 /// self.endpoint.as_deref();` binding at the top of the method, and
1097 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1098 /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
1099 /// field-accesses that expressed no compile-time link back to the
1100 /// typed slot. A future extension of the `:contratos :endpoint`
1101 /// axis to a richer author surface (an M4 promotion from
1102 /// `Option<String>` to a typed HTTP path-template enum once the
1103 /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
1104 /// this struct's own `:wit` field docstring, a per-cluster endpoint-
1105 /// alias table the operator pins through a future `:placement`-
1106 /// scoped slot, a canonicalization pass that percent-encodes non-
1107 /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
1108 /// materializer applies per-tenant) would have had to be threaded
1109 /// through both open-coded copies in lockstep or the two consumers
1110 /// would silently disagree on which HTTP path a given edge resolves
1111 /// to — the [`WitContract::target`] payload-extraction reading
1112 /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
1113 /// the operator-resolved `"/tenant-a/lookup"` would silently split
1114 /// the [`WitTarget::Http`]-arm rendered payload from the actual
1115 /// dedup-key uniqueness axis, a two-consumer split at the validator
1116 /// far from the source `caixa.lisp` with no field naming the
1117 /// payload-drift root cause. Lifting the resolution rule to a typed
1118 /// method on the substrate primitive means every downstream
1119 /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
1120 /// L7-payload surface reaches for exactly one typed dispatch — the
1121 /// resolver's accept-set migrates as a unit on any future axis
1122 /// addition.
1123 ///
1124 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
1125 /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
1126 /// accessors on the M3 mesh-slot family — same "one typed dispatch
1127 /// on the substrate primitive, thin projections at each consumer"
1128 /// discipline extended onto the per-`:contratos` HTTP-shaped
1129 /// payload-carrier `Option<String>` optional-scalar axis. First
1130 /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
1131 /// atom — opens the "optional per-slot payload-carrier scalar"
1132 /// projection pattern the sibling per-`:contratos` `:subject` /
1133 /// `:slot` future lifts fold on, matching the closed
1134 /// per-`:contratos` scalar-value accessor family
1135 /// ([`WitContract::source`] / [`WitContract::destination`] /
1136 /// [`WitContract::world_ref`]) already lifted onto the mandatory-
1137 /// scalar `String` axes. Named `endpoint()` to match the storage
1138 /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
1139 /// author-facing label const; the accessor's identity name maps
1140 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1141 /// docstring already carries.
1142 #[must_use]
1143 pub const fn endpoint(&self) -> Option<&str> {
1144 match &self.endpoint {
1145 Some(s) => Some(s.as_str()),
1146 None => None,
1147 }
1148 }
1149
1150 /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
1151 /// payload-target scalar accessor every consumer that reads the
1152 /// edge's NATS / Kafka publish subject payload keys off — returns
1153 /// the author-declared `:contratos :subject` byte-string verbatim
1154 /// as an `Option<&str>`, borrowed from the typed slot's own
1155 /// `Option<String>` storage; `None` when the slot is absent (the
1156 /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
1157 /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
1158 /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
1159 /// [`WitTarget::Capability`] edge carries none of the three).
1160 ///
1161 /// The `:contratos :subject` slot carries the NATS / Kafka publish
1162 /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
1163 /// per-edge target selector — `orders.paid`, `events.>`, whatever
1164 /// subject namespace the author names on the pub-sub edge) that
1165 /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
1166 /// arm's `subject: &'a str` payload when the edge's `:wit` world
1167 /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
1168 /// downstream consumer that reads the payload keys off this scalar
1169 /// (the [`WitContract::target`] PubSub-arm payload extraction that
1170 /// materializes [`WitTarget::PubSub { subject }`] under the paired
1171 /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
1172 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1173 /// key's subject arm that pins the payload as part of the six-tuple
1174 /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
1175 /// future M4 per-edge WIT registry resolver's pub-sub-arm
1176 /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
1177 /// materializer's per-edge NATS admission webhook, the future
1178 /// caixa-mesh L4 CNP emission path that lands the payload verbatim
1179 /// as a NATS subject the operator pins per-CR).
1180 ///
1181 /// Prior to this lift the `.subject` field was accessed inline at
1182 /// two production sites in `caixa-core/src/aplicacao.rs` — the
1183 /// [`WitContract::target`] payload-shape dispatch's `let subject =
1184 /// self.subject.as_deref();` binding at the top of the method, and
1185 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1186 /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
1187 /// field-accesses that expressed no compile-time link back to the
1188 /// typed slot. A future extension of the `:contratos :subject` axis
1189 /// to a richer author surface (an M4 promotion from `Option<String>`
1190 /// to a typed NATS-subject-template enum once the WIT registry
1191 /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
1192 /// struct's own `:wit` field docstring, a per-cluster subject-alias
1193 /// table the operator pins through a future `:placement`-scoped
1194 /// slot, a canonicalization pass that lowercases / dedupes wildcard
1195 /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
1196 /// applies per-tenant) would have had to be threaded through both
1197 /// open-coded copies in lockstep or the two consumers would silently
1198 /// disagree on which NATS subject a given edge resolves to — the
1199 /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
1200 /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
1201 /// resolved `"tenant-a.orders.paid"` would silently split the
1202 /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
1203 /// key uniqueness axis, a two-consumer split at the validator far
1204 /// from the source `caixa.lisp` with no field naming the payload-
1205 /// drift root cause. Lifting the resolution rule to a typed method
1206 /// on the substrate primitive means every downstream pub-sub-payload-
1207 /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
1208 /// surface reaches for exactly one typed dispatch — the resolver's
1209 /// accept-set migrates as a unit on any future axis addition.
1210 ///
1211 /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
1212 /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
1213 /// carrier axis — second `Option<&str>`-return accessor on the
1214 /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
1215 /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
1216 /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
1217 /// key/value-store arm as the last unlifted per-`:contratos`
1218 /// `Option<String>` axis. Named `subject()` to match the storage
1219 /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
1220 /// author-facing label const; the accessor's identity name maps
1221 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1222 /// docstring already carries.
1223 #[must_use]
1224 pub const fn subject(&self) -> Option<&str> {
1225 match &self.subject {
1226 Some(s) => Some(s.as_str()),
1227 None => None,
1228 }
1229 }
1230
1231 /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
1232 /// shaped payload-target scalar accessor every consumer that reads
1233 /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
1234 /// off — returns the author-declared `:contratos :slot` byte-string
1235 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
1236 /// own `Option<String>` storage; `None` when the slot is absent
1237 /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
1238 /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
1239 /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
1240 /// [`WitTarget::Capability`] edge carries none of the three).
1241 ///
1242 /// The `:contratos :slot` slot carries the key/value store
1243 /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
1244 /// arm's per-edge target selector — `carts/{cart_id}`,
1245 /// `sessions/{tenant}/{sid}`, whatever key-template the author
1246 /// names on the store edge) that [`WitContract::target`] projects
1247 /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
1248 /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
1249 /// accept-set. Every downstream consumer that reads the payload
1250 /// keys off this scalar (the [`WitContract::target`] Store-arm
1251 /// payload extraction that materializes [`WitTarget::Store { slot }`]
1252 /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
1253 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
1254 /// key's store arm that pins the payload as part of the six-tuple
1255 /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
1256 /// the future M4 per-edge WIT registry resolver's store-arm
1257 /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
1258 /// materializer's per-edge key/value admission webhook, the future
1259 /// caixa-mesh L4 CNP emission path that lands the payload verbatim
1260 /// as a key-template the operator pins per-CR).
1261 ///
1262 /// Prior to this lift the `.slot` field was accessed inline at two
1263 /// production sites in `caixa-core/src/aplicacao.rs` — the
1264 /// [`WitContract::target`] payload-shape dispatch's `let slot =
1265 /// self.slot.as_deref();` binding at the top of the method, and
1266 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
1267 /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
1268 /// field-accesses that expressed no compile-time link back to the
1269 /// typed slot. A future extension of the `:contratos :slot` axis
1270 /// to a richer author surface (an M4 promotion from `Option<String>`
1271 /// to a typed key-template enum once the WIT registry stabilizes
1272 /// key-template parameter shapes in tatara-lisp per this struct's
1273 /// own `:wit` field docstring, a per-cluster slot-alias table the
1274 /// operator pins through a future `:placement`-scoped slot, a
1275 /// canonicalization pass that lowercases the bucket prefix, a
1276 /// per-CR fully-qualified rewrite the M4 CR materializer applies
1277 /// per-tenant) would have had to be threaded through both
1278 /// open-coded copies in lockstep or the two consumers would
1279 /// silently disagree on which key-template a given edge resolves
1280 /// to — the [`WitContract::target`] payload-extraction reading
1281 /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
1282 /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
1283 /// would silently split the [`WitTarget::Store`]-arm rendered
1284 /// payload from the actual dedup-key uniqueness axis, a
1285 /// two-consumer split at the validator far from the source
1286 /// `caixa.lisp` with no field naming the payload-drift root cause.
1287 /// Lifting the resolution rule to a typed method on the substrate
1288 /// primitive means every downstream store-payload-facing consumer
1289 /// of the Aplicacao's per-`:contratos` payload surface reaches for
1290 /// exactly one typed dispatch — the resolver's accept-set migrates
1291 /// as a unit on any future axis addition.
1292 ///
1293 /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
1294 /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
1295 /// accessors on the M3 mesh-slot payload-carrier axis — third and
1296 /// final `Option<&str>`-return accessor on the per-`:contratos`
1297 /// mesh-slot atom, closes the last unlifted per-`:contratos`
1298 /// `Option<String>` axis and completes the "optional per-slot
1299 /// payload-carrier scalar" projection pattern the peer HTTP /
1300 /// pub-sub arms established across the three payload-shape
1301 /// dispatch arms. Named `slot()` to match the storage field's
1302 /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
1303 /// author-facing label const; the accessor's identity name maps
1304 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
1305 /// docstring already carries.
1306 #[must_use]
1307 pub const fn slot(&self) -> Option<&str> {
1308 match &self.slot {
1309 Some(s) => Some(s.as_str()),
1310 None => None,
1311 }
1312 }
1313
1314 /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
1315 /// caller-callee-pair accessor every consumer that constructs an
1316 /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
1317 /// caller-callee pair keys off — returns the author-declared
1318 /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
1319 /// owned `(String, String)` tuple, projected through the lifted
1320 /// [`WitContract::source`] / [`WitContract::destination`] scalar
1321 /// accessors so any future rebrand on the caller-arm / callee-arm
1322 /// projection axis (an M4 per-cluster caller-alias table the
1323 /// operator pins through a future `:placement`-scoped slot, a
1324 /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
1325 /// a per-`:membros` alias overlay from the future `:membros
1326 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1327 /// acknowledges) reaches every diagnostic-construction site by
1328 /// construction.
1329 ///
1330 /// The `(de, para)` pair is the "typed-edge caller-callee identity in
1331 /// owned form" primitive every per-`:contratos` diagnostic variant on
1332 /// [`AplicacaoError`] carries alongside its payload-shape arm — the
1333 /// nine variants [`AplicacaoError::EmptyWit`],
1334 /// [`AplicacaoError::ContratoEndpointEmpty`],
1335 /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
1336 /// [`AplicacaoError::ContratoEndpointInvalid`],
1337 /// [`AplicacaoError::ContratoSubjectEmpty`],
1338 /// [`AplicacaoError::ContratoSubjectInvalid`],
1339 /// [`AplicacaoError::ContratoSlotEmpty`],
1340 /// [`AplicacaoError::ContratoSlotInvalid`], and
1341 /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
1342 /// para: String` field pair the constructor site reads verbatim off
1343 /// the [`WitContract`] the diagnostic points at, so a diagnostic
1344 /// whose `de:` and `para:` labels silently drift off the source
1345 /// caller/callee — a per-cluster caller-alias rewrite that landed on
1346 /// one variant's inline `de: c.de.clone()` field access but not on
1347 /// its sibling variant's, an accidental swap of the `de:` and `para:`
1348 /// arms in a copy-paste of the constructor block — would emit a
1349 /// build-time error whose "which caixa is at fault" question the
1350 /// operator answers wrongly, far from the source `caixa.lisp`.
1351 ///
1352 /// Prior to this lift the `(self.de.clone(), self.para.clone())`
1353 /// pair was inlined at seven [`WitContract::target`] error-
1354 /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
1355 /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
1356 /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
1357 /// the [`AplicacaoError::ContratoSubjectEmpty`] /
1358 /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
1359 /// the [`AplicacaoError::ContratoSlotEmpty`] /
1360 /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
1361 /// two [`AplicacaoSpec::validate`] error-construction sites (the
1362 /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
1363 /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
1364 /// insert-first-seen closure) — nine open-coded `.de.clone() +
1365 /// .para.clone()` pairs that expressed no compile-time contract that
1366 /// the caller-arm and callee-arm arms of the same diagnostic
1367 /// construction reach for the same [`WitContract`] instance or that
1368 /// the `de:` and `para:` label pair binds to the fields the author
1369 /// declared. Any future rebrand on the axis — an M4 per-cluster
1370 /// caller/callee-alias rewrite the operator pins through a future
1371 /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
1372 /// per-CR fully-qualified namespace prefix the M4
1373 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
1374 /// per-tenant, a canonicalization pass that lowercases the caller +
1375 /// callee identifiers post-parse — would have had to be threaded
1376 /// through every open-coded copy in lockstep or one variant's
1377 /// diagnostic would silently name a different caller/callee pair
1378 /// than its peer, silently degrading the "which caixa is at fault"
1379 /// self-locating signal every operator-facing typed diagnostic
1380 /// exists to carry. Lifting the pair to a typed method on the
1381 /// substrate primitive means every downstream diagnostic-construction
1382 /// site reaches for exactly one typed dispatch — the resolver's
1383 /// projection migrates as a unit on any future axis addition.
1384 ///
1385 /// Peer of the sibling per-`:contratos` scalar accessor family
1386 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
1387 /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
1388 /// scalar-value axes — first composite-projection accessor on the
1389 /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
1390 /// form `.clone()` field-accesses that pair the sibling
1391 /// caller/callee accessors' `&str`-return borrowed-form outputs onto
1392 /// one typed dispatch. Named `edge_pair()` to reflect the identity
1393 /// name of the projected tuple (the typed-edge caller-callee pair,
1394 /// distinct from the sibling triple-projection
1395 /// [`WitContract::edge_triple`] accessor that folds the local `edge`
1396 /// closure in [`WitContract::target`] + the paired
1397 /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
1398 /// site's `(de, para, wit)` triple onto one typed dispatch).
1399 #[must_use]
1400 pub fn edge_pair(&self) -> (String, String) {
1401 (self.source().to_string(), self.destination().to_string())
1402 }
1403
1404 /// Owned form of the `(:contratos :de, :contratos :para, :contratos
1405 /// :wit)` triple every per-edge diagnostic constructor that names
1406 /// all three axes threads verbatim into its `de:` / `para:` /
1407 /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
1408 /// / missing-target / invalid-wit / capability-with-payload arms
1409 /// (eight sites all shape `let (de, para, wit) = edge();
1410 /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
1411 /// accessor landed) and the sibling
1412 /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
1413 /// constructor (which paired `edge_pair()` for the `(de, para)`
1414 /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
1415 /// typed-dispatch + raw-field-access shape the sibling accessor
1416 /// family already flagged as a drift risk). Nine total call sites
1417 /// collapse onto this helper.
1418 ///
1419 /// Lifted with the same one-source-of-truth discipline
1420 /// [`WitContract::edge_pair`] carries on the paired
1421 /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
1422 /// arms compose through the lifted [`WitContract::source`] /
1423 /// [`WitContract::destination`] / [`WitContract::world_ref`]
1424 /// scalar accessors byte-for-byte (pinned by the paired
1425 /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
1426 /// composition-pin), so any future rebrand on the per-`:contratos`
1427 /// caller / callee / world-ref axis (an M4 per-cluster
1428 /// caller/callee-alias rewrite the operator pins through a future
1429 /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
1430 /// per-CR fully-qualified namespace prefix the M4
1431 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
1432 /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
1433 /// on `source()` / `destination()`, a per-CR canonicalization pass
1434 /// that lowercases the WIT world ref post-parse) migrates as a
1435 /// single caixa-core edit rather than a coordinated rewrite of
1436 /// nine open-coded triple-constructors.
1437 ///
1438 /// Peer of the sibling per-`:contratos` composite-projection
1439 /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
1440 /// composite-value axes — closes the last unlifted owned-form
1441 /// composite-tuple axis on the per-`:contratos` diagnostic-
1442 /// construction surface. Named `edge_triple()` to reflect the
1443 /// identity name of the projected tuple (the typed-edge
1444 /// caller-callee-wit triple, sibling to the caller-callee-only
1445 /// pair `edge_pair()` returns).
1446 #[must_use]
1447 pub fn edge_triple(&self) -> (String, String, String) {
1448 (
1449 self.source().to_string(),
1450 self.destination().to_string(),
1451 self.world_ref().to_string(),
1452 )
1453 }
1454
1455 /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
1456 /// dedups typed edges keys off — routes through the lifted
1457 /// [`WitContract::source`] / [`WitContract::destination`] /
1458 /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
1459 /// [`WitContract::subject`] / [`WitContract::slot`] scalar
1460 /// accessors so the tuple's six arms and the [`ContratoIdentity`]
1461 /// type alias's six axes migrate as a unit on any future axis
1462 /// addition (adding a seventh field to [`WitContract`] is one
1463 /// [`ContratoIdentity`] alias edit + one accessor addition + one
1464 /// arm here, not a coordinated rewrite of every open-coded
1465 /// six-tuple builder that dedups on the identity axis).
1466 ///
1467 /// Sibling of [`WitContract::edge_pair`] /
1468 /// [`WitContract::edge_triple`] on the composite-projection axis:
1469 /// the pair projects the caller-callee axes, the triple extends it
1470 /// with the world-ref, this method extends it with the three
1471 /// payload-carrier axes. Every projection returns the same six
1472 /// scalar accessors' outputs; the three methods differ only in
1473 /// which arms they surface.
1474 ///
1475 /// Declared `pub const fn` — every callee is itself `pub const fn`
1476 /// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
1477 /// project through `pub const fn` [`String::as_str`], const-stable
1478 /// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
1479 /// [`Self::slot`] project through the same `String::as_str` under a
1480 /// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
1481 /// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
1482 /// closed the const-eval surface on) and tuple construction from
1483 /// borrowed-reference / `Option`-of-borrowed-reference arms is
1484 /// itself trivially const. The `ContratoIdentity<'_>` alias
1485 /// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
1486 /// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
1487 /// no heap allocation, no non-const call folded through the tuple's
1488 /// construction. Sibling in `const`-eval posture to the peer
1489 /// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
1490 /// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
1491 /// composite-projection family the sibling
1492 /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1493 /// already anchors — this extends the same `const`-eval-surface
1494 /// posture onto the peer six-arm composite-projection axis where
1495 /// the projection surfaces the full identity tuple rather than a
1496 /// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
1497 /// bearing by
1498 /// [`wit_contract_identity_projection_accessor_is_const_fn`] below
1499 /// (a future accidental downgrade fires E0015 at the wrapper at
1500 /// caixa-core build time).
1501 #[must_use]
1502 pub const fn identity(&self) -> ContratoIdentity<'_> {
1503 (
1504 self.source(),
1505 self.destination(),
1506 self.world_ref(),
1507 self.endpoint(),
1508 self.subject(),
1509 self.slot(),
1510 )
1511 }
1512
1513 /// True when this contract targets an HTTP-shaped WIT world.
1514 ///
1515 /// Declared `pub const fn` — routes through the paired `pub const
1516 /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1517 /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1518 /// (d46420c). Sibling in `const`-eval posture to the peer
1519 /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1520 /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1521 /// 4-arm partition on the raw `:contratos :wit` axis now carries
1522 /// the same `const`-eval-surface posture as the free-function
1523 /// classifier family it composes through. Pinned load-bearing by
1524 /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1525 /// test (a future accidental downgrade to non-`const` fires E0015
1526 /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1527 /// build time).
1528 #[must_use]
1529 pub const fn is_http(&self) -> bool {
1530 wit_shape_is_http(self.world_ref())
1531 }
1532
1533 /// True when this contract targets a pub-sub-shaped WIT world.
1534 ///
1535 /// Declared `pub const fn` — sibling in `const`-eval posture to
1536 /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1537 /// [`Self::is_capability`] WIT-shape-predicate family. See
1538 /// [`Self::is_http`] for the family-closure rationale.
1539 #[must_use]
1540 pub const fn is_pubsub(&self) -> bool {
1541 wit_shape_is_pubsub(self.world_ref())
1542 }
1543
1544 /// True when this contract targets a key/value-shaped WIT world.
1545 ///
1546 /// Declared `pub const fn` — sibling in `const`-eval posture to
1547 /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1548 /// [`Self::is_capability`] WIT-shape-predicate family. See
1549 /// [`Self::is_http`] for the family-closure rationale.
1550 #[must_use]
1551 pub const fn is_store(&self) -> bool {
1552 wit_shape_is_store(self.world_ref())
1553 }
1554
1555 /// True when this contract targets *none* of the three known payload-
1556 /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1557 /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1558 /// open on the [`WitContract`] surface. Returns the exact-inverse
1559 /// disjunction of the peer trio — `true` when none of the three
1560 /// prefix-set predicates matches the raw `:contratos :wit` value; the
1561 /// author-declared WIT world is a pure typed capability edge with no
1562 /// payload selector (the shape [`WitContract::target`] projects onto
1563 /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1564 /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1565 ///
1566 /// The `:contratos :wit` shape-space is closed at four arms
1567 /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1568 /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1569 /// everything else on the payload-less capability arm), and every
1570 /// downstream consumer that must filter contratos by shape-class
1571 /// keys off the four sibling predicates (the [`WitContract::target`]
1572 /// dispatch's implicit `else` after the three payload-shape arm
1573 /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1574 /// every future substrate-side capability-shape-only emitter — the
1575 /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1576 /// future `feira app graph --capability` per-Aplicacao capability-
1577 /// column filter, the future per-cluster capability-scope reconciler
1578 /// that skips L4/L7 emission for payload-less edges since Cilium
1579 /// can't introspect WASI capability calls, the future
1580 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1581 /// shape shape-count histogram). Every such consumer reaches for one
1582 /// typed dispatch on the substrate primitive so the "which arm
1583 /// carries the capability-only shape?" answer lives at one caixa-core
1584 /// edit rather than open-coded across per-consumer
1585 /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1586 /// negations, each of which would silently drop a future fourth
1587 /// payload-arm addition without a compile-time signal at the
1588 /// consumer site.
1589 ///
1590 /// Prior to this lift the "not one of the three known payload
1591 /// shapes" classification sat inline at [`WitContract::target`]'s
1592 /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1593 /// [`WitTarget::Capability`] admission arm after the three `if
1594 /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1595 /// { … }` guards) with no named accessor for downstream consumers
1596 /// to reach through. A future substrate-side capability-only
1597 /// filter or a future capability-scope reconciler would have had to
1598 /// re-inline the same triplet negation at every emit site with no
1599 /// compile-time link back to the sibling trio, and a future arm
1600 /// addition (a hypothetical fourth payload-shape prefix set — a
1601 /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1602 /// import carrier per the sibling [`wit_shape_matches`] docstring's
1603 /// trajectory bullet) would land the new predicate on the payload-
1604 /// carrying trio and silently misclassify the new shape as
1605 /// capability at every triplet-negation consumer site, propagating
1606 /// the drift far from the caixa-core prefix-set commit.
1607 ///
1608 /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1609 /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1610 /// trio into a 4-way partition witness on the raw `:contratos :wit`
1611 /// axis, mirroring the paired post-projection [`WitTarget`]
1612 /// `gen_platform::IsVariant`-derived 4-way predicate set
1613 /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1614 /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1615 /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1616 /// arm-set). The two typed axes — pre-projection on the raw
1617 /// `:contratos :wit` string, post-projection on the validated typed
1618 /// view — now carry a matched 4-arm predicate discipline: every
1619 /// arm on the closed [`WitTarget`] set has a peer pre-projection
1620 /// predicate on the [`WitContract`] surface, and any future
1621 /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1622 /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1623 /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1624 /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1625 /// pre-projection axis through a matching peer prefix-set + peer
1626 /// predicate lift by construction — the compile-time exhaustiveness
1627 /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1628 /// the post-projection accessor family stays in sync, and the sibling
1629 /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1630 /// partition-witness pin locks the pre-projection classification in
1631 /// load-bearing so a peer prefix-set addition that widened one arm's
1632 /// accept-set without shrinking the [`Self::is_capability`] accept-set
1633 /// surfaces as a test failure at caixa-core build time rather than a
1634 /// silent per-consumer split at renderer emit time.
1635 ///
1636 /// Composes byte-for-byte through the lifted peer trio
1637 /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1638 /// any future rebrand of any prefix-set const flows through this
1639 /// method by construction without a coordinated per-consumer rewrite
1640 /// (pinned by the sibling
1641 /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1642 /// composition-witness).
1643 ///
1644 /// Note: purely syntactic classification on the `:wit` prefix-set —
1645 /// unlike [`Self::target`], which additionally rejects value-shape-
1646 /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1647 /// package) via [`crate::render::is_wit_world_ref`] and payload-
1648 /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1649 /// structurally malformed returns `true` from `is_capability()` (the
1650 /// prefix set matches nothing), and the surrounding
1651 /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1652 /// is where the [`AplicacaoError::EmptyWit`] /
1653 /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1654 /// predicate is the classifier, not the validator.
1655 ///
1656 /// Declared `pub const fn` — closes the WIT-shape-predicate
1657 /// family's `const`-eval-surface pass at the fourth (payload-less)
1658 /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1659 /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1660 /// See [`Self::is_http`] for the family-closure rationale.
1661 #[must_use]
1662 pub const fn is_capability(&self) -> bool {
1663 wit_shape_is_capability(self.world_ref())
1664 }
1665
1666 /// True when this contract's caller equals its callee — a
1667 /// structurally degenerate typed edge that no `:contratos` entry can
1668 /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1669 /// Servico B" is an *inter*-Servico contract between two distinct
1670 /// graph nodes). A Servico contracting with itself resolves to an
1671 /// in-process call the wasm-engine never routes through the mesh at
1672 /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1673 /// per-edge policy can express the intended shape — the pub-sub
1674 /// path silently rendered a self-allow rule that is a no-op (intra-
1675 /// pod traffic bypasses the mesh entirely), and the synchronous
1676 /// paths surfaced as a misleading `ContratoCycle` whose path was
1677 /// `["cart", "cart"]` — framing a self-edge as a multi-node
1678 /// deadlock. Every downstream consumer that must reject the shape
1679 /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1680 /// gate at caixa-core/src/aplicacao.rs:5559, every future
1681 /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1682 /// axis, every future adjacency-graph builder that must skip self-
1683 /// edges rather than fold them into an incidental cycle) now keys
1684 /// off exactly one typed dispatch on the substrate primitive, so
1685 /// any future rebrand on the axis (an M4-typed-caller enum whose
1686 /// identity comparison rule the accessor could route through, an
1687 /// operator-side per-cluster caller/callee-alias table the
1688 /// materializer resolves per-CR before the equality probe, a
1689 /// promotion of the pointwise `==` to a set-membership check once
1690 /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1691 /// so a per-replica self-edge is rejected under the same predicate)
1692 /// migrates as a single caixa-core edit rather than a coordinated
1693 /// rewrite of every downstream self-edge consumer. Composes
1694 /// byte-for-byte through the lifted [`Self::source`] /
1695 /// [`Self::destination`] scalar accessors — the accessor pair every
1696 /// per-`:contratos` scalar-value axis already routes through — so
1697 /// any future rebrand of the underlying `:de` / `:para` storage
1698 /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1699 /// a per-Aplicacao interning arena the M4 CR materializer authors,
1700 /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1701 /// same one body without a coordinated per-consumer rewrite.
1702 ///
1703 /// Sibling in shape to the peer per-`:contratos` shape-predicate
1704 /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1705 /// on the `:wit` world-ref axis — extended onto the per-edge
1706 /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1707 /// partition the WIT-shape-space; `is_self_loop` partitions the
1708 /// caller-callee identity-space. Named `is_self_loop()` to reflect
1709 /// the graph-theoretic identity of the shape (a loop from a graph
1710 /// node to itself, distinct from the sibling multi-node
1711 /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1712 /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1713 /// variant already carrying the term.
1714 ///
1715 /// Declared `pub const fn` — closes the last unlifted per-`:contratos`
1716 /// shape-predicate on the substrate's `const`-eval surface. The peer
1717 /// per-`:contratos` shape-predicate family [`Self::is_http`] /
1718 /// [`Self::is_pubsub`] / [`Self::is_store`] / [`Self::is_capability`]
1719 /// (d46420c / 84c2325 / 279823b) already carries the `pub const fn`
1720 /// posture on the WIT-world-ref classifier axis; this lift extends it
1721 /// onto the peer caller-callee identity-space predicate. The body
1722 /// projects the `:de` / `:para` `String` storage through the sibling
1723 /// `pub const fn` [`Self::source`] / [`Self::destination`] scalar
1724 /// accessors, then compares the resulting `&str` byte-slices under a
1725 /// manual `while`-loop through `str::as_bytes` (`pub const fn`,
1726 /// const-stable since Rust 1.39), primitive-`usize` `!=` on
1727 /// [`<[u8]>::len`], and const-stable slice indexing (since Rust 1.79)
1728 /// — every operation `const`-eval-callable on stable Rust, no
1729 /// iterator methods, no `PartialEq for str` trait dispatch (which
1730 /// remains non-`const` on stable). Mirrors the peer `pub const fn`
1731 /// [`wit_shape_matches`] combinator's manual byte-level `starts_with`
1732 /// loop verbatim on the paired-slice-equality shape. Every downstream
1733 /// substrate-side `const`-context consumer of the per-`:contratos`
1734 /// self-edge partition (a future `const _: () = assert!(…)` module-
1735 /// scope invariant pin over a per-fixture typed [`WitContract`] once
1736 /// the type's carriers admit `const`-context construction, a future
1737 /// M4 admission-webhook `const fn` self-edge resolver, any `const fn`
1738 /// composer that fans on the identity-space partition at compile
1739 /// time) reaches through the same typed dispatch on the substrate
1740 /// primitive at const-eval time as at runtime. Pinned by
1741 /// [`tests::wit_contract_is_self_loop_predicate_is_const_fn`] which
1742 /// witnesses the `const`-eval posture via a `const fn` wrapper so any
1743 /// future accidental downgrade to non-`const` trips at caixa-core
1744 /// build time with E0015 (`cannot call non-const method`), strictly
1745 /// stronger than a runtime `assert!`.
1746 #[must_use]
1747 pub const fn is_self_loop(&self) -> bool {
1748 // Compose through the paired `pub const fn` [`Self::source`] /
1749 // [`Self::destination`] scalar accessors so any future rebrand of
1750 // the underlying `:de` / `:para` storage (a lift from `String` to
1751 // a typed `ServicoName(String)` newtype, a per-Aplicacao interning
1752 // arena the M4 CR materializer authors, a `smol_str::SmolStr`
1753 // inline-buffer swap) flows through the same one body without a
1754 // coordinated per-consumer rewrite. Peer of the sibling
1755 // [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1756 // [`Self::is_capability`] shape-predicate family — each of which
1757 // composes through the paired [`Self::world_ref`] scalar accessor
1758 // onto the peer `pub const fn` [`wit_shape_is_http`] /
1759 // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
1760 // [`wit_shape_is_capability`] free-function classifier — the same
1761 // "typed dispatch composes with typed dispatch, not raw field
1762 // access" discipline extended onto the caller-callee identity-
1763 // space partition. Pinned by
1764 // [`tests::wit_contract_is_self_loop_routes_through_source_destination_accessors`]
1765 // above.
1766 let a = self.source().as_bytes();
1767 let b = self.destination().as_bytes();
1768 if a.len() != b.len() {
1769 return false;
1770 }
1771 // Manual byte-level equality loop — mirrors the peer
1772 // [`wit_shape_matches`] combinator's manual `starts_with` loop
1773 // verbatim on the paired-slice-equality shape. `PartialEq for
1774 // str` remains non-`const` on stable Rust 1.94 (the `Pattern`
1775 // trait dispatch it routes through is not `const`), so a naive
1776 // `self.source() == self.destination()` body would trip on
1777 // `const`-eval-callability; the byte-slice loop dispatches
1778 // through primitive-`u8` `!=`, primitive-`usize` comparison, and
1779 // const-stable slice indexing (since Rust 1.79) — every
1780 // operation `const`-eval-callable on stable.
1781 let mut i = 0;
1782 while i < a.len() {
1783 if a[i] != b[i] {
1784 return false;
1785 }
1786 i += 1;
1787 }
1788 true
1789 }
1790
1791 /// Reject a `:contratos` entry whose `:de` or `:para` names a
1792 /// caixa the `:membros` graph does not contain — the substrate-
1793 /// primitive per-edge graph-membership gate every consumer of the
1794 /// typed inter-Servico edge's endpoint-resolution axis reaches
1795 /// through one dispatch.
1796 ///
1797 /// A `:contratos` entry is a typed directed edge between two
1798 /// declared members (MESH-COMPOSITION §III.1 — "the typed edges
1799 /// address graph nodes, so a reference to a node the graph does
1800 /// not contain is a build error"). Both endpoints must resolve
1801 /// against the same [`AplicacaoSpec::membro_names`] oracle: the
1802 /// paired [`AplicacaoError::ContratoMemberMissing`] diagnostic
1803 /// framing does not distinguish `:de` from `:para` (both arms
1804 /// carry the offending `caixa` name verbatim without a
1805 /// slot-discriminator field, unlike the sibling per-arm shape
1806 /// gate [`validate_contrato_caixa`] whose paired
1807 /// [`AplicacaoError::ContratoCaixaEmpty`] / `ContratoCaixaInvalid`
1808 /// variants each carry a `slot: &'static str` tag). So the two
1809 /// arms are byte-identical modulo the accessor projection they
1810 /// key off, and folding them into one per-edge dispatch preserves
1811 /// every existing diagnostic-fired output byte-for-byte while
1812 /// closing the last inline duplication the substrate-primitive
1813 /// per-edge gate family carried inside
1814 /// [`AplicacaoSpec::validate_contratos`].
1815 ///
1816 /// Routes through the paired [`Self::source`] / [`Self::destination`]
1817 /// scalar accessors so every future rebrand of the underlying
1818 /// `:de` / `:para` storage (a lift from `String` to a typed
1819 /// `ServicoName(String)` newtype, a per-Aplicacao interning arena
1820 /// the M4 CR materializer authors, a per-cluster caller-alias
1821 /// table the operator pins through a future `:placement`-scoped
1822 /// slot, an M4 promotion from `String` to a typed edge-endpoint
1823 /// enum) flows through the same body without a coordinated
1824 /// per-consumer rewrite. Peer of the sibling per-edge substrate
1825 /// primitives already lifted on the same `impl WitContract`
1826 /// surface ([`Self::is_self_loop`] on the identity-space arm,
1827 /// [`Self::target`] on the payload-shape ↔ target-consistency
1828 /// arm, [`Self::identity`] on the dedup-key arm) — this run
1829 /// extends the shape to the last per-edge axis
1830 /// [`AplicacaoSpec::validate_contratos`] carried as an inline
1831 /// twin-arm cascade.
1832 ///
1833 /// Every future consumer that wants to re-check *one* edge's
1834 /// graph-membership reaches through one call: the M4
1835 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
1836 /// admission-webhook re-checking `:contratos` after a
1837 /// per-`(:de, :para)` edge patch without re-walking the whole
1838 /// `:contratos` list, the per-`:contratos`-edge `:politicas`
1839 /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
1840 /// resolves an effective per-edge [`MeshPolicy`] and must
1841 /// re-check the edge's endpoints against the same membership
1842 /// oracle before it can key a per-edge override off the endpoint
1843 /// tuple. Pre-lift each such consumer was structurally forced to
1844 /// either re-inline the twin `if !names.contains(...)` cascade
1845 /// (the duplication the PRIME DIRECTIVE names as a bug) or call
1846 /// [`AplicacaoSpec::validate_contratos`] and pay a whole-list
1847 /// walk to re-check one edge. Post-lift each reaches the axis
1848 /// through one dispatch on the substrate primitive.
1849 ///
1850 /// `:de` runs before `:para` per the canonical edge-direction
1851 /// order the sibling per-arm shape gate
1852 /// [`validate_contrato_caixa`] arm ordering, the self-loop
1853 /// diagnostic string, and every peer arm ordering in
1854 /// [`AplicacaoSpec::validate_contratos`] already use — a
1855 /// well-shaped-but-phantom `:de` fires before a well-shaped-but-
1856 /// phantom `:para`, preserving byte-equal ordering with the
1857 /// pre-lift inline cascade.
1858 fn require_endpoints_in(
1859 &self,
1860 names: &std::collections::HashSet<&str>,
1861 ) -> Result<(), AplicacaoError> {
1862 if !names.contains(self.source()) {
1863 return Err(AplicacaoError::contrato_member_missing(self.source()));
1864 }
1865 if !names.contains(self.destination()) {
1866 return Err(AplicacaoError::contrato_member_missing(self.destination()));
1867 }
1868 Ok(())
1869 }
1870
1871 /// Typed view of the contract's payload target. Enforces that the
1872 /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1873 /// fields agree, and that each carried value is itself
1874 /// value-shape valid:
1875 ///
1876 /// - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1877 /// non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1878 /// `PathPrefix` invariant — same shape required of `:entrada
1879 /// :paths`)
1880 /// - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1881 /// non-empty (NATS / Kafka publish without a subject is a
1882 /// no-op subscribe, never the author's intent)
1883 /// - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1884 /// non-empty (an empty slot template addresses the bucket
1885 /// root, defeating the per-key isolation the slot exists for)
1886 /// - Anything else ⇒ none of the three; the contract is a pure
1887 /// typed capability edge with no payload selector.
1888 ///
1889 /// Translates the Apollo Federation discipline ("conflicts are
1890 /// errors at compile time, not warnings at runtime";
1891 /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1892 /// a contract whose WIT shape disagrees with its target field, or
1893 /// whose target field carries a value-shape-invalid string, is a
1894 /// build error — not a silent renderer drop. The returned
1895 /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1896 /// non-empty (and absolute, for `Http`); every downstream consumer
1897 /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1898 /// the M4 per-edge policy resolver) can rely on that without
1899 /// re-checking.
1900 pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1901 // Route the HTTP-shaped payload-target extraction through the
1902 // lifted [`WitContract::endpoint`] accessor rather than the raw
1903 // `self.endpoint.as_deref()` field access — the two production
1904 // consumers of the per-`:contratos :endpoint` HTTP-shaped
1905 // payload-carrier scalar (this method's Http-arm payload
1906 // extraction, the [`AplicacaoSpec::validate`] duplicate-
1907 // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1908 // off exactly one typed dispatch on the substrate primitive, so
1909 // any future rebrand on the axis (an M4 per-cluster endpoint-
1910 // alias rewrite, a per-CR fully-qualified path prefix the M4
1911 // materializer applies per-tenant, an M4 promotion from
1912 // `Option<String>` to a typed HTTP path-template enum) migrates
1913 // as a single caixa-core edit rather than a coordinated rewrite
1914 // of the two call sites — peer of the sibling M3 per-`:placement`
1915 // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1916 // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1917 // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1918 let endpoint = self.endpoint();
1919 let subject = self.subject();
1920 // Route the store-arm payload-carrier scalar through the
1921 // lifted [`WitContract::slot`] accessor rather than the raw
1922 // `self.slot.as_deref()` field access — the two production
1923 // consumers of the per-`:contratos :slot` key/value-store-
1924 // shaped payload-carrier scalar (this method's Store-arm
1925 // payload extraction, the [`AplicacaoSpec::validate`]
1926 // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1927 // arm) now key off exactly one typed dispatch on the substrate
1928 // primitive. Closes the last unlifted per-`:contratos`
1929 // `Option<String>` axis, completing the payload-carrier
1930 // accessor family peer of the sibling per-`:contratos`
1931 // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1932 // (90de675) lifts across the HTTP / pub-sub arms.
1933 let slot = self.slot();
1934 // Route the local `(de, para, wit)` triple-projection closure
1935 // through the lifted [`WitContract::edge_triple`] typed accessor
1936 // rather than re-inlining `(self.de.clone(), self.para.clone(),
1937 // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1938 // triple-carrying diagnostic constructors below (wrong-target /
1939 // missing-target on all three payload arms + capability-with-
1940 // payload + invalid-wit) now key off exactly one typed dispatch
1941 // on the substrate-primitive composite projection, sibling to
1942 // the peer [`WitContract::edge_pair`]-routed
1943 // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1944 // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1945 // diagnostic constructors on the same per-`:contratos`
1946 // diagnostic-construction surface.
1947 let edge = || self.edge_triple();
1948
1949 // The `:wit` value drives every downstream dispatch — the
1950 // is_http/is_pubsub/is_store prefix matchers below, the
1951 // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1952 // exclusion. Until this gate landed `target()` accepted any
1953 // non-empty string and silently demoted unrecognized shapes to
1954 // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1955 // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1956 // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1957 // package, the paste-from-binary footgun a multi-line blob
1958 // accidentally landing in the slot, the un-percent-encoded
1959 // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1960 // routing, got L4-only" footgun. Empty is still pre-checked at
1961 // the [`AplicacaoSpec::validate`] call site via the narrower
1962 // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1963 // validate layer); the value-shape gate here picks up the
1964 // structurally-invalid non-empty cases the empty check misses,
1965 // and remains correct under direct `target()` calls outside
1966 // validate (the predicate's defensive empty arm returns a
1967 // parser-shaped reason rather than silently falling through to
1968 // the Capability arm). Same trajectory as c4213a4 (WitContract
1969 // endpoint/subject/slot value-shape gates lifted into
1970 // `target()`) on the peer payload axes.
1971 //
1972 // Routed through the lifted [`WitContract::world_ref`] accessor
1973 // rather than the raw `&self.wit` field access — the two
1974 // production consumers of the per-`:contratos :wit` world-ref
1975 // byte-string on the value-shape axis (this method's invalid-
1976 // wit gate, the [`AplicacaoSpec::validate`] duplicate-
1977 // `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
1978 // [`WitContract::identity`]) now key off exactly one typed
1979 // dispatch on the substrate primitive, so any future rebrand on
1980 // the axis (an M4 promotion from `String` to a typed WIT
1981 // world-ref enum once the WIT registry stabilizes in
1982 // tatara-lisp, a per-CR canonicalization pass that lowercases
1983 // the WIT world ref post-parse, a promoted `smol_str::SmolStr`
1984 // inline-buffer swap on the storage arm) migrates as a single
1985 // caixa-core edit rather than a coordinated rewrite of the two
1986 // call sites — sibling of the peer [`WitContract::endpoint`] /
1987 // [`WitContract::subject`] / [`WitContract::slot`] accessor-
1988 // routed payload-carrier extractions above on the same
1989 // [`WitContract::target`] body, completing the per-`:contratos`
1990 // scalar-accessor-routing pass at the last unlifted raw-field-
1991 // access site inside `impl WitContract`. Same "typed dispatch
1992 // composes with typed dispatch, not with raw field access"
1993 // discipline the sibling [`WitContract::edge_pair`] /
1994 // [`WitContract::edge_triple`] / [`WitContract::identity`]
1995 // composite-projection accessors and the
1996 // [`WitContract::is_self_loop`] identity-space predicate
1997 // already route through. Pinned by
1998 // [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
1999 if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
2000 return Err(AplicacaoError::contrato_wit_invalid(
2001 self.edge_pair(),
2002 self.world_ref(),
2003 reason,
2004 ));
2005 }
2006
2007 if self.is_http() {
2008 if subject.is_some() || slot.is_some() {
2009 return Err(AplicacaoError::contrato_wrong_target(
2010 edge(),
2011 WitTarget::HTTP_FIELD_NAME,
2012 ));
2013 }
2014 let ep = endpoint.ok_or_else(|| {
2015 AplicacaoError::contrato_missing_target(edge(), WitTarget::HTTP_FIELD_NAME)
2016 })?;
2017 if ep.is_empty() {
2018 return Err(AplicacaoError::contrato_endpoint_empty(self.edge_pair()));
2019 }
2020 if !ep.starts_with('/') {
2021 return Err(AplicacaoError::contrato_endpoint_not_absolute(
2022 self.edge_pair(),
2023 ep,
2024 ));
2025 }
2026 // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
2027 // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
2028 // API v1 HTTPPathMatch.value admission grammar with the
2029 // sibling `:entrada :paths` axis. Until this gate landed
2030 // `target()` only refused the empty string + the missing-
2031 // leading-`/` form; a structurally invalid endpoint
2032 // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
2033 // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
2034 // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
2035 // path-traversal segment, the >1024-byte slug) silently
2036 // passed validate and the failure surfaced at apply time
2037 // as a Cilium policy rejection / silent traffic drop, far
2038 // from the source caixa.lisp. Same Gateway API HTTPPathMatch
2039 // grammar `:entrada :paths` already gates (55410e4), now
2040 // shared with `:contratos :endpoint` through the lifted
2041 // `crate::render::is_gateway_api_http_path` predicate.
2042 if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
2043 return Err(AplicacaoError::contrato_endpoint_invalid(
2044 self.edge_pair(),
2045 ep,
2046 reason,
2047 ));
2048 }
2049 return Ok(WitTarget::Http { endpoint: ep });
2050 }
2051 if self.is_pubsub() {
2052 if endpoint.is_some() || slot.is_some() {
2053 return Err(AplicacaoError::contrato_wrong_target(
2054 edge(),
2055 WitTarget::PUBSUB_FIELD_NAME,
2056 ));
2057 }
2058 let s = subject.ok_or_else(|| {
2059 AplicacaoError::contrato_missing_target(edge(), WitTarget::PUBSUB_FIELD_NAME)
2060 })?;
2061 if s.is_empty() {
2062 return Err(AplicacaoError::contrato_subject_empty(self.edge_pair()));
2063 }
2064 // The `:subject` lands at runtime as the NATS subject the
2065 // producer publishes to and the consumer subscribes from.
2066 // Until this gate landed `target()` only refused the
2067 // empty string; a structurally invalid subject
2068 // (`"foo..bar"` — empty token between separators,
2069 // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
2070 // server's subject parser rejects, `"foo bar"` —
2071 // un-percent-encoded whitespace, `"foo.café"` —
2072 // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
2073 // empty leading/trailing tokens, the >256-byte
2074 // paste-from-binary slug) silently passed validate and
2075 // the failure surfaced at runtime as a NATS server-side
2076 // `-ERR 'Invalid Subject'` on publish / subscribe, or as
2077 // a silent message drop, far from the source caixa.lisp.
2078 // Same Gateway API HTTPPathMatch / WIT-IDL grammar
2079 // trajectory `:contratos :endpoint` (4f0390b) and
2080 // `:contratos :wit` (6226bf4) already gate, now shared
2081 // with `:contratos :subject` through the lifted
2082 // `crate::render::is_nats_subject` predicate.
2083 if let Err(reason) = crate::render::is_nats_subject(s) {
2084 return Err(AplicacaoError::contrato_subject_invalid(
2085 self.edge_pair(),
2086 s,
2087 reason,
2088 ));
2089 }
2090 return Ok(WitTarget::PubSub { subject: s });
2091 }
2092 if self.is_store() {
2093 if endpoint.is_some() || subject.is_some() {
2094 return Err(AplicacaoError::contrato_wrong_target(
2095 edge(),
2096 WitTarget::STORE_FIELD_NAME,
2097 ));
2098 }
2099 let sl = slot.ok_or_else(|| {
2100 AplicacaoError::contrato_missing_target(edge(), WitTarget::STORE_FIELD_NAME)
2101 })?;
2102 if sl.is_empty() {
2103 return Err(AplicacaoError::contrato_slot_empty(self.edge_pair()));
2104 }
2105 // Value-shape gate on the third (and last) typed payload
2106 // axis the `WitContract::target` dispatch carries — the
2107 // peer of [`crate::render::is_gateway_api_http_path`] for
2108 // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
2109 // for `:subject` (63e18a0). Until this gate landed
2110 // `target()` only refused the empty string; a structurally
2111 // invalid slot (`"check out/$order"` — un-percent-encoded
2112 // whitespace whose runtime behavior varies unpredictably
2113 // across kv backends, `"checkout/\x01order"` — control
2114 // character that Redis admits but corrupts on next read
2115 // and DynamoDB rejects outright, `"chéckout/$order"` —
2116 // un-percent-encoded non-ASCII byte each backend re-encodes
2117 // differently, `"checkout\n/$order"` — embedded newline,
2118 // the 513-byte paste-from-binary slug) silently passed
2119 // validate and surfaced at runtime as a per-backend kv
2120 // write rejection (DynamoDB / etcd) or as a silent
2121 // next-read corruption (Redis-via-RESP3), far from the
2122 // source caixa.lisp with no field naming which `:contratos`
2123 // edge carried the typo. The lifted predicate makes the
2124 // kv-backend intersection-floor a substrate-level
2125 // invariant at validate time, not a runtime "this passed
2126 // validate but the kv backend rejected on first write"
2127 // surprise — closes the typed payload-axis value-shape
2128 // trajectory across all three legs of the four
2129 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
2130 // that caixa-mesh + the future kv emitters land in.
2131 if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
2132 return Err(AplicacaoError::contrato_slot_invalid(
2133 self.edge_pair(),
2134 sl,
2135 reason,
2136 ));
2137 }
2138 return Ok(WitTarget::Store { slot: sl });
2139 }
2140
2141 // Unrecognized WIT world — must not carry any payload target.
2142 if endpoint.is_some() || subject.is_some() || slot.is_some() {
2143 return Err(AplicacaoError::contrato_wrong_target(
2144 edge(),
2145 WitTarget::CAPABILITY_EXPECTED,
2146 ));
2147 }
2148 Ok(WitTarget::Capability)
2149 }
2150
2151 /// Substrate-canonical post-validation projection of the typed
2152 /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
2153 /// downstream of an [`AplicacaoSpec`] that has already crossed the
2154 /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
2155 /// [`typed_view`]-shaped entry point that composes `validate` into
2156 /// the projection) reaches through when it needs the typed
2157 /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
2158 /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
2159 /// coherence for every `:contratos` entry. The peer accessor to the
2160 /// [`Self::target`] `Result`-returning validator on the same
2161 /// per-`:contratos` typed-projection axis — [`Self::target`] is the
2162 /// pre-validation validator that computes the projection *and* raises
2163 /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
2164 /// (`:wit`, payload) mismatch; this method is the post-validation
2165 /// projection every downstream consumer reaches through once the
2166 /// pre-validation gate has succeeded.
2167 ///
2168 /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
2169 ///
2170 /// Prior to this lift the "call `.target()` then `.expect(…)` with
2171 /// the same message" pattern sat inline at two production sites with
2172 /// no compile-time link between them: the
2173 /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
2174 /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
2175 /// (`c.target().expect("validated by typed_view").http_endpoint()`)
2176 /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
2177 /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
2178 /// (`c.target().expect("validated by typed_view").graph_label()`),
2179 /// each open-coding the same `.target().expect("validated by
2180 /// typed_view")` pair with the message spelled twice. A future
2181 /// vocabulary shift on the panic-message axis (a tightening from
2182 /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
2183 /// validate"` as the substrate's validator entry-point vocabulary
2184 /// sharpens, a per-consumer disambiguation, an M4 promotion of the
2185 /// panic to a `debug_assert` under a `--release` build profile) would
2186 /// have had to be threaded through both open-coded call sites in
2187 /// lockstep or one consumer would silently disagree with the peer on
2188 /// which invariant the panic message names. Same "same shape written
2189 /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
2190 /// discipline the sibling [`Self::edge_pair`] /
2191 /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
2192 /// lifts already establish on the paired composite-projection axis;
2193 /// this lift extends it onto the post-validation typed-view axis.
2194 ///
2195 /// Every future downstream consumer of the projected typed view
2196 /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
2197 /// CR materializer's per-edge admission webhook, the future
2198 /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
2199 /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
2200 /// resolver, the future `feira app graph --l7` / `--pubsub` /
2201 /// `--kv` per-shape column emitters) reaches through this one typed
2202 /// dispatch on the substrate primitive rather than an open-coded
2203 /// per-consumer `.target().expect(…)` pair with the message
2204 /// re-inlined. The invariant the accessor's panic path pins — "this
2205 /// call is only reachable after [`AplicacaoSpec::validate`] has
2206 /// succeeded on the containing spec" — is the substrate's answer to
2207 /// give exactly once, at the primitive, not once per consumer.
2208 ///
2209 /// # Panics
2210 ///
2211 /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
2212 /// would return an `Err` — i.e. if this contract's
2213 /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
2214 /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
2215 /// this accessor only from a code path that has already reached the
2216 /// containing [`AplicacaoSpec`] through a validating entry-point
2217 /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
2218 /// [`typed_view`] compose, the future M4 CR admission webhook's
2219 /// per-CR validate). Use [`Self::target`] instead on any pre-
2220 /// validation code path.
2221 ///
2222 /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
2223 #[must_use]
2224 pub fn target_projected(&self) -> WitTarget<'_> {
2225 self.target().expect(Self::PROJECTED_INVARIANT_MSG)
2226 }
2227
2228 /// Canonical panic message the [`Self::target_projected`]
2229 /// post-validation projection accessor threads through when the
2230 /// caller has violated the "call only after [`AplicacaoSpec::validate`]
2231 /// has succeeded" precondition. Lifted as a `pub const` on the
2232 /// [`WitContract`] surface so the byte-string lives in one place
2233 /// across the substrate — the [`Self::target_projected`] method
2234 /// body, the two prior production call sites' comments now naming
2235 /// the const, and every future consumer that must format-match the
2236 /// panic-message shape (a future test suite that asserts the panic-
2237 /// message byte-string across a fuzzed invalid-contract corpus,
2238 /// a future custom-panic hook in `caixa-operator` that surfaces the
2239 /// message with per-`:contratos` telemetry, the future admission
2240 /// webhook's per-CR validate-error report) reaches through the same
2241 /// canonical `&'static str`. A future rebrand on the panic-message
2242 /// axis (a tightening from `"validated by typed_view"` to `"validated
2243 /// by AplicacaoSpec::validate"` as the substrate's validator
2244 /// entry-point vocabulary sharpens once caixa-core grows a
2245 /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
2246 /// [`typed_view`]) lands at one caixa-core edit rather than a
2247 /// coordinated per-consumer sweep — same "one canonical declaration
2248 /// per axis, next to the accessor that reads it" discipline the peer
2249 /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
2250 /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
2251 /// const family already establishes on the paired per-consumer-axis
2252 /// diagnostic-scalar surface.
2253 pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
2254}
2255
2256/// Borrowed identity key for the typed-graph duplicate-`:contratos`
2257/// gate (see [`AplicacaoSpec::validate`]): every field that
2258/// distinguishes one contract from another, in declaration order
2259/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
2260/// with equal [`ContratoIdentity`]s are the same typed edge declared
2261/// twice — the graph-edge analogue of duplicate `:membros` /
2262/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
2263/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
2264/// clippy's `type_complexity` lint (and so a future axis added to
2265/// `WitContract` is one alias edit, not a coordinated rewrite of
2266/// every set instantiation).
2267pub type ContratoIdentity<'a> = (
2268 &'a str,
2269 &'a str,
2270 &'a str,
2271 Option<&'a str>,
2272 Option<&'a str>,
2273 Option<&'a str>,
2274);
2275
2276/// Typed view of a [`WitContract`]'s payload target. Each variant
2277/// carries the field its WIT shape requires; constructing a `Http`
2278/// view without an endpoint is impossible by the type system.
2279///
2280/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
2281/// instead of probing `Option<String>` fields one by one — the
2282/// "which payload field is set?" question is answered once, at
2283/// validation time.
2284#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
2285pub enum WitTarget<'a> {
2286 /// HTTP-shaped WIT world. Carries the configured request path.
2287 Http { endpoint: &'a str },
2288 /// Pub-sub-shaped WIT world. Carries the event-stream subject.
2289 ///
2290 /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
2291 /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
2292 /// `#[is_variant(name = "pubsub")]` override keeps the emitted
2293 /// method name byte-identical to the sibling
2294 /// [`WitContract::is_pubsub`] predicate (the paired shape-side
2295 /// arm-discriminator that routes through
2296 /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
2297 /// through `matches!` on the variant), so the two arm-discriminator
2298 /// axes — target-side variant-arm and shape-side ref-prefix — reach
2299 /// every downstream consumer through the same `is_pubsub()` name.
2300 #[is_variant(name = "pubsub")]
2301 PubSub { subject: &'a str },
2302 /// Key-value-shaped WIT world. Carries the slot template.
2303 Store { slot: &'a str },
2304 /// A typed capability edge with no payload selector — the WIT
2305 /// world stands on its own (rare; reserved for plain capability
2306 /// imports or M4-and-later WIT worlds we haven't shaped yet).
2307 Capability,
2308}
2309
2310impl<'a> WitTarget<'a> {
2311 /// Canonical author-facing `:contratos` payload field name for the
2312 /// HTTP-shaped arm — the `expected: &'static str` scalar the
2313 /// [`AplicacaoError::ContratoMissingTarget`] /
2314 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
2315 /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
2316 /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
2317 /// the `feira app graph` verb prints. Peer of
2318 /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
2319 /// on the payload-field-name axis; declared as a peer const next
2320 /// to the [`WitTarget::Http`] variant so a future rename on the
2321 /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
2322 /// :endpoint …)))` field lands in exactly one place, not scattered
2323 /// across the [`WitContract::target`] gate's six `expected:`
2324 /// literals, the label template, and every downstream consumer
2325 /// that prints a per-arm prefix. Same trajectory as the peer
2326 /// [`WitTarget::label`] lift (174e96a): a single source of truth
2327 /// for the arm's shape, next to the variant declaration.
2328 pub const HTTP_FIELD_NAME: &'static str = "endpoint";
2329 /// Canonical author-facing `:contratos` payload field name for the
2330 /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
2331 /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
2332 /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
2333 pub const PUBSUB_FIELD_NAME: &'static str = "subject";
2334 /// Canonical author-facing `:contratos` payload field name for the
2335 /// key/value-store-shaped arm. Peer of
2336 /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
2337 /// on the payload-field-name axis; see
2338 /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
2339 pub const STORE_FIELD_NAME: &'static str = "slot";
2340
2341 /// Canonical stable human-readable label the payload-less
2342 /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
2343 /// the byte-string every consumer that formats a payload-less
2344 /// typed capability edge as text lands on (the
2345 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
2346 /// naming which identical edge was declared twice, the future
2347 /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
2348 /// policy resolver's audit view, the operator's mesh-graph audit).
2349 /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
2350 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
2351 /// author-facing label-scalar consts — the same
2352 /// "one canonical declaration per arm, next to the variant, so a
2353 /// future rename lands in one place" discipline extended to the
2354 /// payload-less arm. Until this lift landed the byte-string sat
2355 /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
2356 /// match arm, once in the pin test asserting the label's
2357 /// [`WitTarget::Capability`] output — with no compile-time link
2358 /// between the two: a rebrand on either side (an operator-facing
2359 /// vocabulary shift, a per-consumer disambiguation like
2360 /// `"(capability — no payload; typed edge only)"`) would silently
2361 /// desynchronize until a downstream consumer surfaced the drift at
2362 /// runtime.
2363 pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
2364
2365 /// Canonical `expected:` scalar the
2366 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
2367 /// through for the payload-less [`WitTarget::Capability`] arm — the
2368 /// byte-string authors read as "this WIT world's shape is not one
2369 /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
2370 /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
2371 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2372 /// [`Self::STORE_FIELD_NAME`] consts on the
2373 /// `ContratoWrongTarget::expected` axis — the fourth arm of the
2374 /// same "which payload field name goes in the diagnostic" dispatch
2375 /// the three payload-arm consts cover, extended to the payload-less
2376 /// arm. Until this lift landed the byte-string sat twice — once
2377 /// inline in the [`Self::target`] Capability-arm rejection at the
2378 /// production dispatch, once in the pin test asserting the
2379 /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
2380 /// no compile-time link between the two: a rebrand on either side
2381 /// (an author-facing vocabulary shift to `"capability"` /
2382 /// `"(none)"` / `"no-payload"` as the WIT registry's shape
2383 /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
2384 /// [`WitTarget::Capability`] into per-shape peers) would silently
2385 /// desynchronize until a downstream consumer surfaced the drift at
2386 /// runtime. Same "one canonical declaration per arm, next to the
2387 /// variant, so a future rename lands in one place" discipline the
2388 /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
2389 /// established for the payload-less arm's human-readable label
2390 /// axis; this lift extends it onto the peer diagnostic-scalar axis
2391 /// so both halves of the "how does the Capability arm surface at
2392 /// its two consumer axes (human-readable label, wrong-target
2393 /// diagnostic)" pipeline route through peer consts declared next
2394 /// to the variant.
2395 ///
2396 /// Pairwise-distinctness against the three payload-arm scalars
2397 /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2398 /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
2399 /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
2400 /// test — the 4-way closure of the 3-way
2401 /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
2402 /// the `ContratoWrongTarget::expected` axis, matching the peer
2403 /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
2404 /// scalar-value distinctness discipline the sibling M3 typed-enum
2405 /// discriminator axis already carries.
2406 pub const CAPABILITY_EXPECTED: &'static str = "none";
2407
2408 /// Canonical `feira app graph` per-`:contratos`-edge payload-column
2409 /// byte-string the payload-less [`WitTarget::Capability`] arm renders
2410 /// as under [`Self::graph_label`] — the sibling
2411 /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
2412 /// payload-column axis (the graph verb spells payload-less as
2413 /// `(capability-only)`, distinct from the duplicate-`:contratos`
2414 /// diagnostic's `(capability — no payload)` on the human-readable
2415 /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
2416 /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
2417 /// family — extends the "one canonical declaration per arm, next to
2418 /// the variant, so a future rename lands in one place" discipline
2419 /// onto the third payload-less-arm consumer axis (`feira app graph`
2420 /// payload column, joining the [`Self::label`] duplicate-`:contratos`
2421 /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
2422 /// axis).
2423 ///
2424 /// Until this lift landed the byte-string sat inline in
2425 /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
2426 /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
2427 /// `"(capability-only)".to_string()` literal, with no compile-time link
2428 /// back to the [`WitTarget::Capability`] variant declaration nor to
2429 /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
2430 /// peer consts already carrying the "one canonical declaration per
2431 /// payload-less-arm consumer axis" discipline. A rebrand on either
2432 /// side (the graph verb's operator-facing vocabulary tightening from
2433 /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
2434 /// the WIT registry vocabulary sharpens, an M4 split of
2435 /// [`Self::Capability`] into per-shape peers) would silently
2436 /// desynchronize the graph-verb byte-string from the paired
2437 /// per-arm-adjacent const and land two spellings of the same axis in
2438 /// two spots.
2439 pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
2440
2441 /// The `(author-facing field name, payload)` pair this typed target
2442 /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
2443 /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
2444 /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
2445 /// [`Self::Store`], `None` for the payload-less
2446 /// [`Self::Capability`] arm.
2447 ///
2448 /// Lifted as the single 4-arm dispatch that both [`Self::label`]
2449 /// (formats `":{field} {payload:?}"` on `Some`, falls to
2450 /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
2451 /// (returns the first component) route through, so a future
2452 /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
2453 /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
2454 /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
2455 /// exactly one new match-arm here (a compile-time exhaustiveness
2456 /// error otherwise), not a coordinated three-way rewrite of the
2457 /// prior [`Self::label`] template + [`Self::field_name`] dispatch
2458 /// + every downstream consumer that reaches for the pair.
2459 ///
2460 /// Until this lift landed the three payload arms sat in
2461 /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
2462 /// invocations (one per variant, each hand-quoting the paired
2463 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
2464 /// [`Self::STORE_FIELD_NAME`] const) — the canonical
2465 /// "same shape, written N times" duplication THEORY.md §I.3.5
2466 /// ("Generation first, composition second, hand-authoring last;
2467 /// the duplication budget is zero") promotes to a build-time
2468 /// concern, with each per-arm site paired to its own const with no
2469 /// compile-time link between the format template and the arm's
2470 /// payload extraction.
2471 #[must_use]
2472 pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
2473 match *self {
2474 WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
2475 WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
2476 WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
2477 WitTarget::Capability => None,
2478 }
2479 }
2480
2481 /// The canonical author-facing `:contratos` payload field name
2482 /// this typed target arm carries (`Http` → `Some("endpoint")`,
2483 /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
2484 /// `None` for the payload-less `Capability` arm.
2485 ///
2486 /// Routes through [`Self::payload_pair`] — the single 4-arm
2487 /// dispatch [`Self::label`] also reads — so a future variant
2488 /// addition is one match-arm edit at [`Self::payload_pair`], not a
2489 /// per-consumer rewrite. Same "exhaustive-match at one canonical
2490 /// dispatch, thin projections at each consumer" trajectory the
2491 /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
2492 /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
2493 #[must_use]
2494 pub const fn field_name(&self) -> Option<&'static str> {
2495 match self.payload_pair() {
2496 Some((f, _)) => Some(f),
2497 None => None,
2498 }
2499 }
2500
2501 /// The underlying scalar the payload-carrying arm carries — the
2502 /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
2503 /// subject ([`Self::PubSub`] `:subject`), or slot template
2504 /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
2505 /// `&'a str` storage — or `None` on the payload-less
2506 /// [`Self::Capability`] arm.
2507 ///
2508 /// Thin projection onto the single 4-arm [`Self::payload_pair`]
2509 /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
2510 /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
2511 /// the paired sub-selector axis. Both per-half accessors read from
2512 /// one authoritative match, so a future [`WitTarget`] variant
2513 /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
2514 /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
2515 /// on [`Self::payload_pair`] and both per-half projections + every
2516 /// downstream consumer picks the new arm up by construction — no
2517 /// coordinated N-way rewrite across the paired accessor dispatches,
2518 /// the [`Self::label`] / [`Self::graph_label`] format templates,
2519 /// and every future WIT-registry-shaped consumer.
2520 ///
2521 /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
2522 /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
2523 /// controller `spec.ref.<field>` axis — same "one paired dispatch,
2524 /// both per-half projections as thin readers, every downstream
2525 /// consumer through the same match" discipline extended onto the
2526 /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
2527 /// gap between the two paired-dispatch surfaces: the peer
2528 /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
2529 /// the first-component projection until this lift; the second-
2530 /// component sibling now sits alongside so both halves reach every
2531 /// future consumer through the same substrate-primitive dispatch.
2532 ///
2533 /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
2534 #[must_use]
2535 pub const fn payload(&self) -> Option<&'a str> {
2536 match self.payload_pair() {
2537 Some((_, p)) => Some(p),
2538 None => None,
2539 }
2540 }
2541
2542 /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
2543 /// consumer that fans on the L7-HTTP-shaped payload keys off —
2544 /// returns the [`Self::Http`]-arm's author-declared request path
2545 /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
2546 /// projected target is [`Self::Http { endpoint }`], `None` on the
2547 /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
2548 /// [`Self::Capability`], each of which carries no HTTP endpoint by
2549 /// definition).
2550 ///
2551 /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
2552 /// `path:` rule payload every substrate-side L7-introspecting
2553 /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
2554 /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
2555 /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
2556 /// on the L7 introspection branch; every peer WIT shape stays
2557 /// L4-only because Cilium can't introspect NATS / key-value / plain
2558 /// capability edges), and every future L7-introspecting consumer
2559 /// of the projected target's HTTP endpoint (the future M4
2560 /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
2561 /// materializer's per-edge L7 admission-webhook overlay, the
2562 /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
2563 /// path bucket-key resolver, the future per-`:contratos`-edge
2564 /// mTLS-required overlay's HTTP-shape scope filter, the future
2565 /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
2566 /// through the same typed dispatch.
2567 ///
2568 /// Prior to this lift the sole production consumer of the projected-
2569 /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
2570 /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
2571 /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
2572 /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
2573 /// }`) — reached the payload through a raw per-arm `if let` pattern-
2574 /// match that expressed no compile-time link back to the substrate
2575 /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
2576 /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
2577 /// scalar accessor on the peer per-`:contratos` raw-field axis but
2578 /// with no post-projection peer on the typed-view surface. A future
2579 /// [`WitTarget`] variant addition that splits [`Self::Http`] into
2580 /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
2581 /// gRPC-shaped worlds per this enum's own docstring at
2582 /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
2583 /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
2584 /// would have had to be threaded through the caixa-mesh L7 emit
2585 /// branch's raw `if let` in lockstep — either coalescing the two
2586 /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
2587 /// emit path per-arm — with no substrate-primitive dispatch making
2588 /// the "which arms count as L7-HTTP-shaped for path-emission
2589 /// purposes" question the substrate's answer to give. Lifting the
2590 /// resolution to a typed method on the substrate primitive means
2591 /// every downstream L7-HTTP-facing consumer of the Aplicacao's
2592 /// projected-target HTTP endpoint reaches for exactly one typed
2593 /// dispatch — the resolver's accept-set migrates as a unit on any
2594 /// future arm-family widening, and the caixa-mesh L7 emit branch
2595 /// reads through the same substrate primitive.
2596 ///
2597 /// Peer of the sibling pre-projection [`WitContract::endpoint`]
2598 /// (7020470) `Option<&str>` scalar accessor on the raw
2599 /// `:contratos :endpoint` field-access axis — same "one typed
2600 /// dispatch on the substrate primitive, thin projections at each
2601 /// consumer" discipline extended onto the peer post-projection typed-
2602 /// view surface (the [`WitContract::endpoint`] pre-projection
2603 /// accessor returns `Some` for any author-declared `:endpoint`
2604 /// value regardless of the paired `:wit` world's HTTP-shape
2605 /// classification — the raw slot before validation crosses it —
2606 /// while this post-projection [`Self::http_endpoint`] accessor
2607 /// returns `Some` iff the target has been projected onto the
2608 /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
2609 /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
2610 /// coherence; the two accessors close the pre-projection /
2611 /// post-projection pair on the HTTP-endpoint axis). Sibling of the
2612 /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
2613 /// the three payload-carrying arms) — extends the per-arm
2614 /// projection family onto the [`Self::Http`] specialization axis
2615 /// that the pan-arm accessor's shape blends into a single arm-
2616 /// agnostic view; paired with [`Self::pubsub_subject`] /
2617 /// [`Self::store_slot`] on the sibling per-arm axes so every
2618 /// per-payload-arm shape carries a named post-projection accessor
2619 /// on the same shape as `http_endpoint`, closing the per-arm-shape
2620 /// accept-set the substrate primitive owns.
2621 #[must_use]
2622 pub const fn http_endpoint(&self) -> Option<&'a str> {
2623 match *self {
2624 WitTarget::Http { endpoint } => Some(endpoint),
2625 WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2626 }
2627 }
2628
2629 /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2630 /// consumer that fans on the pub-sub-shaped payload keys off —
2631 /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2632 /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2633 /// the projected target is [`Self::PubSub { subject }`], `None` on
2634 /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2635 /// [`Self::Capability`], each of which carries no NATS-shaped
2636 /// subject by definition).
2637 ///
2638 /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2639 /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2640 /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2641 /// CR materializer's `spec.subjects[]` projection, the future
2642 /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2643 /// bucket-key resolver, the future `feira app graph --pubsub`
2644 /// per-Aplicacao subject column, any future substrate-lifted
2645 /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2646 /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2647 /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2648 /// future pub-sub-shape consumer reaches for the same typed
2649 /// dispatch this accessor exposes so the "which arm carries the
2650 /// subject scalar?" answer lives at one caixa-core edit rather
2651 /// than open-coded across per-consumer `if let WitTarget::PubSub
2652 /// { subject } = c.target()…` pattern-matches.
2653 ///
2654 /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2655 /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2656 /// the pre-projection [`WitContract::subject`] scalar accessor on
2657 /// the raw `:contratos :subject` field-access axis — same "one
2658 /// typed dispatch on the substrate primitive, thin projections at
2659 /// each consumer" discipline extended onto the per-arm pub-sub
2660 /// post-projection axis. The pre-projection accessor returns
2661 /// `Some` for any author-declared `:subject` value regardless of
2662 /// the paired `:wit` world's pub-sub-shape classification (the raw
2663 /// slot before validation crosses it); this post-projection
2664 /// accessor returns `Some` iff the target has been projected onto
2665 /// the [`Self::PubSub`] arm, i.e. only after the
2666 /// [`WitContract::target`] gate has admitted the
2667 /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2668 /// the pre-/post-projection pair on the pub-sub-subject axis to
2669 /// match the pair the [`WitContract::endpoint`] +
2670 /// [`Self::http_endpoint`] surfaces already close on the peer
2671 /// HTTP-endpoint axis.
2672 ///
2673 /// Sibling of the unified pan-arm [`Self::payload`]
2674 /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2675 /// extends the per-arm projection family onto the [`Self::PubSub`]
2676 /// specialization axis that the pan-arm accessor's shape blends
2677 /// into a single arm-agnostic view; the pair
2678 /// (`pubsub_subject`, `store_slot`) closes the trio
2679 /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2680 /// payload arm now carries its own per-arm-shape post-projection
2681 /// accessor.
2682 #[must_use]
2683 pub const fn pubsub_subject(&self) -> Option<&'a str> {
2684 match *self {
2685 WitTarget::PubSub { subject } => Some(subject),
2686 WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2687 }
2688 }
2689
2690 /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2691 /// every consumer that fans on the store-shaped payload keys off —
2692 /// returns the [`Self::Store`]-arm's author-declared slot template
2693 /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2694 /// projected target is [`Self::Store { slot }`], `None` on the
2695 /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2696 /// [`Self::Capability`], each of which carries no
2697 /// key/value-store slot by definition).
2698 ///
2699 /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2700 /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2701 /// every future substrate-side store-introspecting per-`(:de,
2702 /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2703 /// namespace / prefix reconciler's per-slot projection, the future
2704 /// per-store-backend routing overlay's slot-shape gate, the future
2705 /// `feira app graph --store` per-Aplicacao slot column, any future
2706 /// substrate-lifted store-shape emitter that reads a projected
2707 /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2708 /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2709 /// Every future store-shape consumer reaches for the same typed
2710 /// dispatch this accessor exposes so the "which arm carries the
2711 /// slot scalar?" answer lives at one caixa-core edit rather than
2712 /// open-coded across per-consumer
2713 /// `if let WitTarget::Store { slot } = c.target()…`
2714 /// pattern-matches.
2715 ///
2716 /// Peer of the sibling [`Self::http_endpoint`] +
2717 /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2718 /// axes and of the pre-projection [`WitContract::slot`] scalar
2719 /// accessor on the raw `:contratos :slot` field-access axis — same
2720 /// "one typed dispatch on the substrate primitive, thin projections
2721 /// at each consumer" discipline extended onto the per-arm store
2722 /// post-projection axis. Closes the pre-/post-projection pair on
2723 /// the store-slot axis to match the pairs the
2724 /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2725 /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2726 /// already close on the peer HTTP-endpoint and pub-sub-subject
2727 /// axes; the substrate-side pre-/post-projection accessor family
2728 /// now spans all three payload arms as a matched trio, so any
2729 /// future arm-shape widening (a `Rest`/`Grpc` split of
2730 /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2731 /// lands one accessor without threading through the sibling
2732 /// pre-projection or the peer per-arm post-projection surfaces a
2733 /// compile-time exhaustiveness error at the substrate primitive,
2734 /// not a silent per-consumer split at renderer emit time.
2735 ///
2736 /// Sibling of the unified pan-arm [`Self::payload`]
2737 /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2738 /// closes the per-arm projection family onto the [`Self::Store`]
2739 /// specialization axis that the pan-arm accessor's shape blends
2740 /// into a single arm-agnostic view. The trio
2741 /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2742 /// pan-arm accept-set on every payload-carrying arm: exactly one
2743 /// per-arm accessor returns `Some(payload)` and the two peers
2744 /// return `None`, and every payload-less [`Self::Capability`]
2745 /// input returns `None` on all three — the partition the sibling
2746 /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2747 /// pin locks in load-bearing.
2748 #[must_use]
2749 pub const fn store_slot(&self) -> Option<&'a str> {
2750 match *self {
2751 WitTarget::Store { slot } => Some(slot),
2752 WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2753 }
2754 }
2755
2756 /// Render this typed target as a stable human-readable label
2757 /// (`:endpoint "/charge"`, `:subject "events.x"`,
2758 /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2759 /// the WIT world is a pure capability edge).
2760 ///
2761 /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2762 /// gate so the diagnostic names *which* identical edge was
2763 /// declared twice (not just which `(de, para, wit)` triple).
2764 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2765 /// on the payload-carrying arms (`Some((field, payload)) →
2766 /// format!(":{field} {payload:?}")`) and through the lifted
2767 /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2768 /// [`Self::Capability`] arm — so a future variant addition (the
2769 /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2770 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2771 /// `Queue`-shaped peer) becomes a single new match-arm on
2772 /// [`Self::payload_pair`] rather than a rewrite of this template
2773 /// (and every downstream consumer that reaches for the label
2774 /// shape: the per-edge policy resolver in M4, the `feira app
2775 /// graph` view, the operator's mesh-graph audit). Until this
2776 /// lift landed the three payload arms carried three near-identical
2777 /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2778 /// [`Self::Capability`] arm carried the payload-less byte-string
2779 /// twice (once inline here, once in the pin test) — closing the
2780 /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2781 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2782 /// / 4a1e490) peer-const lifts already established for the
2783 /// payload-carrying arms.
2784 #[must_use]
2785 pub fn label(&self) -> String {
2786 match self.payload_pair() {
2787 Some((field, payload)) => format!(":{field} {payload:?}"),
2788 None => Self::CAPABILITY_LABEL.to_string(),
2789 }
2790 }
2791
2792 /// Render this typed target as the `feira app graph` per-`:contratos`
2793 /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2794 /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2795 /// payload-less arm).
2796 ///
2797 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2798 /// on the payload-carrying arms (`Some((field, payload)) →
2799 /// format!("{field}={payload}")`) and through the lifted
2800 /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2801 /// [`Self::Capability`] arm — so a future variant addition
2802 /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2803 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2804 /// `Queue`-shaped peer) becomes one match-arm edit at
2805 /// [`Self::payload_pair`], propagating through this graph-verb
2806 /// projection at zero call-site cost, sibling to the peer
2807 /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2808 /// same 4-arm dispatch.
2809 ///
2810 /// Until this lift landed the [`caixa-feira`]
2811 /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2812 /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2813 /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2814 /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2815 /// `format!("{}={endpoint}", ...)` template and hard-coding
2816 /// `"(capability-only)"` as a fifth payload-less scalar with no link
2817 /// back to the paired [`WitTarget::Capability`] variant declaration.
2818 /// A future variant addition would have had to be threaded through
2819 /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2820 /// verb's inline match in lockstep or the two projections would
2821 /// silently disagree on the arm-set the graph verb prints — the
2822 /// duplicate-`:contratos` diagnostic reading one shape while the
2823 /// graph verb's payload column silently dropped the new arm to
2824 /// `(capability-only)`. Lifting the graph-verb projection onto the
2825 /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2826 /// the axis: both projections migrate as a unit.
2827 ///
2828 /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2829 /// quoting) shape is graph-verb-canonical — distinct from the
2830 /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2831 /// duplicate-`:contratos` diagnostic seeds (see
2832 /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2833 /// on the payload-less axis for the paired distinction).
2834 #[must_use]
2835 pub fn graph_label(&self) -> String {
2836 match self.payload_pair() {
2837 Some((field, payload)) => format!("{field}={payload}"),
2838 None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2839 }
2840 }
2841}
2842
2843/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2844/// pretty-printed byte-string every consumer that formats a typed
2845/// payload target as user-facing text lands on (the
2846/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2847/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2848/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2849/// graph` per-`:contratos`-edge payload column that reaches the graph
2850/// verb through `format!("{target}")`, the future M4 per-edge policy
2851/// resolver's per-edge audit-log line, the operator's mesh-graph
2852/// per-edge inspection view) reaches for the same lifted
2853/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2854/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2855/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2856/// routes through — extending the three-path-convergence
2857/// (`Debug` for structural inspection, `Display` for user-facing text,
2858/// per-arm typed accessor for the canonical byte-string) discipline the
2859/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2860/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2861/// onto the fourth (and only remaining) typed-shape-discriminator axis
2862/// on the caixa surface.
2863///
2864/// Pre-lift the two paths were structurally independent — every consumer
2865/// reaching for a payload byte-string past the [`WitTarget::label`]
2866/// helper had to pick between three paths ([`WitTarget::label`],
2867/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2868/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2869/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2870/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2871/// that reached for `format!("{target}")` — the canonical shape every
2872/// user-facing pretty-print site on the sibling typed-enum axes already
2873/// uses — would silently land on the `Debug` derive's structural output
2874/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2875/// than the `label()` helper's stable byte-string (`:endpoint
2876/// "/charge"` — the author-facing `:contratos` keyword form) the
2877/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2878/// already threads through. The two spellings would diverge silently in
2879/// every downstream diagnostic / graph / audit line reached through
2880/// `format!` rather than through the `label()` helper. Routing
2881/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2882/// path: every `format!("{v}")` call reaches the same
2883/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2884/// and the duplicate-`:contratos` gate already route through, so a
2885/// future variant addition (the M4-and-later per-edge WIT registry may
2886/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2887/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2888/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2889/// match — rather than fanning out through hand-rolled per-arm
2890/// [`std::fmt::Display`] arms.
2891///
2892/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2893/// is the typed view returned by [`WitContract::target`], not a
2894/// closed-set discriminator enum with a gen-platform Discriminant
2895/// registration, so the `Debug` derive's structural output (which every
2896/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2897/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2898/// shape for structural inspection; `Display` (via `label`) reveals the
2899/// stable author-facing payload projection.
2900///
2901/// Pin tests
2902/// [`tests::wit_target_display_routes_through_label_helper`] and
2903/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2904/// assert the two paths agree byte-for-byte on every variant, so a
2905/// future variant addition or `label()` reimplementation that hand-rolls
2906/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2907/// build error visible at caixa-core test time, not a silent
2908/// per-consumer dispatch miss at diagnostic / audit / graph time.
2909impl std::fmt::Display for WitTarget<'_> {
2910 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2911 f.write_str(&self.label())
2912 }
2913}
2914
2915// ── one Aplicacao member ─────────────────────────────────────────────
2916
2917/// A Servico participating in the Aplicacao. Same shape as
2918/// `crate::supervisor::ChildSpec` but without a restart policy —
2919/// supervision is per-Servico (each member has its own
2920/// `:supervisor`), the Aplicacao orchestrates *placement*.
2921#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2922#[serde(rename_all = "camelCase")]
2923pub struct Membro {
2924 /// Member caixa's `:nome`. Resolves through the same dep
2925 /// resolution path as `crate::dep::Dep`.
2926 pub caixa: String,
2927
2928 /// Semver constraint.
2929 pub versao: String,
2930}
2931
2932impl Membro {
2933 /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2934 /// accessor every consumer that reads the member's Servico identity
2935 /// keys off — returns the author-declared `:membros :caixa`
2936 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2937 /// own [`String`] storage.
2938 ///
2939 /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2940 /// participating in the Aplicacao — validated by
2941 /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2942 /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2943 /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2944 /// [`validate_no_self_membership`]) — and every downstream consumer
2945 /// that fans on the member's identity keys off this scalar (the
2946 /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2947 /// lookup, the per-`:membros` duplicate gate's dedup key, the
2948 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2949 /// identity, the self-membership gate, the
2950 /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2951 /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2952 /// CR materializer's per-member resolver).
2953 ///
2954 /// Prior to this lift the `.caixa` byte-string was read inline at
2955 /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2956 /// set collector at
2957 /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2958 /// [`validate_membros`] validation-side member-caixa gate at
2959 /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2960 /// per-member duplicate-gate dedup key at
2961 /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2962 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2963 /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2964 /// [`validate_no_self_membership`] self-loop gate at
2965 /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2966 /// expressed no compile-time link back to the typed slot. Every
2967 /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2968 /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2969 /// `name:` axis, so a future extension of the `:membros :caixa`
2970 /// axis to a richer author surface — a per-cluster alias table the
2971 /// operator pins through a future `:placement`-scoped slot, a
2972 /// namespace-qualified rewrite the M4 CR materializer applies
2973 /// per-CR, a per-member overlay from the future `:membros
2974 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2975 /// acknowledges — would have had to be threaded through every
2976 /// open-coded copy in lockstep or one consumer would silently
2977 /// disagree with the peers on which caixa a given member resolves
2978 /// to. A member-set lookup that treated the name as `"cart"` while
2979 /// the peer adjacency map treated it as `"tenant-a/cart"` would
2980 /// silently split the `:contratos` membership-lookup diagnostic from
2981 /// the cycle-detector's node identity — a two-consumer split at the
2982 /// validator far from the source `caixa.lisp` with no field naming
2983 /// the identity-drift root cause. Lifting the resolution rule to a
2984 /// typed method on the substrate primitive means every downstream
2985 /// consumer of the Aplicacao's per-`:membros` identity surface
2986 /// reaches for exactly one typed dispatch — the resolver's
2987 /// accept-set migrates as a unit on any future axis addition.
2988 ///
2989 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2990 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2991 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2992 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2993 /// destination-Servico scalar accessors — same "one typed dispatch
2994 /// on the substrate primitive, thin projections at each consumer"
2995 /// discipline extended onto the per-`:membros` member-caixa `:nome`
2996 /// byte-string axis. Named `nome()` to match the tatara-lisp
2997 /// author-surface term the field's docstring already reaches for
2998 /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2999 /// [`crate::dep::Dep::nome`] field-name discipline the substrate
3000 /// already carries — the accessor's name maps directly onto the
3001 /// canonical caixa-identity vocabulary rather than shadowing the
3002 /// field's storage-side `caixa` label.
3003 #[must_use]
3004 pub const fn nome(&self) -> &str {
3005 self.caixa.as_str()
3006 }
3007
3008 /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
3009 /// requirement scalar accessor every consumer that reads the
3010 /// member's version pin keys off — returns the author-declared
3011 /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
3012 /// from the typed slot's own [`String`] storage.
3013 ///
3014 /// The `:membros :versao` slot carries the Cargo-shaped semver
3015 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
3016 /// pins which release of the member-caixa the Aplicacao composes
3017 /// against — the same requirement grammar the peer `:deps :versao`
3018 /// / `:children :versao` axes carry, resolved through the shared
3019 /// [`crate::render::require_valid_versao_requirement`] cascade and
3020 /// the shared [`crate::version::parse_requirement`] parser. Every
3021 /// downstream consumer that fans on the member's version pin keys
3022 /// off this scalar (the [`validate_membros`] per-member requirement
3023 /// gate at `require_valid_versao_requirement(m.versao_requirement(),
3024 /// …)`, the [`feira app graph`] per-member `println!(" - {} {}",
3025 /// m.nome(), m.versao_requirement())` line, every future per-cluster
3026 /// version-lock overlay the operator pins through a future
3027 /// `:placement`-scoped slot, the future
3028 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
3029 /// version resolver, the future `feira app deploy` pipeline's
3030 /// per-member lacre BLAKE3-closure lookup).
3031 ///
3032 /// Prior to this lift the `.versao` byte-string was accessed inline
3033 /// at two `&str`-shaped sites — the [`validate_membros`]
3034 /// requirement-gate call `require_valid_versao_requirement(&m.versao,
3035 /// …)` and the `feira app graph` per-member printer's `println!(
3036 /// " - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
3037 /// prior to this lift) — two open-coded field-accesses that expressed
3038 /// no compile-time link back to the typed slot. A future extension of
3039 /// the `:membros :versao` axis to a richer author surface (a
3040 /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
3041 /// flow, a lacre-projected concrete-version rewrite the operator
3042 /// materializes at CR-admission time, a future `:membros :versao-lock`
3043 /// per-cluster override slot) would have had to be threaded through
3044 /// every open-coded copy in lockstep or one consumer would silently
3045 /// disagree with the peers on which release constraint a given
3046 /// member resolves to. Lifting the resolution rule to a typed method
3047 /// on the substrate primitive means every downstream requirement-
3048 /// facing consumer reaches for exactly one typed dispatch — the
3049 /// resolver's accept-set migrates as a unit on any future axis
3050 /// addition.
3051 ///
3052 /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
3053 /// member-caixa `:nome` scalar accessor — the pair
3054 /// `(nome(), versao_requirement())` jointly projects the
3055 /// `(caixa, versao)` field pair every renderer that fans on
3056 /// per-member identity + version pin keys off, closing the last
3057 /// unlifted per-`:membros` scalar axis so every downstream
3058 /// per-`:membros` reader now routes through a typed dispatch on the
3059 /// substrate primitive. Named `versao_requirement()` rather than
3060 /// `versao()` because the field's storage-side `.versao` label is
3061 /// already the author-surface term (`:versao`); the accessor's name
3062 /// carries the semantic role — the semver *requirement* string the
3063 /// shared [`crate::version::parse_requirement`] entry-point consumes
3064 /// — so a raw field access and a typed dispatch read differently at
3065 /// every consumer site.
3066 ///
3067 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
3068 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
3069 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
3070 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
3071 /// destination-Servico scalar accessors — same "one typed dispatch
3072 /// on the substrate primitive, thin projections at each consumer"
3073 /// discipline extended onto the per-`:membros` member-`:versao`
3074 /// semver-requirement byte-string axis.
3075 #[must_use]
3076 pub const fn versao_requirement(&self) -> &str {
3077 self.versao.as_str()
3078 }
3079}
3080
3081// ── mesh-level policies ──────────────────────────────────────────────
3082
3083/// Mesh policies that apply to every `:contratos` edge unless
3084/// overridden per-edge in M4. V0 is a single global policy block.
3085#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3086#[serde(rename_all = "camelCase")]
3087pub struct MeshPolicy {
3088 /// Per-call timeout. Authored as a duration string (`"30s"`).
3089 #[serde(
3090 default,
3091 skip_serializing_if = "Option::is_none",
3092 with = "supervisor::duration_codec"
3093 )]
3094 pub timeout: Option<Duration>,
3095
3096 /// Number of retries on transient failure. None = no retries.
3097 #[serde(default, skip_serializing_if = "Option::is_none")]
3098 pub retries: Option<u32>,
3099
3100 /// Circuit breaker config. Trips after N failures within W
3101 /// duration; closes after a cooldown.
3102 #[serde(default, skip_serializing_if = "Option::is_none")]
3103 pub circuit_breaker: Option<CircuitBreaker>,
3104
3105 /// Whether mTLS is required for every contrato. Default: true
3106 /// (sandboxing-by-default; explicit opt-out only).
3107 #[serde(default, skip_serializing_if = "Option::is_none")]
3108 pub mtls_required: Option<bool>,
3109
3110 /// Token-bucket rate limit. Authored as `"100/s"` or
3111 /// `"5000/m"`; stored as `(rate, window)`.
3112 #[serde(
3113 default,
3114 skip_serializing_if = "Option::is_none",
3115 with = "rate_limit_codec"
3116 )]
3117 pub rate_limit: Option<RateLimit>,
3118}
3119
3120/// Route the derived-style [`Default`] impl on [`MeshPolicy`] through
3121/// the substrate-canonical [`MeshPolicy::empty`] `pub const fn`
3122/// constructor rather than the derive-generated per-field
3123/// `<Option<_> as Default>::default` cascade — one source of truth for
3124/// the "canonical unset per-`:politicas` slot" shape across the two
3125/// paths every downstream consumer already reaches through (the
3126/// derived-until-now [`Default::default`] the `..Default::default()`
3127/// struct-update-syntax on every one-axis-under-test fixture in this
3128/// crate's test module rests on, and the `pub const fn`
3129/// [`MeshPolicy::empty`] constructor every `const`-context consumer
3130/// reaches through).
3131///
3132/// Prior to this fold the two paths were byte-equal by *coincidence*
3133/// under the pinning test
3134/// [`tests::mesh_policy_empty_byte_equals_default`] rather than
3135/// byte-equal by *construction* — the derive-generated
3136/// [`Default::default`] resolved each `Option<_>` field through its
3137/// own `<Option<_> as Default>::default` (which returns `None`) and
3138/// the lifted `pub const fn` [`MeshPolicy::empty`] named the same five
3139/// `None` arms verbatim in its struct-literal. Two hand-authored (or
3140/// derive-authored) sources of the same "canonical unset baseline"
3141/// shape on the same primitive is exactly the substrate-canonical-
3142/// source-of-truth duplication the [`crate::LimitsSpec::empty`]
3143/// (9739971) / [`MeshPolicy::empty`] (6df969b) /
3144/// [`crate::BehaviorSpec::empty`] (f9b18e3) lifts closed on the
3145/// forward `const`-context path — extending the same discipline onto
3146/// the paired [`Default`] impl means every consumer of the derived-
3147/// until-now [`Default::default`] surface (every `..Default::default()`
3148/// struct-update-syntax fixture in this crate's test module — the
3149/// five per-axis-only pins at [`tests::mesh_policy_with_only_timeout_is_not_empty`],
3150/// [`tests::mesh_policy_with_only_retries_is_not_empty`],
3151/// [`tests::mesh_policy_with_only_circuit_breaker_is_not_empty`],
3152/// [`tests::mesh_policy_with_only_mtls_required_is_not_empty`],
3153/// [`tests::mesh_policy_with_only_rate_limit_is_not_empty`] — and the
3154/// entry pin at [`tests::mesh_policy_default_is_empty`], the future
3155/// M4 per-edge `:politicas` overlay CR materializer's admission-time
3156/// default-overlay-emit gate, every future `..Default::default()`
3157/// struct-update-syntax fixture-builder arm) also routes through the
3158/// substrate primitive's single source of truth.
3159///
3160/// A future extension of the `:politicas` axis set (a per-edge
3161/// `:politicas` overlay the M4 roadmap grows once per-`:contratos`-
3162/// edge overrides land, a sixth `:politicas` sub-slot the roadmap
3163/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3164/// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
3165/// reaches this impl's return value through exactly one edit on
3166/// [`MeshPolicy::empty`] — the derived path could silently disagree
3167/// with the constructor's shape on any new field whose
3168/// `Default::default` is not `None` (a future non-`Option<_>` field
3169/// with a non-`Default::default`-equivalent baseline, a `Vec<_>` field
3170/// defaulting to an empty vector, an enum arm-carrying field with a
3171/// non-`Default::default` canonical unset arm), while this delegated
3172/// impl reaches the constructor directly and picks up every future
3173/// extension by construction.
3174///
3175/// Direct peer of [`crate::LimitsSpec`]'s
3176/// [`Default`]-through-[`crate::LimitsSpec::empty`] fold (abd52c2) on
3177/// the M2 `:limits` typed slot — same "one source of truth for the
3178/// canonical unset baseline" discipline extended onto the M3
3179/// `:politicas` typed slot. The sibling [`crate::BehaviorSpec`] impl
3180/// on the M2 `:behavior` slot is the third and last established
3181/// candidate for the same delegation fold once the per-slot peer pin
3182/// on this axis lands in a future run. Pinned load-bearing by
3183/// [`tests::mesh_policy_default_routes_through_empty_ctor`]
3184/// (byte-parity pin against [`MeshPolicy::empty`] under `PartialEq`,
3185/// sharpening the pre-existing
3186/// [`tests::mesh_policy_empty_byte_equals_default`] pin from a "two
3187/// paths byte-equal by coincidence" invariant into a "two paths
3188/// byte-equal by construction — one delegates to the other" invariant)
3189/// and by [`tests::mesh_policy_empty_validates_ok`] (the canonical
3190/// unset baseline must pass [`MeshPolicy::validate`] — every per-axis
3191/// value-shape gate is `if let Some(_)` guarded and every cross-axis
3192/// arm on [`MeshPolicy::first_cross_axis_violation`] is a
3193/// `let (Some(_), Some(_))` pattern, so an all-`None` input
3194/// structurally short-circuits every arm; the pin makes the invariant
3195/// load-bearing so a future extension that adds a non-`Option`-guarded
3196/// gate to [`MeshPolicy::validate`] trips at caixa-core test time
3197/// rather than at a downstream consumer that composed
3198/// [`MeshPolicy::default`]/[`MeshPolicy::empty`] with
3199/// [`MeshPolicy::validate`] as its "no-op axis short-circuit").
3200impl Default for MeshPolicy {
3201 #[inline]
3202 fn default() -> Self {
3203 Self::empty()
3204 }
3205}
3206
3207impl MeshPolicy {
3208 /// Substrate-canonical `const`-context peer of the derived
3209 /// [`Default::default`] on [`MeshPolicy`] — returns the fully-empty
3210 /// per-`:politicas` slot (every one of the five `Option<_>`-carrying
3211 /// per-axis fields set to `None`), materializable at `const`-eval
3212 /// time.
3213 ///
3214 /// Named `empty()` (not `default()` / `new()`) to match the sibling
3215 /// `is_empty()` predicate on the same primitive: the pair
3216 /// (`empty()` / `is_empty()`) forms the round-trip discipline
3217 /// `MeshPolicy::empty().is_empty() == true` the pin
3218 /// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
3219 /// locks load-bearing, and every `const`-context consumer that
3220 /// wants a canonical unset baseline reads through this constructor
3221 /// rather than the derived (non-`const`) [`Default::default`] or
3222 /// the five-field struct-literal `MeshPolicy { timeout: None,
3223 /// retries: None, circuit_breaker: None, mtls_required: None,
3224 /// rate_limit: None }` open-coded per-site.
3225 ///
3226 /// Direct peer of [`crate::LimitsSpec::empty`] (9739971) on the
3227 /// M2 `:limits` typed slot — same "`const`-context peer of the
3228 /// derived non-`const` [`Default::default`]" discipline extended
3229 /// onto the M3 `:politicas` typed slot. The two lifted `pub const
3230 /// fn` constructors together now cover the two per-slot
3231 /// [`Default`]-carrying M2/M3 typed slots that also carry an
3232 /// `is_empty()` emptiness predicate: every `const`-context consumer
3233 /// of a canonical unset per-slot baseline reads through the same
3234 /// paired-`(empty(), is_empty())` shape on either slot without a
3235 /// runtime dispatch on the derived [`Default::default`].
3236 ///
3237 /// Prior to this lift the "canonical unset [`MeshPolicy`]" shape
3238 /// was reached through one of two paths — the derived
3239 /// [`Default::default`] (`fn`, not `const fn` — a downstream
3240 /// `const _: MeshPolicy = MeshPolicy::default();` cannot compile
3241 /// because [`Default::default`] is not `const`-stable on stable
3242 /// Rust; the tracking issue on `const Default` still blocks the
3243 /// promotion) or an open-coded struct-literal with five `None`
3244 /// arms threaded verbatim at every call site (the five
3245 /// `MeshPolicy { timeout: Some(_), ..Default::default() }` /
3246 /// `MeshPolicy { retries: Some(_), ..Default::default() }` /
3247 /// sibling per-axis-only fixtures in this crate's own test module
3248 /// each rest on `..Default::default()` for the four peer arms; a
3249 /// future axis addition silently drifts the fixture's intent from
3250 /// "one axis under test, the other four unset" to "one axis under
3251 /// test, N axes unset, one field forgotten"). A future extension
3252 /// of the axis (a per-edge `:politicas` overlay the M4 roadmap
3253 /// grows once per-`:contratos`-edge overrides land, a sixth
3254 /// `:politicas` sub-slot the roadmap
3255 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
3256 /// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
3257 /// reaches this constructor at one edit (one added struct field
3258 /// on the type + one added `<axis>: None` line here) rather than
3259 /// a coordinated rewrite of every open-coded struct-literal at
3260 /// every downstream consumer.
3261 ///
3262 /// `pub const fn` — matches the sibling
3263 /// [`MeshPolicy::is_empty`] `pub const fn` shape verbatim, so
3264 /// every downstream consumer that folds a canonical unset
3265 /// baseline into a `const` position (a `const EMPTY: MeshPolicy =
3266 /// MeshPolicy::empty();` module-scope binding a future per-edge
3267 /// `:politicas` overlay reads through as its "no override
3268 /// declared" arm, a compile-time per-fixture-builder default the
3269 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3270 /// admission-time default-overlay-emit gate consults, a
3271 /// compile-time lookup table the LSP hover renderer materializes
3272 /// per typed-slot fixture) reads through one `const` dispatch
3273 /// rather than being forced onto the runtime code path. Pinned
3274 /// load-bearing at the substrate-primitive level by
3275 /// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
3276 /// (round-trip pin against [`Self::is_empty`]),
3277 /// [`tests::mesh_policy_empty_byte_equals_default`] (byte-parity
3278 /// pin against the derived [`Default::default`]), and
3279 /// [`tests::mesh_policy_empty_ctor_is_const_fn`] (const-eval-surface
3280 /// pin via `const` binding — any future accidental downgrade to
3281 /// `pub fn` fires E0015 at the binding at caixa-core build time,
3282 /// strictly stronger than a runtime `assert!`).
3283 #[must_use]
3284 pub const fn empty() -> Self {
3285 Self {
3286 timeout: None,
3287 retries: None,
3288 circuit_breaker: None,
3289 mtls_required: None,
3290 rate_limit: None,
3291 }
3292 }
3293
3294 /// True when no `:politicas` axis carries a value — every field is
3295 /// `None`. The same emptiness contract every other M2/M3 typed
3296 /// surface carries ([`crate::LimitsSpec::is_empty`],
3297 /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
3298 /// typed slot onto a cluster artifact key off this predicate to
3299 /// decide "emit the slot" vs "skip the slot entirely", so an
3300 /// authored-but-unset `:politicas (())` round-trips to a rendered
3301 /// artifact that's structurally identical to one that omits the
3302 /// slot. Lifted as a typed predicate (rather than per-renderer
3303 /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
3304 /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
3305 /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
3306 /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
3307 /// not a coordinated rewrite of every consumer that's reaching
3308 /// for the emptiness semantic.
3309 #[must_use]
3310 pub const fn is_empty(&self) -> bool {
3311 self.timeout().is_none()
3312 && self.retries().is_none()
3313 && self.circuit_breaker().is_none()
3314 && self.mtls_required().is_none()
3315 && self.rate_limit().is_none()
3316 }
3317
3318 /// Substrate-canonical cross-axis coherence predicate on the
3319 /// `:politicas` slot: does the `:circuit-breaker :window` rolling
3320 /// failure-observation interval span at least one full
3321 /// `:timeout`-bounded call?
3322 ///
3323 /// The first *cross-axis* invariant on the `:politicas` surface —
3324 /// every prior gate ([`AplicacaoSpec::validate_politicas`]'s four
3325 /// zero-floor + canonical-form + cap brackets) validates one axis
3326 /// in isolation, so a `MeshPolicy` whose axes are each individually
3327 /// well-formed could still name a structurally inert pair. The
3328 /// pair `{ timeout: 30s, circuit_breaker: { window: 10s, .. } }`
3329 /// passes every per-axis bracket (30s ≤ [`POLICY_TIMEOUT_MAX`],
3330 /// 10s ≤ [`POLICY_BREAKER_WINDOW_MAX`], both integer-millisecond,
3331 /// both above the zero floor) and is nonetheless a breaker that
3332 /// cannot trip on the failure mode it exists to catch: a call
3333 /// dispatched at t=0 is declared failed at t=30s, by which point
3334 /// the 10s window open at dispatch has rolled twice over, so no
3335 /// window can ever hold even one timeout-derived failure however
3336 /// high the call volume. Envoy's `outlier_detection.interval`
3337 /// carries the identical relation against the per-route request
3338 /// timeout; Hystrix ships the canonical ratio in its defaults
3339 /// (10s `metrics.rollingStats.timeInMilliseconds` against a 1s
3340 /// `execution.isolation.thread.timeoutInMilliseconds`).
3341 ///
3342 /// Vacuously `true` when either axis is absent — a `:politicas`
3343 /// that names only one of the pair declares no relation for the
3344 /// substrate to hold it to (`:timeout` alone is a per-call deadline
3345 /// with no breaker; `:circuit-breaker` alone is a breaker whose
3346 /// failures arrive from the transport's own error signal rather
3347 /// than from a substrate-imposed deadline, so no dispatch-to-report
3348 /// lag is knowable at author time). This is the same
3349 /// "unset means the cluster default applies, not zero" partition
3350 /// [`MeshPolicy::is_empty`] and every per-axis accessor's `None`
3351 /// arm already carry.
3352 ///
3353 /// Lifted as a typed predicate on the substrate primitive rather
3354 /// than open-coded at the validate gate so every downstream
3355 /// consumer of the pair reaches the invariant through one dispatch:
3356 /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
3357 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3358 /// (MESH-COMPOSITION §III.2 #3) that must emit
3359 /// `outlier_detection.interval` and the per-route `timeout` as one
3360 /// coherent Envoy block, the future M4
3361 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3362 /// webhook, and the future per-`:contratos`-edge `:politicas`
3363 /// override that same roadmap acknowledges — which resolves an
3364 /// *effective* pair per edge (edge-level `:timeout` against the
3365 /// Aplicacao-level `:window`, or vice versa) and so must re-check
3366 /// the relation on a pair neither axis's declaration site can see
3367 /// whole. Naming the invariant once means that resolver folds this
3368 /// predicate over its resolved pair instead of re-deriving the
3369 /// comparison, exactly as the sibling cross-slot
3370 /// [`PlacementStrategy::is_shard_keyed`] predicate names the
3371 /// `:placement`/`:shard-key` relation for its own consumers.
3372 #[must_use]
3373 pub const fn breaker_window_observes_timeout(&self) -> bool {
3374 match (self.timeout(), self.circuit_breaker()) {
3375 (Some(timeout), Some(cb)) => cb.window().as_nanos() >= timeout.as_nanos(),
3376 _ => true,
3377 }
3378 }
3379
3380 /// Substrate-canonical cross-axis coherence predicate on the
3381 /// `:politicas` slot: can the token-bucket rate declared by
3382 /// `:rate-limit` dispatch enough calls inside `:circuit-breaker
3383 /// :window` to reach `:max-failures`?
3384 ///
3385 /// The second cross-axis invariant on the `:politicas` surface —
3386 /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
3387 /// the `(:timeout, :circuit-breaker :window)` pair, extended onto
3388 /// the `(:rate-limit, :circuit-breaker)` pair. Each axis in the
3389 /// pair is validated in isolation by the per-axis brackets in
3390 /// [`AplicacaoSpec::validate_politicas`] (rate zero-floor + cap,
3391 /// max-failures zero-floor + cap, both windows zero-floor +
3392 /// integer-millisecond + cap, rate-limit window canonical-form),
3393 /// so a `MeshPolicy` whose axes are each individually well-formed
3394 /// can still name a structurally inert pair. The pair
3395 /// `{ rate-limit: "1/h", circuit-breaker: (:max-failures 5 :window
3396 /// "10s") }` passes every per-axis bracket and is nonetheless a
3397 /// breaker that cannot trip on the failure mode it exists to
3398 /// catch: the token bucket admits `rate × (cb.window / rl.window)`
3399 /// = `1 × (10s / 3600s)` ≈ 0 calls per rolling breaker window, so
3400 /// no window can accumulate five failures however catastrophically
3401 /// the upstream is failing. Envoy's
3402 /// `outlier_detection.consecutive_5xx` paired against
3403 /// `local_rate_limit.token_bucket.max_tokens` /
3404 /// `fill_interval` carries the identical relation; every
3405 /// production playbook that pairs the two axes (Envoy, Istio, AWS
3406 /// App Mesh, Kong) recommends sizing the rate at or above the
3407 /// breaker's minimum-request-volume threshold for exactly this
3408 /// reason.
3409 ///
3410 /// The typed test is the integer inequality
3411 /// `rate × cb.window.as_nanos() >= max_failures × rl.window.as_nanos()`
3412 /// (rearranged from `rate × cb.window / rl.window >= max_failures`
3413 /// so no floating-point division mediates the comparison and so
3414 /// the sub-second `rl.window` arms — `"n/s"` = 1s — are treated
3415 /// exactly). Both multiplicands are `saturating_mul`'d into
3416 /// [`u128`] so a struct-literal `MeshPolicy` whose per-axis fields
3417 /// have not yet passed [`AplicacaoSpec::validate_politicas`]
3418 /// (e.g. `rate: u32::MAX, cb_window: Duration::MAX`) does not
3419 /// panic the predicate; a saturated pair collapses to the
3420 /// "vacuously coherent" branch the peer per-axis brackets reject
3421 /// via their own zero-floor / cap arms first.
3422 ///
3423 /// Vacuously `true` when either axis is absent — a `:politicas`
3424 /// that names only one of the pair declares no relation for the
3425 /// substrate to hold it to (`:rate-limit` alone is a per-edge
3426 /// token-bucket declaration with no failure counter to starve;
3427 /// `:circuit-breaker` alone is a rolling-window failure counter
3428 /// whose call rate is unconstrained by the substrate, so no
3429 /// bucket-derived upper bound on calls-per-window is knowable at
3430 /// author time). Same "unset means the cluster default applies,
3431 /// not zero" partition [`MeshPolicy::is_empty`] and the sibling
3432 /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
3433 /// carry.
3434 ///
3435 /// Lifted as a typed predicate on the substrate primitive rather
3436 /// than open-coded at the validate gate so every downstream
3437 /// consumer of the pair reaches the invariant through one
3438 /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
3439 /// below, the future `CiliumClusterwideEnvoyConfig`
3440 /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
3441 /// must emit `local_rate_limit.token_bucket.{max_tokens,
3442 /// fill_interval}` alongside `outlier_detection.consecutive_5xx`
3443 /// / `outlier_detection.interval` as one coherent Envoy block,
3444 /// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3445 /// materializer's admission webhook, and the future
3446 /// per-`:contratos`-edge `:politicas` override the same roadmap
3447 /// acknowledges — which resolves an *effective* pair per edge
3448 /// (edge-level `:rate-limit` against the Aplicacao-level
3449 /// `:circuit-breaker`, or vice versa) and so must re-check the
3450 /// relation on a pair neither axis's declaration site can see
3451 /// whole. Naming the invariant once means that resolver folds
3452 /// this predicate over its resolved pair instead of re-deriving
3453 /// the comparison, exactly as the sibling cross-axis
3454 /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
3455 /// names the `(:timeout, :window)` relation for its own consumers.
3456 #[must_use]
3457 pub const fn breaker_can_trip_under_rate_limit(&self) -> bool {
3458 match (self.rate_limit(), self.circuit_breaker()) {
3459 (Some(rl), Some(cb)) => {
3460 let calls_per_cb_window =
3461 (rl.rate() as u128).saturating_mul(cb.window().as_nanos());
3462 let trip_threshold_per_cb_window =
3463 (cb.max_failures() as u128).saturating_mul(rl.window().as_nanos());
3464 calls_per_cb_window >= trip_threshold_per_cb_window
3465 }
3466 _ => true,
3467 }
3468 }
3469
3470 /// Substrate-canonical cross-axis coherence predicate on the
3471 /// `:politicas` slot: can one client's declared `:retries` all
3472 /// complete before `:circuit-breaker :max-failures` trips the
3473 /// breaker mid-retry?
3474 ///
3475 /// The third cross-axis invariant on the `:politicas` surface —
3476 /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
3477 /// the `(:timeout, :circuit-breaker :window)` pair and
3478 /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
3479 /// `(:rate-limit, :circuit-breaker)` pair, extended onto the
3480 /// `(:retries, :circuit-breaker :max-failures)` pair. Each axis in
3481 /// the pair is validated in isolation by the per-axis brackets in
3482 /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
3483 /// max-failures zero-floor + cap), so a `MeshPolicy` whose axes
3484 /// are each individually well-formed can still name a
3485 /// structurally-inert retry policy. The pair
3486 /// `{ :retries 3, :circuit-breaker (:max-failures 3 :window "1s") }`
3487 /// passes every per-axis bracket and is nonetheless a retry
3488 /// policy the substrate cannot honor: one client's initial attempt
3489 /// plus three retries is four attempts, but the breaker trips on
3490 /// the third failure — the fourth attempt (the last declared
3491 /// retry) is blocked by the open breaker, so the substrate
3492 /// declared four attempts and structurally allows three.
3493 ///
3494 /// The typed test is the integer inequality
3495 /// `cb.max_failures() > retries` — the retries count is the
3496 /// *number of retry attempts beyond the initial* (Envoy's
3497 /// `retry_policy.num_retries` semantics), so a client makes at
3498 /// most `retries + 1` attempts per client call, each of which may
3499 /// fail. For the breaker to *admit* the retry policy through
3500 /// completion, its trip threshold must not be reached by one
3501 /// client's failures alone: `retries + 1 <= max_failures`,
3502 /// equivalently `retries < max_failures`, equivalently
3503 /// `max_failures > retries`. The boundary case
3504 /// `max_failures == retries + 1` accepts (the R+1th failure — the
3505 /// last retry — trips the breaker exactly as it completes; retries
3506 /// are fully executed). The strict-below case
3507 /// `max_failures <= retries` rejects (the breaker trips before
3508 /// retries exhaust, silently truncating the declared retry policy
3509 /// mid-run — the same declared-but-structurally-inert footgun the
3510 /// sibling per-axis cap arms close on the single-axis surfaces).
3511 ///
3512 /// Vacuously `true` when either axis is absent — a `:politicas`
3513 /// that names only one of the pair declares no relation for the
3514 /// substrate to hold it to (`:retries` alone is a client-retry
3515 /// policy with no failure counter to trip; `:circuit-breaker`
3516 /// alone is a failure counter whose per-client attempt count is
3517 /// unconstrained by the substrate, so no per-client saturation
3518 /// bound on failures-per-client-call is knowable at author time).
3519 /// Same "unset means the cluster default applies, not zero"
3520 /// partition [`MeshPolicy::is_empty`] and the sibling
3521 /// [`MeshPolicy::breaker_window_observes_timeout`] /
3522 /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
3523 /// carry.
3524 ///
3525 /// Lifted as a typed predicate on the substrate primitive rather
3526 /// than open-coded at the validate gate so every downstream
3527 /// consumer of the pair reaches the invariant through one
3528 /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
3529 /// below, the future `CiliumClusterwideEnvoyConfig`
3530 /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
3531 /// must emit `retry_policy.num_retries` alongside
3532 /// `outlier_detection.consecutive_5xx` as one coherent Envoy
3533 /// block, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3534 /// materializer's admission webhook, and the future
3535 /// per-`:contratos`-edge `:politicas` override the same roadmap
3536 /// acknowledges — which resolves an *effective* pair per edge
3537 /// (edge-level `:retries` against the Aplicacao-level
3538 /// `:circuit-breaker`, or vice versa) and so must re-check the
3539 /// relation on a pair neither axis's declaration site can see
3540 /// whole. Naming the invariant once means that resolver folds
3541 /// this predicate over its resolved pair instead of re-deriving
3542 /// the comparison, exactly as the sibling cross-axis
3543 /// [`MeshPolicy::breaker_window_observes_timeout`] and
3544 /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
3545 /// name the `(:timeout, :window)` and `(:rate-limit,
3546 /// :circuit-breaker)` relations for their own consumers.
3547 #[must_use]
3548 pub const fn retries_fit_under_breaker_trip_threshold(&self) -> bool {
3549 match (self.retries(), self.circuit_breaker()) {
3550 (Some(retries), Some(cb)) => cb.max_failures() > retries,
3551 _ => true,
3552 }
3553 }
3554
3555 /// Substrate-canonical cross-axis coherence predicate on the
3556 /// `:politicas` slot: does the `:rate-limit` token-bucket capacity
3557 /// admit one client's full `:retries + 1` attempt burst inside a
3558 /// single refill window?
3559 ///
3560 /// The fourth cross-axis invariant on the `:politicas` surface,
3561 /// completing the triangle of pairs the three sibling gates carve
3562 /// out — sibling to [`MeshPolicy::breaker_window_observes_timeout`]
3563 /// on the `(:timeout, :circuit-breaker :window)` pair,
3564 /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
3565 /// `(:rate-limit, :circuit-breaker)` pair, and
3566 /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on the
3567 /// `(:retries, :circuit-breaker :max-failures)` pair, extended onto
3568 /// the `(:retries, :rate-limit)` pair — the last cross-axis relation
3569 /// among the three scalar `:politicas` axes (`:retries`,
3570 /// `:rate-limit`, `:circuit-breaker`) whose axis-triple defines the
3571 /// coherence surface every production overlay (Envoy, Istio,
3572 /// resilience4j, AWS App Mesh) resolves as one block. Each axis in
3573 /// the pair is validated in isolation by the per-axis brackets in
3574 /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
3575 /// rate zero-floor + cap, window canonical-form), so a `MeshPolicy`
3576 /// whose axes are each individually well-formed can still name a
3577 /// structurally-truncated retry policy the rate limiter refuses to
3578 /// admit. The pair `{ :retries 5, :rate-limit "3/s" }` passes every
3579 /// per-axis bracket and is nonetheless a retry policy the substrate
3580 /// cannot honor: one client's initial attempt plus five retries is
3581 /// six attempts, but the token bucket admits at most three tokens
3582 /// per one-second refill window, so the fourth attempt onward is
3583 /// blocked by the rate limiter itself — the substrate declared six
3584 /// attempts and structurally allows three. Envoy's
3585 /// `local_rate_limit.token_bucket.max_tokens` paired against
3586 /// `retry_policy.num_retries` carries the identical relation; every
3587 /// production playbook that pairs the two axes recommends sizing
3588 /// the bucket capacity above any single client's retry budget so
3589 /// the retry policy is not silently truncated by the same rate
3590 /// limiter it feeds through.
3591 ///
3592 /// The typed test is the integer inequality
3593 /// `rl.rate() >= retries + 1` — the retries count is the *number of
3594 /// retry attempts beyond the initial* (Envoy's
3595 /// `retry_policy.num_retries` semantics), so a client makes at most
3596 /// `retries + 1` attempts per client call, each of which consumes
3597 /// one token from the local rate-limit bucket. For the bucket to
3598 /// *admit* the retry burst without dropping tokens, its capacity
3599 /// must not be reached by one client's attempts alone:
3600 /// `retries + 1 <= rate`, equivalently `rate >= retries + 1`. The
3601 /// boundary case `rate == retries + 1` accepts (the bucket admits
3602 /// exactly one client's full retry sequence per refill window —
3603 /// retries fully executed). The strict-below case `rate <= retries`
3604 /// rejects (the bucket exhausts before retries complete, silently
3605 /// truncating the declared retry policy mid-run — the same
3606 /// declared-but-structurally-inert footgun the sibling per-axis cap
3607 /// arms close on the single-axis surfaces). The equivalent
3608 /// coherent-direction form `rl.rate() > retries` sidesteps the
3609 /// `retries + 1` addition entirely (both `rate` and `retries` are
3610 /// `u32`; the `>` comparison is total on the type with no overflow
3611 /// against past-the-guard struct-literal `retries` values a caller
3612 /// might pass before `validate` runs), matching the peer
3613 /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] direct-
3614 /// `>`-comparison discipline on the sibling
3615 /// `(:retries, :max-failures)` pair.
3616 ///
3617 /// Vacuously `true` when either axis is absent — a `:politicas`
3618 /// that names only one of the pair declares no relation for the
3619 /// substrate to hold it to (`:retries` alone is a client-retry
3620 /// policy with no rate limiter to saturate; `:rate-limit` alone is
3621 /// a token-bucket declaration whose per-client attempt count is
3622 /// unconstrained by the substrate, so no per-client saturation
3623 /// bound on tokens-per-client-call is knowable at author time).
3624 /// Same "unset means the cluster default applies, not zero"
3625 /// partition [`MeshPolicy::is_empty`] and the three sibling
3626 /// cross-axis predicates
3627 /// ([`MeshPolicy::breaker_window_observes_timeout`],
3628 /// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
3629 /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]) carry.
3630 ///
3631 /// Lifted as a typed predicate on the substrate primitive rather
3632 /// than open-coded at the validate gate so every downstream
3633 /// consumer of the pair reaches the invariant through one dispatch:
3634 /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
3635 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3636 /// (MESH-COMPOSITION §III.2 #3) that must emit
3637 /// `local_rate_limit.token_bucket.max_tokens` alongside
3638 /// `retry_policy.num_retries` as one coherent Envoy block, the
3639 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3640 /// admission webhook, and the future per-`:contratos`-edge
3641 /// `:politicas` override the same roadmap acknowledges — which
3642 /// resolves an *effective* pair per edge (edge-level `:retries`
3643 /// against the Aplicacao-level `:rate-limit`, or vice versa) and
3644 /// so must re-check the relation on a pair neither axis's
3645 /// declaration site can see whole. Naming the invariant once means
3646 /// that resolver folds this predicate over its resolved pair
3647 /// instead of re-deriving the comparison, exactly as the three
3648 /// sibling cross-axis predicates name the
3649 /// `(:timeout, :window)` / `(:rate-limit, :circuit-breaker)` /
3650 /// `(:retries, :max-failures)` relations for their own consumers,
3651 /// closing the fourth and last cross-axis relation on the scalar
3652 /// `:politicas` axis-triple.
3653 #[must_use]
3654 pub const fn rate_limit_admits_retry_burst(&self) -> bool {
3655 match (self.retries(), self.rate_limit()) {
3656 (Some(retries), Some(rl)) => rl.rate() > retries,
3657 _ => true,
3658 }
3659 }
3660
3661 /// Substrate-canonical fold over the four cross-axis coherence
3662 /// predicates on the `:politicas` slot — returns the *first*
3663 /// cross-axis violation (as its [`AplicacaoError`] variant) in the
3664 /// canonical "more-foundational-cross-axis first" ordering
3665 /// [`MeshPolicy::breaker_window_observes_timeout`] on
3666 /// `(:timeout, :circuit-breaker :window)` →
3667 /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on
3668 /// `(:rate-limit, :circuit-breaker)` →
3669 /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on
3670 /// `(:retries, :circuit-breaker :max-failures)` →
3671 /// [`MeshPolicy::rate_limit_admits_retry_burst`] on `(:retries,
3672 /// :rate-limit)`. Returns `None` when every cross-axis relation
3673 /// holds (the vacuous shape [`MeshPolicy::is_empty`] and the fully-
3674 /// coherent shape both land here).
3675 ///
3676 /// The ordering discipline this method encodes was open-coded four
3677 /// times at [`AplicacaoSpec::validate_politicas`] — each cross-axis
3678 /// gate was an `if !<predicate>() { let <a> = self.<axis>().expect(
3679 /// "cross-axis gate fires only when :<axis> is present"); let <b>
3680 /// = self.<axis>().expect(…); return Err(<variant>) }` block whose
3681 /// axis-fetch step depended on the predicate having just returned
3682 /// `false` (structurally guaranteed both paired axes are `Some`,
3683 /// but the compiler cannot see through the predicate body, so
3684 /// every arm re-called the accessor with `.expect(…)` to reach
3685 /// the axis it just tested). Two unsound consequences: (1) the
3686 /// validate gate carried eight `.expect(…)` panic call sites the
3687 /// predicate contract already forbids on every well-typed input
3688 /// but the type system does not enforce; (2) the
3689 /// "which-cross-axis-fires-first-when-two-apply" contract lived
3690 /// twice — once in each predicate's own doc comments and once at
3691 /// the validate call site's four-arm cascade. Lifting the four-arm
3692 /// cascade onto this substrate primitive collapses both
3693 /// duplications: the predicate contract and the axis-fetch step
3694 /// live in the same body (no `.expect(…)` — the pattern match at
3695 /// each arm rebinds the paired axes so their `Some` presence is a
3696 /// compile-time property of the local scope), and the ordering
3697 /// discipline lives once at the top of the primitive rather than
3698 /// scattered across four sibling doc-comment blocks that must
3699 /// stay in lockstep.
3700 ///
3701 /// Every downstream cross-axis consumer (the [`AplicacaoSpec::
3702 /// validate_politicas`] gate below, the future M4 `mesh.pleme.io/
3703 /// v1alpha1/Aplicacao` CR materializer's admission webhook, the
3704 /// per-`:contratos`-edge `:politicas` override MESH-COMPOSITION
3705 /// §III.2 #3 acknowledges — the last of which resolves an
3706 /// *effective* per-edge pair and must emit *the same* diagnostic
3707 /// on the same paired-axis input as `feira build`) reaches through
3708 /// one call rather than re-inlining the four pattern-matches +
3709 /// accessor-fetches + variant-constructions + ordering-cascade.
3710 ///
3711 /// Returns owned copies of every axis carried into the diagnostic:
3712 /// [`Duration`] and [`u32`] are `Copy`, so no `String` allocation
3713 /// occurs on the happy path when no violation fires.
3714 #[must_use]
3715 pub fn first_cross_axis_violation(&self) -> Option<AplicacaoError> {
3716 // Ordering discipline this fold encodes matches the four
3717 // per-arm predicate doc comments' pairwise-ordering contract:
3718 // window-below-timeout wins over every arm that names `:rate-
3719 // limit` or `:retries` (its diagnostic is more self-locating —
3720 // the pair is a per-call-deadline invariant every synchronous
3721 // edge carries whether or not `:rate-limit`/`:retries` is
3722 // declared); the starve arm wins over the two retry arms (its
3723 // diagnostic reasons across the token-bucket-vs-breaker
3724 // relation, an axis the retry arms do not touch); the
3725 // retries-saturate arm wins over the retries-burst arm (its
3726 // diagnostic reasons across the per-client-vs-breaker
3727 // relation, which carries whether or not `:rate-limit` is
3728 // declared). Each arm rebinds the paired axes through the
3729 // pattern match, so the `.expect(…)` panics the four-block
3730 // cascade at `validate_politicas` carried collapse to no-op
3731 // pattern rebindings the compiler statically proves exhaust.
3732 if let (Some(t), Some(cb)) = (self.timeout(), self.circuit_breaker())
3733 && !self.breaker_window_observes_timeout()
3734 {
3735 return Some(AplicacaoError::policy_breaker_window_below_timeout(&cb, t));
3736 }
3737 if let (Some(rl), Some(cb)) = (self.rate_limit(), self.circuit_breaker())
3738 && !self.breaker_can_trip_under_rate_limit()
3739 {
3740 return Some(AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(
3741 &rl, &cb,
3742 ));
3743 }
3744 if let (Some(retries), Some(cb)) = (self.retries(), self.circuit_breaker())
3745 && !self.retries_fit_under_breaker_trip_threshold()
3746 {
3747 return Some(
3748 AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb),
3749 );
3750 }
3751 if let (Some(retries), Some(rl)) = (self.retries(), self.rate_limit())
3752 && !self.rate_limit_admits_retry_burst()
3753 {
3754 return Some(AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(
3755 retries, &rl,
3756 ));
3757 }
3758 None
3759 }
3760
3761 /// Substrate-canonical compound entry gate over the whole
3762 /// `:politicas` typed slot — folds every per-axis bracket
3763 /// (`:timeout` / `:retries` / `:circuit-breaker :max-failures` /
3764 /// `:circuit-breaker :window` / `:rate-limit` rate / `:rate-limit`
3765 /// window-canonical-form) *and* the compound cross-axis fold
3766 /// [`MeshPolicy::first_cross_axis_violation`] into one call every
3767 /// consumer of a validated [`MeshPolicy`] reaches through.
3768 ///
3769 /// Returns the first violation as its [`AplicacaoError`] variant,
3770 /// or `Ok(())` when every per-axis value lies in its accept-set and
3771 /// every cross-axis relation holds. Per-axis brackets run strictly
3772 /// before the cross-axis fold — the sibling
3773 /// [`AplicacaoSpec::validate_politicas`] gate carried the same
3774 /// ordering discipline for the same reason: a per-axis
3775 /// structurally-invalid value (a `Duration::ZERO` `:window`, an
3776 /// above-cap `:rate-limit` rate) surfaces its own self-locating
3777 /// diagnostic first, ahead of any cross-axis arm that would send
3778 /// the author to reconcile two values one of which is not a
3779 /// meaningful window at all. Within the per-axis phase, arms fire
3780 /// in the same slot-order the peer per-axis brackets carry
3781 /// (`:timeout` → `:retries` → `:circuit-breaker` → `:rate-limit`,
3782 /// each internally ordered zero-floor before canonical-form before
3783 /// cap by [`crate::render::require_positive_bounded_u32`] /
3784 /// [`crate::render::require_positive_canonical_bounded_duration`]);
3785 /// within the cross-axis phase, arms fire in the canonical
3786 /// more-foundational-cross-axis-first ordering
3787 /// [`MeshPolicy::first_cross_axis_violation`] encodes.
3788 ///
3789 /// Lifted as a typed method on the substrate primitive so every
3790 /// downstream consumer of a validated [`MeshPolicy`] reaches the
3791 /// invariant through one dispatch: the
3792 /// [`AplicacaoSpec::validate_politicas`] gate below (whose whole
3793 /// body collapses to `self.politicas().validate()`), the future
3794 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3795 /// admission webhook, the future per-`:contratos`-edge `:politicas`
3796 /// override MESH-COMPOSITION §III.2 #3 acknowledges — the last of
3797 /// which resolves an *effective* per-edge [`MeshPolicy`] and must
3798 /// emit *the same* diagnostic on the same input as `feira build`.
3799 /// Naming the compound gate once on the substrate primitive means
3800 /// every downstream consumer inherits both the per-axis brackets
3801 /// *and* the cross-axis fold through one call, rather than
3802 /// re-inlining the four-per-axis + one-cross-axis cascade in
3803 /// lockstep with `validate_politicas`.
3804 ///
3805 /// Peer of the per-kind compound entry gates lifted at
3806 /// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
3807 /// [`crate::render::require_supervisor_view`] (8d8a5c3), and
3808 /// [`crate::render::require_v0_servico_shape`] on the per-Caixa
3809 /// layout axis, and the sibling compound cross-axis fold
3810 /// [`MeshPolicy::first_cross_axis_violation`] on the same
3811 /// `:politicas` axis — extended here onto the per-slot per-axis +
3812 /// cross-axis compound entry gate that folds both surfaces.
3813 pub fn validate(&self) -> Result<(), AplicacaoError> {
3814 if let Some(t) = self.timeout() {
3815 crate::render::require_positive_canonical_bounded_duration(
3816 t,
3817 POLICY_TIMEOUT_MAX,
3818 || AplicacaoError::PolicyTimeoutZero,
3819 AplicacaoError::policy_timeout_not_canonical,
3820 AplicacaoError::policy_timeout_exceeds_cap,
3821 )?;
3822 }
3823 if let Some(r) = self.retries() {
3824 crate::render::require_positive_bounded_u32(
3825 r,
3826 POLICY_RETRIES_MAX,
3827 || AplicacaoError::PolicyRetriesZero,
3828 AplicacaoError::policy_retries_exceeds_cap,
3829 )?;
3830 }
3831 if let Some(cb) = self.circuit_breaker() {
3832 crate::render::require_positive_bounded_u32(
3833 cb.max_failures(),
3834 POLICY_BREAKER_MAX_FAILURES_MAX,
3835 || AplicacaoError::PolicyBreakerZeroFailures,
3836 AplicacaoError::policy_breaker_max_failures_exceeds_cap,
3837 )?;
3838 crate::render::require_positive_canonical_bounded_duration(
3839 cb.window(),
3840 POLICY_BREAKER_WINDOW_MAX,
3841 || AplicacaoError::PolicyBreakerZeroWindow,
3842 AplicacaoError::policy_breaker_window_not_canonical,
3843 AplicacaoError::policy_breaker_window_exceeds_cap,
3844 )?;
3845 }
3846 if let Some(rl) = self.rate_limit() {
3847 crate::render::require_positive_bounded_u32(
3848 rl.rate(),
3849 POLICY_RATE_LIMIT_MAX,
3850 || AplicacaoError::PolicyRateLimitZero,
3851 AplicacaoError::policy_rate_limit_exceeds_cap,
3852 )?;
3853 if rl.canonical_unit().is_none() {
3854 return Err(AplicacaoError::policy_rate_limit_window_not_canonical(
3855 rl.window(),
3856 ));
3857 }
3858 }
3859 if let Some(err) = self.first_cross_axis_violation() {
3860 return Err(err);
3861 }
3862 Ok(())
3863 }
3864
3865 /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
3866 /// per-call-deadline scalar accessor every consumer of the
3867 /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
3868 /// returns the author-declared `:politicas :timeout` typed
3869 /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
3870 /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
3871 /// is `Copy`, so the accessor returns by value; no borrow of
3872 /// `&self` past the call). `None` when the slot is absent (the
3873 /// "cluster default applies — typically the gateway class's
3874 /// implementation-side per-request wall-clock cap" arm caixa-mesh's
3875 /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
3876 /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
3877 /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
3878 /// round-trips to a rendered `HTTPRoute` structurally identical to
3879 /// one that omits the slot).
3880 ///
3881 /// The `:politicas :timeout` slot carries the "no infinite blocking"
3882 /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
3883 /// the typed slot's `Option<Duration>` accept-set (zero-floor
3884 /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
3885 /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
3886 /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
3887 /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
3888 /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
3889 /// Every downstream consumer that reads the per-call cap keys off
3890 /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3891 /// renderers key off to decide "emit :politicas overlay" vs "skip
3892 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3893 /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
3894 /// fans the deadline into every rule via
3895 /// [`crate::render::single_field_overlay`], the future M4 per-
3896 /// Aplicacao Gateway API reconciler materialization pass, the
3897 /// future per-`:contratos`-edge timeout-override overlay the
3898 /// MESH-COMPOSITION §III.2 roadmap acknowledges).
3899 ///
3900 /// Prior to this lift the `.timeout` field was accessed inline at
3901 /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
3902 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
3903 /// …)` call — two open-coded field-accesses that expressed no
3904 /// compile-time link back to the typed slot. A future extension of
3905 /// the `:politicas :timeout` axis to a richer author surface — a
3906 /// per-`:contratos`-edge timeout override the operator pins through
3907 /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
3908 /// roadmap acknowledges, a per-cluster timeout-default overlay the
3909 /// M4 CR materializer resolves per-CR, a split of the single
3910 /// per-call `Duration` into a richer `{request, backendRequest}`
3911 /// pair once the Gateway API's per-rule `timeouts` block grows the
3912 /// upstream-facing backendRequest arm alongside the client-facing
3913 /// request arm — would have had to be threaded through both open-
3914 /// coded copies in lockstep or the emptiness predicate and the
3915 /// caixa-mesh emit path would silently disagree on which per-call
3916 /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
3917 /// whose only axis is a `Some :timeout` would satisfy `is_empty()
3918 /// == false` while the renderer's overlay-emit path silently read
3919 /// a drifted other value, or vice versa: an author's `:timeout
3920 /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
3921 /// the emptiness predicate still classified the policy as non-
3922 /// empty, and every `kubectl -n tatara-system get httproute -o yaml
3923 /// | grep -A2 timeouts` audit would land on a route whose author's
3924 /// typed slot value silently vanished at the renderer layer).
3925 /// Lifting the resolution to a typed method on the substrate
3926 /// primitive means every downstream consumer of the Aplicacao's
3927 /// per-`:politicas` deadline surface reaches for exactly one typed
3928 /// dispatch — the resolver's accept-set migrates as a unit on any
3929 /// future axis addition.
3930 ///
3931 /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
3932 /// family (sibling of the peer per-`:politicas`
3933 /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
3934 /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
3935 /// `Option<bool>` accessor — same "one typed dispatch on the
3936 /// substrate primitive, thin projections at each consumer"
3937 /// discipline extended onto the peer per-`:politicas` typed-
3938 /// [`Duration`] optional-scalar axis; closes the "optional per-slot
3939 /// numeric-Copy-T scalar" projection pattern the sibling
3940 /// `Option<u32>` / `Option<bool>` lifts opened, since every
3941 /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
3942 /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
3943 /// than a scalar). Named `timeout()` to match the storage field's
3944 /// name; the accessor's identity maps onto the canonical MESH-
3945 /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
3946 #[must_use]
3947 pub const fn timeout(&self) -> Option<Duration> {
3948 self.timeout
3949 }
3950
3951 /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
3952 /// retry-budget scalar accessor every consumer of the Aplicacao's
3953 /// Gateway API v1.x per-rule retry-cap keys off — returns the
3954 /// author-declared `:politicas :retries` typed `u32` verbatim as an
3955 /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
3956 /// storage (`Option<u32>` is `Copy`, so the accessor returns by
3957 /// value; no borrow of `&self` past the call). `None` when the slot
3958 /// is absent (the "cluster default applies — typically 'no retries
3959 /// beyond a single dispatch attempt'" arm the caixa-mesh
3960 /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
3961 /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
3962 /// this predicate too, so an authored-but-unset `:politicas
3963 /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
3964 /// identical to one that omits the slot).
3965 ///
3966 /// The `:politicas :retries` slot carries the "transient failure
3967 /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
3968 /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
3969 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3970 /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
3971 /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
3972 /// count scalar the caixa-mesh `retry_overlay` builder writes.
3973 /// Every downstream consumer that reads the retry cap keys off this
3974 /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3975 /// renderers key off to decide "emit :politicas overlay" vs "skip
3976 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3977 /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
3978 /// the value into every rule via [`crate::render::single_field_overlay`],
3979 /// the future M4 per-Aplicacao Gateway API reconciler
3980 /// materialization pass, the future per-`:contratos`-edge retry-
3981 /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
3982 /// acknowledges).
3983 ///
3984 /// Prior to this lift the `.retries` field was accessed inline at
3985 /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
3986 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
3987 /// …)` call — two open-coded field-accesses that expressed no
3988 /// compile-time link back to the typed slot. A future extension of
3989 /// the `:politicas :retries` axis to a richer author surface — a
3990 /// per-`:contratos`-edge retry override the operator pins through a
3991 /// future `:contratos :retries` slot, a per-cluster retry-default
3992 /// overlay the M4 CR materializer resolves per-CR, a promotion of
3993 /// the plain `u32` attempt-count to a richer `{attempts, codes,
3994 /// backoff}` sub-block once the Gateway API grows the peer
3995 /// `retry.codes` / `retry.backoff` axes — would have had to be
3996 /// threaded through both open-coded copies in lockstep or the
3997 /// emptiness predicate and the caixa-mesh emit path would silently
3998 /// disagree on which retry budget a given [`MeshPolicy`] resolves to
3999 /// (a `:politicas` block whose only axis is a `Some :retries` would
4000 /// satisfy `is_empty() == false` while the renderer's overlay-emit
4001 /// path silently read a drifted other value, or vice versa: an
4002 /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
4003 /// block while the emptiness predicate still classified the policy
4004 /// as non-empty). Lifting the resolution to a typed method on the
4005 /// substrate primitive means every downstream consumer of the
4006 /// Aplicacao's per-`:politicas` retry surface reaches for exactly
4007 /// one typed dispatch — the resolver's accept-set migrates as a
4008 /// unit on any future axis addition.
4009 ///
4010 /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
4011 /// family (sibling of the peer per-`:politicas`
4012 /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
4013 /// same "one typed dispatch on the substrate primitive, thin
4014 /// projections at each consumer" discipline extended onto the
4015 /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
4016 /// the "optional per-slot numeric-Copy-T scalar" projection pattern
4017 /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
4018 /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
4019 /// fold on). Named `retries()` to match the storage field's name;
4020 /// the accessor's identity maps onto the canonical MESH-COMPOSITION
4021 /// §III.2 vocabulary the slot's docstring already carries.
4022 #[must_use]
4023 pub const fn retries(&self) -> Option<u32> {
4024 self.retries
4025 }
4026
4027 /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
4028 /// enforcement-toggle scalar accessor every consumer of the
4029 /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
4030 /// — returns the author-declared `:politicas :mtls-required` typed
4031 /// bool verbatim as an `Option<bool>`, copied out of the typed
4032 /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
4033 /// the accessor returns by value; no borrow of `&self` past the
4034 /// call). `None` when the slot is absent (the "cluster default
4035 /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
4036 /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
4037 /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
4038 /// this predicate too, so an authored-but-unset `:politicas
4039 /// (:mtls-required ())` round-trips to a rendered
4040 /// `CiliumNetworkPolicy` structurally identical to one that omits
4041 /// the slot).
4042 ///
4043 /// The `:politicas :mtls-required` slot carries the "explicit opt-
4044 /// out only, sandboxing-by-default" mTLS-enforcement toggle
4045 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
4046 /// `{None, Some(true), Some(false)}` accept-set maps onto the
4047 /// Cilium `authentication.mode` bijection through
4048 /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
4049 /// handshake enforced), `Some(false) → "disabled"` (handshake
4050 /// skipped — the debug-edge opt-out), `None` → omit the block
4051 /// (cluster default applies). Every downstream consumer that
4052 /// reads the toggle keys off this scalar (the
4053 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4054 /// off to decide "emit :politicas overlay" vs "skip entirely", the
4055 /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
4056 /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
4057 /// ingress rule via [`crate::render::single_field_overlay`], the
4058 /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
4059 /// materialization pass, the future per-`:contratos`-edge mTLS
4060 /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4061 ///
4062 /// Prior to this lift the `.mtls_required` field was accessed
4063 /// inline at two sites — [`MeshPolicy::is_empty`]'s
4064 /// `self.mtls_required.is_none()` arm and caixa-mesh's
4065 /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
4066 /// two open-coded field-accesses that expressed no compile-time
4067 /// link back to the typed slot. A future extension of the
4068 /// `:politicas :mtls-required` axis to a richer author surface —
4069 /// a per-`:contratos`-edge mTLS override the operator pins through
4070 /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
4071 /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
4072 /// M4 CR materializer resolves per-CR, a three-valued
4073 /// `{None, Some(true), Some(false), Some(Optional)}` promotion
4074 /// once Cilium's `authentication.mode` grows an `"optional"` arm —
4075 /// would have had to be threaded through both open-coded copies in
4076 /// lockstep or the emptiness predicate and the caixa-mesh emit
4077 /// path would silently disagree on which toggle a given
4078 /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
4079 /// axis is a `Some`
4080 /// `:mtls-required` would satisfy `is_empty() == false` while the
4081 /// renderer's overlay-emit path silently read a drifted other
4082 /// value, or vice versa). Lifting the resolution to a typed method
4083 /// on the substrate primitive means every downstream consumer of
4084 /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
4085 /// for exactly one typed dispatch — the resolver's accept-set
4086 /// migrates as a unit on any future axis addition.
4087 ///
4088 /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
4089 /// family (peer of the sibling per-`:placement`
4090 /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
4091 /// same "one typed dispatch on the substrate primitive, thin
4092 /// projections at each consumer" discipline extended onto the
4093 /// peer per-`:politicas` typed-bool optional-scalar axis; opens
4094 /// the "optional per-slot Copy-T scalar" projection pattern the
4095 /// sibling per-`:politicas` `:retries` (Option<u32>) /
4096 /// `:timeout` (Option<Duration>) future lifts fold on). Named
4097 /// `mtls_required()` to match the storage field's name; the
4098 /// accessor's identity maps onto the canonical MESH-COMPOSITION
4099 /// §III.2 vocabulary the slot's docstring already carries.
4100 #[must_use]
4101 pub const fn mtls_required(&self) -> Option<bool> {
4102 self.mtls_required
4103 }
4104
4105 /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
4106 /// `local_rate_limit`-mesh token-bucket-declaration scalar
4107 /// accessor every consumer of the Aplicacao's per-`:politicas`
4108 /// per-`(rate, window)` rate-limit surface keys off — returns the
4109 /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
4110 /// verbatim as an `Option<RateLimit>`, copied out of the typed
4111 /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
4112 /// `Copy`, so the accessor returns by value; no borrow of `&self`
4113 /// past the call). `None` when the slot is absent (the "cluster
4114 /// default applies — typically 'no per-Aplicacao rate declaration,
4115 /// gateway-class per-listener default applies'" arm the future
4116 /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
4117 /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
4118 /// `rate_limit().is_none()` arm reads this predicate too, so an
4119 /// authored-but-unset `:politicas (:rate-limit ())` round-trips
4120 /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
4121 /// identical to one that omits the slot).
4122 ///
4123 /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
4124 /// token-bucket rate declaration" contract (MESH-COMPOSITION
4125 /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
4126 /// (rate lower-bounded by 1 through
4127 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
4128 /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
4129 /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
4130 /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
4131 /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
4132 /// bijection the future `CiliumClusterwideEnvoyConfig` per-
4133 /// `:politicas` overlay emits. Every downstream consumer that
4134 /// reads the rate declaration keys off this scalar (the
4135 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4136 /// off to decide "emit :politicas overlay" vs "skip entirely", the
4137 /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
4138 /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
4139 /// `rl.window` against [`is_canonical_rate_limit_window`], the
4140 /// future M4 per-Aplicacao Envoy reconciler materialization pass,
4141 /// the future per-`:contratos`-edge rate-limit override the
4142 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4143 ///
4144 /// Prior to this lift the `.rate_limit` field was accessed inline
4145 /// at two sites — [`MeshPolicy::is_empty`]'s
4146 /// `self.rate_limit.is_none()` arm and the `validate_politicas`
4147 /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
4148 /// field-accesses that expressed no compile-time link back to the
4149 /// typed slot. A future extension of the `:politicas :rate-limit`
4150 /// axis to a richer author surface — a per-`:contratos`-edge
4151 /// rate-limit override the operator pins through a future
4152 /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
4153 /// roadmap acknowledges, a per-cluster rate-limit-default overlay
4154 /// the M4 CR materializer resolves per-CR, a promotion of the
4155 /// plain `(rate, window)` scalar pair to a richer
4156 /// `{rate, window, burst, key}` sub-block once Envoy's
4157 /// `local_rate_limit` grows the peer `burst_size` /
4158 /// `descriptor_key` axes — would have had to be threaded through
4159 /// both open-coded copies in lockstep or the emptiness predicate
4160 /// and the validate gate would silently disagree on which rate
4161 /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
4162 /// block whose only axis is a `Some :rate-limit` would satisfy
4163 /// `is_empty() == false` while the validate path silently read a
4164 /// drifted other value, or vice versa: an author's
4165 /// `:rate-limit "100/s"` would omit the value-shape gate while the
4166 /// emptiness predicate still classified the policy as non-empty).
4167 /// Lifting the resolution to a typed method on the substrate
4168 /// primitive means every downstream consumer of the Aplicacao's
4169 /// per-`:politicas` rate-limit surface reaches for exactly one
4170 /// typed dispatch — the resolver's accept-set migrates as a unit
4171 /// on any future axis addition.
4172 ///
4173 /// First `Option<Copy-composite-T>`-return accessor on the M3
4174 /// mesh-slot family — closes the last un-lifted per-`:politicas`
4175 /// scalar-value axis. Peer of the sibling per-`:politicas`
4176 /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
4177 /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
4178 /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
4179 /// "one typed dispatch on the substrate primitive, thin
4180 /// projections at each consumer" discipline extended onto the
4181 /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
4182 /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
4183 /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
4184 /// sub-accessors rather than a top-level accessor because
4185 /// consumers reach for the axes not the aggregate). Named
4186 /// `rate_limit()` to match the storage field's name; the
4187 /// accessor's identity maps onto the canonical MESH-COMPOSITION
4188 /// §III.2 vocabulary the slot's docstring already carries.
4189 #[must_use]
4190 pub const fn rate_limit(&self) -> Option<RateLimit> {
4191 self.rate_limit
4192 }
4193
4194 /// Substrate-canonical per-`:politicas` `:circuit-breaker`
4195 /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
4196 /// declaration scalar accessor every consumer of the Aplicacao's
4197 /// per-`:politicas` breaker declaration keys off — returns the
4198 /// author-declared `:politicas :circuit-breaker` typed
4199 /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
4200 /// copied out of the typed slot's own `Option<CircuitBreaker>`
4201 /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
4202 /// by value; no borrow of `&self` past the call). `None` when the
4203 /// slot is absent (the "cluster default applies — typically 'no
4204 /// per-Aplicacao breaker declaration, gateway-class per-listener
4205 /// default applies'" arm the future caixa-mesh
4206 /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
4207 /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
4208 /// arm reads this predicate too, so an authored-but-unset
4209 /// `:politicas (:circuit-breaker ())` round-trips to a rendered
4210 /// `CiliumClusterwideEnvoyConfig` structurally identical to one
4211 /// that omits the slot).
4212 ///
4213 /// The `:politicas :circuit-breaker` slot carries the
4214 /// "per-Aplicacao consecutive-transient-failure trip declaration"
4215 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
4216 /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
4217 /// zero-floor rejected through
4218 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
4219 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
4220 /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
4221 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
4222 /// canonical-form pinned through
4223 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
4224 /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
4225 /// bijection the future `CiliumClusterwideEnvoyConfig`
4226 /// per-`:politicas` overlay emits. Every downstream consumer that
4227 /// reads the breaker declaration keys off this scalar (the
4228 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
4229 /// off to decide "emit :politicas overlay" vs "skip entirely", the
4230 /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
4231 /// that brackets `cb.max_failures()` against
4232 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
4233 /// [`POLICY_BREAKER_WINDOW_MAX`] via
4234 /// [`crate::render::require_positive_canonical_bounded_duration`],
4235 /// the future M4 per-Aplicacao Envoy reconciler materialization
4236 /// pass, the future per-`:contratos`-edge breaker override the
4237 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4238 ///
4239 /// Prior to this lift the `.circuit_breaker` field was accessed
4240 /// inline at two sites — [`MeshPolicy::is_empty`]'s
4241 /// `self.circuit_breaker.is_none()` arm and the
4242 /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
4243 /// bind — two open-coded field-accesses that expressed no
4244 /// compile-time link back to the typed slot. A future extension of
4245 /// the `:politicas :circuit-breaker` axis to a richer author
4246 /// surface — a per-`:contratos`-edge breaker override the operator
4247 /// pins through a future `:contratos :circuit-breaker` slot the
4248 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
4249 /// breaker-default overlay the M4 CR materializer resolves per-CR,
4250 /// a promotion of the plain `(max_failures, window)` scalar pair to
4251 /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
4252 /// sub-block once Envoy's `outlier_detection` grows the peer
4253 /// ejection-percentage / ejection-time axes — would have had to be
4254 /// threaded through both open-coded copies in lockstep or the
4255 /// emptiness predicate and the validate gate would silently
4256 /// disagree on which breaker declaration a given [`MeshPolicy`]
4257 /// resolves to (a `:politicas` block whose only axis is a
4258 /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
4259 /// the validate path silently read a drifted other value, or vice
4260 /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
4261 /// "60s"))` would omit the value-shape gate while the emptiness
4262 /// predicate still classified the policy as non-empty). Lifting
4263 /// the resolution to a typed method on the substrate primitive
4264 /// means every downstream consumer of the Aplicacao's
4265 /// per-`:politicas` breaker surface reaches for exactly one typed
4266 /// dispatch — the resolver's accept-set migrates as a unit on any
4267 /// future axis addition.
4268 ///
4269 /// Second `Option<Copy-composite-T>`-return accessor on the M3
4270 /// mesh-slot family (sibling of the peer per-`:politicas`
4271 /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
4272 /// on the same composite-Copy shape, and of the sibling per-
4273 /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
4274 /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
4275 /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
4276 /// `Option<bool>` accessors on the sibling primitive-Copy axes —
4277 /// same "one typed dispatch on the substrate primitive, thin
4278 /// projections at each consumer" discipline extended onto the last
4279 /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
4280 /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
4281 /// match the storage field's name; the accessor's identity maps
4282 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4283 /// docstring already carries. Closes the last unlifted
4284 /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
4285 /// reader now routes through a typed dispatch on the substrate
4286 /// primitive.
4287 #[must_use]
4288 pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
4289 self.circuit_breaker
4290 }
4291}
4292
4293#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
4294#[serde(rename_all = "camelCase")]
4295pub struct CircuitBreaker {
4296 pub max_failures: u32,
4297 #[serde(with = "supervisor::duration_codec_required")]
4298 pub window: Duration,
4299}
4300
4301impl CircuitBreaker {
4302 /// Substrate-canonical per-`:politicas :circuit-breaker`
4303 /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
4304 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4305 /// breaker trip-count keys off — returns the author-declared
4306 /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
4307 /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
4308 /// so the accessor returns by value; no borrow of `&self` past the
4309 /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
4310 /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
4311 /// axis; a `CircuitBreaker` past pattern-match is definitionally
4312 /// present, and its `:max-failures` field carries the trip count as a
4313 /// required-axis scalar).
4314 ///
4315 /// The `:politicas :circuit-breaker :max-failures` axis carries the
4316 /// "consecutive-transient-failure trip threshold" contract
4317 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
4318 /// (zero-floor rejected through
4319 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
4320 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
4321 /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
4322 /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
4323 /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
4324 /// Every downstream consumer that reads the trip threshold keys off
4325 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4326 /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
4327 /// canonical `require_positive_bounded_u32` helper, the future M4
4328 /// per-Aplicacao Envoy config reconciler materialization pass, the
4329 /// future per-`:contratos`-edge breaker-override overlay the
4330 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4331 ///
4332 /// Prior to this lift the `.max_failures` field was accessed inline
4333 /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
4334 /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
4335 /// open-coded field-access that expressed no compile-time link back
4336 /// to the typed sub-struct axis. A future extension of the
4337 /// `:max-failures` axis to a richer author surface — a
4338 /// per-`:contratos`-edge breaker override the operator pins through a
4339 /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
4340 /// #3 roadmap acknowledges, a per-cluster max-failures-default
4341 /// overlay the M4 CR materializer resolves per-CR, a promotion of the
4342 /// plain `u32` trip count to a richer
4343 /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
4344 /// tuple once Envoy's `outlier_detection` block's peer axes come into
4345 /// scope, a per-Envoy-cluster minimum-request-volume gate before the
4346 /// count arms — would have had to be threaded through every open-
4347 /// coded copy in lockstep or the validate gate and the future M4
4348 /// emit path would silently disagree on which trip threshold a given
4349 /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
4350 /// would satisfy validate while the emit path silently read a drifted
4351 /// other value, or vice versa: a validated typed slot would land at
4352 /// the emit boundary as a no-op breaker whose trip threshold is
4353 /// structurally never reached). Lifting the resolution to a typed
4354 /// method on the substrate primitive means every downstream consumer
4355 /// of the Aplicacao's per-`:politicas :circuit-breaker`
4356 /// trip-threshold surface reaches for exactly one typed dispatch —
4357 /// the resolver's accept-set migrates as a unit on any future axis
4358 /// addition.
4359 ///
4360 /// First sub-struct scalar accessor on the M3 mesh-slot family
4361 /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
4362 /// scalar" projection pattern the sibling `CircuitBreaker::window` /
4363 /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
4364 /// closes the last unlifted per-`:politicas` scalar-value axis after
4365 /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
4366 /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
4367 /// Same "one typed dispatch on the substrate primitive, thin
4368 /// projections at each consumer" discipline the peer
4369 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
4370 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
4371 /// [`Membro::versao_requirement`] (a40b0e3),
4372 /// [`Entrada::destination`] (6db982c) accessors carry on their
4373 /// respective per-mesh-slot-atom scalar-value axes, extended onto the
4374 /// per-sub-struct required-`u32` axis. Named `max_failures()` to
4375 /// match the storage field's name; the accessor's identity maps onto
4376 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4377 /// docstring already carries.
4378 #[must_use]
4379 pub const fn max_failures(&self) -> u32 {
4380 self.max_failures
4381 }
4382
4383 /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
4384 /// Envoy-outlier-detection rolling-observation-interval scalar
4385 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4386 /// breaker rolling-window duration keys off — returns the
4387 /// author-declared `:politicas :circuit-breaker :window` typed
4388 /// `Duration` verbatim, copied out of the typed slot's own
4389 /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
4390 /// by value; no borrow of `&self` past the call). Non-optional (the
4391 /// surrounding `Option<CircuitBreaker>` is the "slot present?"
4392 /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
4393 /// `CircuitBreaker` past pattern-match is definitionally present,
4394 /// and its `:window` field carries the rolling-observation interval
4395 /// as a required-axis scalar).
4396 ///
4397 /// The `:politicas :circuit-breaker :window` axis carries the
4398 /// "consecutive-transient-failure rolling-observation interval"
4399 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
4400 /// `Duration` accept-set (zero-floor rejected through
4401 /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
4402 /// residue rejected through
4403 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
4404 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
4405 /// Envoy `outlier_detection.interval` per-cluster
4406 /// ejection-observation-interval scalar (equivalently the future
4407 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4408 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4409 /// consumer that reads the rolling-observation interval keys off
4410 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4411 /// integer-millisecond canonical-form + cap bracket at
4412 /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
4413 /// [`crate::render::require_positive_canonical_bounded_duration`]
4414 /// helper, the future M4 per-Aplicacao Envoy config reconciler
4415 /// materialization pass, the future per-`:contratos`-edge
4416 /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4417 /// acknowledges).
4418 ///
4419 /// Prior to this lift the `.window` field was accessed inline at
4420 /// one production site — [`AplicacaoSpec::validate_politicas`]'s
4421 /// `require_positive_canonical_bounded_duration(cb.window, …)`
4422 /// call — one open-coded field-access that expressed no compile-
4423 /// time link back to the typed sub-struct axis. A future extension
4424 /// of the `:window` axis to a richer author surface — a
4425 /// per-`:contratos`-edge window override the operator pins through
4426 /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
4427 /// #3 roadmap acknowledges, a per-cluster window-default overlay
4428 /// the M4 CR materializer resolves per-CR, a promotion of the plain
4429 /// `Duration` observation interval to a richer
4430 /// `{interval, base_ejection_time, max_ejection_percent}` tuple
4431 /// once Envoy's `outlier_detection` block's peer axes come into
4432 /// scope, a per-Envoy-cluster minimum-request-volume gate before
4433 /// the window arms — would have had to be threaded through every
4434 /// open-coded copy in lockstep or the validate gate and the future
4435 /// M4 emit path would silently disagree on which observation
4436 /// interval a given [`CircuitBreaker`] resolves to (an author's
4437 /// `:window "60s"` would satisfy validate while the emit path
4438 /// silently read a drifted other value, or vice versa: a validated
4439 /// typed slot would land at the emit boundary as a breaker whose
4440 /// observation window is structurally so wide that no realistic
4441 /// failure-rate shape can trip it). Lifting the resolution to a
4442 /// typed method on the substrate primitive means every downstream
4443 /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
4444 /// observation-window surface reaches for exactly one typed
4445 /// dispatch — the resolver's accept-set migrates as a unit on any
4446 /// future axis addition.
4447 ///
4448 /// Second sub-struct scalar accessor on the M3 mesh-slot family —
4449 /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
4450 /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
4451 /// required-axis, extended onto the per-sub-struct required-`Duration`
4452 /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
4453 /// axis. Same "one typed dispatch on the substrate primitive, thin
4454 /// projections at each consumer" discipline the peer
4455 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
4456 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
4457 /// [`Membro::versao_requirement`] (a40b0e3),
4458 /// [`Entrada::destination`] (6db982c) accessors carry on their
4459 /// respective per-mesh-slot-atom scalar-value axes, extended onto
4460 /// the per-sub-struct required-`Duration` axis. Named `window()` to
4461 /// match the storage field's name; the accessor's identity maps onto
4462 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4463 /// docstring already carries.
4464 #[must_use]
4465 pub const fn window(&self) -> Duration {
4466 self.window
4467 }
4468}
4469
4470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4471pub struct RateLimit {
4472 /// Requests per window.
4473 pub rate: u32,
4474 /// Window duration.
4475 pub window: Duration,
4476}
4477
4478impl RateLimit {
4479 /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
4480 /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
4481 /// every consumer of the Aplicacao's per-`:contratos`-edge
4482 /// rate-limit-bucket capacity keys off — returns the author-declared
4483 /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
4484 /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
4485 /// returns by value; no borrow of `&self` past the call). Non-optional
4486 /// (the surrounding `Option<RateLimit>` is the "slot present?"
4487 /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
4488 /// `RateLimit` past pattern-match is definitionally present, and its
4489 /// `:rate` field carries the token-bucket capacity as a required-axis
4490 /// scalar).
4491 ///
4492 /// The `:politicas :rate-limit` `:rate` axis carries the
4493 /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
4494 /// the typed slot's `u32` accept-set (zero-floor rejected through
4495 /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
4496 /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
4497 /// `local_rate_limit.token_bucket.max_tokens` per-cluster
4498 /// token-bucket-capacity scalar (equivalently the future
4499 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4500 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4501 /// consumer that reads the token-bucket capacity keys off this
4502 /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4503 /// cap bracket that gates on the canonical
4504 /// [`crate::render::require_positive_bounded_u32`] helper, the
4505 /// [`rate_limit_codec::render`] `Duration → unit` projection that
4506 /// emits the `<n>/<s|m|h>` author surface, the future M4
4507 /// per-Aplicacao Envoy config reconciler materialization pass, the
4508 /// future per-`:contratos`-edge rate-limit-override overlay the
4509 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4510 ///
4511 /// Prior to this lift the `.rate` field was accessed inline at three
4512 /// production sites — [`AplicacaoSpec::validate_politicas`]'s
4513 /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
4514 /// [`rate_limit_codec::render`] format-arm arms (canonical-window
4515 /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
4516 /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
4517 /// field-accesses that expressed no compile-time link back to the
4518 /// typed sub-struct axis. A future extension of the `:rate` axis
4519 /// to a richer author surface — a per-`:contratos`-edge rate
4520 /// override the operator pins through a future `:contratos :rate`
4521 /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
4522 /// per-cluster rate-default overlay the M4 CR materializer resolves
4523 /// per-CR, a promotion of the plain `u32` token capacity to a
4524 /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
4525 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
4526 /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
4527 /// before the token arms — would have had to be threaded through
4528 /// every open-coded copy in lockstep or the validate gate, the
4529 /// codec's render path, and the future M4 emit path would silently
4530 /// disagree on which token capacity a given [`RateLimit`] resolves
4531 /// to (an author's `:rate-limit "100/s"` would satisfy validate
4532 /// while the render / emit paths silently read a drifted other
4533 /// value, or vice versa: a validated typed slot would land at the
4534 /// emit boundary as a no-op limiter whose token capacity is
4535 /// structurally so high that no realistic per-edge traffic shape
4536 /// can drain it). Lifting the resolution to a typed method on the
4537 /// substrate primitive means every downstream consumer of the
4538 /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
4539 /// reaches for exactly one typed dispatch — the resolver's
4540 /// accept-set migrates as a unit on any future axis addition.
4541 ///
4542 /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
4543 /// in shape to the peer per-`CircuitBreaker`
4544 /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
4545 /// on the peer per-sub-struct required-axis, extended onto the
4546 /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
4547 /// required-axis scalar" projection pattern the sibling
4548 /// [`RateLimit::window`] future lift folds on. Same "one typed
4549 /// dispatch on the substrate primitive, thin projections at each
4550 /// consumer" discipline the peer [`WitContract::source`] /
4551 /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
4552 /// (0804823), [`Membro::nome`] (4a32abf),
4553 /// [`Membro::versao_requirement`] (a40b0e3),
4554 /// [`Entrada::destination`] (6db982c),
4555 /// [`CircuitBreaker::max_failures`] (3a74062),
4556 /// [`CircuitBreaker::window`] (373957f) accessors carry on their
4557 /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
4558 /// to match the storage field's name; the accessor's identity maps
4559 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4560 /// docstring already carries.
4561 #[must_use]
4562 pub const fn rate(&self) -> u32 {
4563 self.rate
4564 }
4565
4566 /// Substrate-canonical per-`:politicas :rate-limit` `:window`
4567 /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
4568 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4569 /// rate-limit-bucket refill period keys off — returns the
4570 /// author-declared `:politicas :rate-limit` typed `Duration`
4571 /// verbatim, copied out of the typed slot's own `Duration` storage
4572 /// (`Duration` is `Copy`, so the accessor returns by value; no
4573 /// borrow of `&self` past the call). Non-optional (the surrounding
4574 /// `Option<RateLimit>` is the "slot present?" projection at the
4575 /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
4576 /// pattern-match is definitionally present, and its `:window`
4577 /// field carries the token-bucket refill period as a required-axis
4578 /// scalar).
4579 ///
4580 /// The `:politicas :rate-limit` `:window` axis carries the
4581 /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
4582 /// — the typed slot's `Duration` accept-set (constrained to the
4583 /// three canonical windows `{1s, 60s, 3600s}` the
4584 /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
4585 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
4586 /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
4587 /// per-cluster token-bucket-refill-period scalar (equivalently the
4588 /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4589 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4590 /// consumer that reads the token-bucket refill period keys off
4591 /// this scalar (the [`AplicacaoSpec::validate_politicas`]
4592 /// canonical-window gate that keys off
4593 /// [`is_canonical_rate_limit_window`], the
4594 /// [`rate_limit_codec::render`] `Duration → unit` projection that
4595 /// emits the `<n>/<s|m|h>` author surface — canonical arm via
4596 /// [`rate_limit_window_unit`] and non-canonical fallback via
4597 /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
4598 /// reconciler materialization pass, the future per-`:contratos`-
4599 /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
4600 /// roadmap acknowledges).
4601 ///
4602 /// Prior to this lift the `.window` field was accessed inline at
4603 /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
4604 /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
4605 /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
4606 /// error-payload construction on refusal, and the two
4607 /// [`rate_limit_codec::render`] arms
4608 /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
4609 /// and non-canonical-window `rl.window.as_secs()` fallback). Three
4610 /// open-coded field-accesses that expressed no compile-time link
4611 /// back to the typed sub-struct axis. A future extension of the
4612 /// `:window` axis to a richer author surface — a per-`:contratos`-
4613 /// edge window override the operator pins through a future
4614 /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
4615 /// acknowledges, a per-cluster window-default overlay the M4 CR
4616 /// materializer resolves per-CR, a promotion of the plain
4617 /// `Duration` refill period to a richer
4618 /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
4619 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
4620 /// axis comes into scope, an addition of a `"d"` day suffix once
4621 /// Envoy's `rate_limit_action` grows daily-bucket support — would
4622 /// have had to be threaded through every open-coded copy in
4623 /// lockstep or the validate gate, the codec's render path, and
4624 /// the future M4 emit path would silently disagree on which
4625 /// refill period a given [`RateLimit`] resolves to (an author's
4626 /// `:rate-limit "100/s"` would satisfy validate while the render
4627 /// / emit paths silently read a drifted other value, or vice
4628 /// versa: a validated typed slot would land at the emit boundary
4629 /// as a limiter whose refill period is structurally so long that
4630 /// no realistic per-edge traffic shape stays inside the token
4631 /// budget). Lifting the resolution to a typed method on the
4632 /// substrate primitive means every downstream consumer of the
4633 /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
4634 /// reaches for exactly one typed dispatch — the resolver's
4635 /// accept-set migrates as a unit on any future axis addition.
4636 ///
4637 /// Second sub-struct scalar accessor on the `RateLimit` axis —
4638 /// sibling in shape to the just-landed [`RateLimit::rate`]
4639 /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
4640 /// required-axis, extended onto the per-sub-struct
4641 /// required-`Duration` axis; closes the last unlifted
4642 /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
4643 /// per-sub-struct accessor coverage is now complete across both
4644 /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
4645 /// the substrate primitive, thin projections at each consumer"
4646 /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
4647 /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
4648 /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
4649 /// (7f0fd43), [`WitContract::world_ref`] (0804823),
4650 /// [`Membro::nome`] (4a32abf),
4651 /// [`Membro::versao_requirement`] (a40b0e3),
4652 /// [`Entrada::destination`] (6db982c) accessors carry on their
4653 /// respective per-mesh-slot-atom scalar-value axes. Named
4654 /// `window()` to match the storage field's name; the accessor's
4655 /// identity maps onto the canonical MESH-COMPOSITION §III.2
4656 /// vocabulary the slot's docstring already carries.
4657 #[must_use]
4658 pub const fn window(&self) -> Duration {
4659 self.window
4660 }
4661
4662 /// Recognize this rate-limit's `:window` as a canonical
4663 /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
4664 /// exactly matches one of the three closed-set arm-Durations
4665 /// (`1s` / `60s` / `3600s`), `None` when the window carries a
4666 /// non-canonical magnitude the codec's round-trip would break on
4667 /// (sub-second residue, or a second-magnitude outside the set
4668 /// [`RateLimitUnit::ALL`] enumerates).
4669 ///
4670 /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
4671 /// returns `Some` here — the validate gate's
4672 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
4673 /// rejects every window this accessor returns `None` on. Downstream
4674 /// consumers past validate (the codec's [`rate_limit_codec::render`]
4675 /// path, the future M4 per-Aplicacao Envoy config reconciler's
4676 /// materialization pass, the future per-`:contratos`-edge rate-limit-
4677 /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4678 /// acknowledges) that read the typed unit off a validated slot can
4679 /// pattern-match on the returned `Some` without re-checking
4680 /// canonicality at the consumer layer — the typed enum surface is
4681 /// the load-bearing carrier of the canonicality invariant.
4682 ///
4683 /// Preferred over the free [`is_canonical_rate_limit_window`]
4684 /// module-private helper at any call site that has the typed
4685 /// [`RateLimit`] in hand (the codec's `render` arm at
4686 /// [`rate_limit_codec::render`], the validate gate's canonical-form
4687 /// arm in [`AplicacaoSpec::validate_politicas`], any future
4688 /// per-`:contratos` edge-override overlay resolver): those consumers
4689 /// reach for the typed enum without going through the
4690 /// `.window()` scalar-projection layer, and get the enum value
4691 /// directly (which the codec's render arm can then format via
4692 /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
4693 /// "typed sub-struct scalar accessor, one dispatch on the substrate
4694 /// primitive" discipline the sibling [`RateLimit::rate`] and
4695 /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
4696 /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
4697 /// projection axis (the third scalar accessor on the [`RateLimit`]
4698 /// axis, first typed-enum-return projection).
4699 ///
4700 /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
4701 /// the canonical [`RateLimitUnit`] arm now carries the same
4702 /// `const`-eval-surface posture the sibling `pub const fn`
4703 /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
4704 /// this typed sub-struct already carry, composing through the
4705 /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
4706 /// reverse-resolver in `const` context. Any downstream substrate-
4707 /// side `const`-context consumer of the typed unit (a module-scope
4708 /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
4709 /// invariant pin on a typed fixture, a future M4 admission-webhook
4710 /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
4711 /// resolver over a typed [`RateLimit`], any future `const fn`
4712 /// per-`:contratos`-edge rate-limit-override overlay resolver over
4713 /// the substrate primitive) now reaches the same typed dispatch on
4714 /// the substrate primitive at const-eval time as at runtime.
4715 ///
4716 /// Pinned load-bearing at the substrate-primitive level by
4717 /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
4718 /// eval-surface pin via `const fn` wrapper).
4719 #[must_use]
4720 pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
4721 RateLimitUnit::from_window(self.window)
4722 }
4723}
4724
4725/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
4726/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
4727/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
4728///
4729/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
4730/// the `:politicas :rate-limit` unit surface reads from
4731/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
4732/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
4733/// [`is_canonical_rate_limit_window`] predicate the
4734/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
4735/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
4736/// projection) now lives inside this typed enum's `match self` arms — a
4737/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
4738/// `rate_limit_action` grows daily-bucket support) is one new variant
4739/// plus the exhaustiveness arms on the four methods, so every consumer
4740/// picks it up by compile-time construction rather than a runtime
4741/// table-scan miss.
4742///
4743/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
4744/// scanned via `find_map` at every projection call — an untyped runtime
4745/// walk that carried no compile-time link between the parse arm's
4746/// accepted suffixes, the render arm's emitted suffixes, and the
4747/// validate gate's accepted windows. A future rate-limit-unit addition
4748/// that landed one row without threading through the other consumers
4749/// (or a copy-paste flip that collapsed two rows onto one suffix) would
4750/// silently split the accepted-set across the three consumers — the
4751/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
4752/// for a 24h window that parse can't round-trip, the validate gate
4753/// misses one canonical window. Lifting the pairs onto a typed
4754/// closed-set enum with exhaustive `match` arms makes any such
4755/// half-landed extension a caixa-core build error (the compiler enforces
4756/// arm coverage on every method), not a silent per-consumer drift
4757/// surfacing at apply time. Same "closed-set typed-enum discriminator"
4758/// discipline the sibling [`PlacementStrategy`] (cc8f749),
4759/// [`crate::supervisor::RestartStrategy`],
4760/// [`crate::supervisor::RestartPolicy`],
4761/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
4762/// closed-set typed enums carry on their respective closed-set axes —
4763/// extended onto the seventh closed-set typed-enum discriminator axis
4764/// on the caixa typed surface (the `:politicas :rate-limit :window`
4765/// canonical-unit axis).
4766#[derive(
4767 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4768)]
4769pub enum RateLimitUnit {
4770 /// 1-second window — canonical author-surface suffix `"s"`
4771 /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4772 /// with a 1s magnitude.
4773 Second,
4774 /// 1-minute window — canonical author-surface suffix `"m"`
4775 /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4776 /// with a 60s magnitude.
4777 Minute,
4778 /// 1-hour window — canonical author-surface suffix `"h"`
4779 /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4780 /// with a 3600s magnitude.
4781 Hour,
4782}
4783
4784impl RateLimitUnit {
4785 /// Exhaustive iteration surface for every consumer that reads the
4786 /// full canonical-unit set (the byte-parity witness against the
4787 /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
4788 /// webhook's accepted-suffix listing in its rejection body, any
4789 /// future round-trip fuzz harness). A future variant addition to
4790 /// [`RateLimitUnit`] extends this slice as a single edit and every
4791 /// consumer picks up the new entry by construction — the compiler-
4792 /// checked exhaustiveness on the sibling method `match` arms is the
4793 /// build-time guarantee that no arm forgets to grow.
4794 pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
4795
4796 /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
4797 /// string every `<n>/<unit>` rate-limit shape carries after its
4798 /// `/` separator. The single source of truth the codec's parse and
4799 /// render arms both dispatch on: the parse arm matches an incoming
4800 /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
4801 /// output; the render arm emits the entry's `as_suffix` verbatim
4802 /// after the rate magnitude.
4803 #[must_use]
4804 pub const fn as_suffix(self) -> &'static str {
4805 match self {
4806 Self::Second => "s",
4807 Self::Minute => "m",
4808 Self::Hour => "h",
4809 }
4810 }
4811
4812 /// Canonical `Duration` for this unit — the token-bucket refill
4813 /// period the [`RateLimit::window`] axis carries when the surrounding
4814 /// slot's `:rate-limit` author surface named this unit.
4815 #[must_use]
4816 pub const fn window(self) -> Duration {
4817 Duration::from_secs(match self {
4818 Self::Second => 1,
4819 Self::Minute => 60,
4820 Self::Hour => 3_600,
4821 })
4822 }
4823
4824 /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
4825 /// `None` when `suffix` is outside the closed-set arm-string set
4826 /// [`Self::as_suffix`] emits. The single `str → Self` projection
4827 /// [`rate_limit_codec::parse`] consumes.
4828 #[must_use]
4829 pub fn from_suffix(suffix: &str) -> Option<Self> {
4830 Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
4831 }
4832
4833 /// Recognize a canonical rate-limit `Duration` as one of the three
4834 /// arms, or `None` when `window` carries sub-second residue or a
4835 /// second-magnitude outside the closed-set arm-window set
4836 /// [`Self::window`] emits. The single `Duration → Self` projection
4837 /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
4838 /// both consume.
4839 ///
4840 /// `pub const fn` — the reverse `Duration → Self` projection now
4841 /// carries the same `const`-eval-surface posture the sibling
4842 /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
4843 /// projection accessors on this closed-set typed enum already
4844 /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
4845 /// typed-`RateLimit`-projection sibling composes through in `const`
4846 /// context. Routes byte-for-byte through the peer `pub const fn`
4847 /// [`Self::window`] canonical-`Duration` projection so any future
4848 /// arm-magnitude edit on the sibling accessor reaches this reverse
4849 /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
4850 /// per-arm probes each dispatch through one `pub const fn` on the
4851 /// substrate primitive rather than a hand-authored per-arm second-
4852 /// magnitude literal that would silently drift on any future
4853 /// [`Self::window`] arm-magnitude edit.
4854 ///
4855 /// Prior to the `const` lift the body dispatched through
4856 /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
4857 /// iterator-driven linear scan whose iterator methods
4858 /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
4859 /// `PartialEq` dispatch each carry non-`const` bounds on stable
4860 /// Rust 1.94, so any downstream substrate-side `const`-context
4861 /// consumer of the reverse resolver (a module-scope
4862 /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
4863 /// invariant pin on a typed fixture, a future M4
4864 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
4865 /// webhook `const fn` per-`:politicas` canonical-window floor over a
4866 /// typed [`RateLimit`] scalar, any future `const fn`
4867 /// per-`:contratos`-edge rate-limit-override overlay resolver over
4868 /// the substrate primitive that wants to fan on the canonical unit
4869 /// at compile time) surfaced as a downstream E0015 far from the
4870 /// resolver's own declaration. The `pub const fn` posture closes
4871 /// the drift structurally at caixa-core build time.
4872 ///
4873 /// Pinned load-bearing at the substrate-primitive level by
4874 /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
4875 /// eval-surface pin via `const fn` wrapper) and
4876 /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
4877 /// (composition-witness pin against the peer `Self::window` scalar
4878 /// dispatch).
4879 #[must_use]
4880 pub const fn from_window(window: Duration) -> Option<Self> {
4881 if window.subsec_nanos() != 0 {
4882 return None;
4883 }
4884 // Route through the peer `pub const fn` [`Self::window`]
4885 // canonical-`Duration` projection so any future arm-magnitude
4886 // edit on the sibling accessor reaches this reverse resolver by
4887 // construction — the per-arm `secs` comparison keys off
4888 // `Duration::as_secs` (`pub const fn`), not a hand-authored
4889 // per-arm second-magnitude literal that would silently drift.
4890 let secs = window.as_secs();
4891 if secs == Self::Second.window().as_secs() {
4892 Some(Self::Second)
4893 } else if secs == Self::Minute.window().as_secs() {
4894 Some(Self::Minute)
4895 } else if secs == Self::Hour.window().as_secs() {
4896 Some(Self::Hour)
4897 } else {
4898 None
4899 }
4900 }
4901
4902 /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
4903 /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
4904 /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
4905 /// single `&str → Duration` projection [`rate_limit_codec::parse`]
4906 /// consumes.
4907 ///
4908 /// The peer `Duration → &'static str` axis folded onto the substrate
4909 /// primitive [`RateLimit::canonical_unit`] typed accessor once both
4910 /// production consumers ([`rate_limit_codec::render`] and
4911 /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
4912 /// migrated (61421a6): the free helper's `Duration → &str` projection
4913 /// is now the two-step composition
4914 /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
4915 /// reads through the typed accessor. This lift closes the peer
4916 /// `&str → Duration` axis by folding the vestigial module-private
4917 /// `rate_limit_window_from_unit` delegate onto this associated method
4918 /// — the codec's parse arm and every future wire-side consumer of the
4919 /// `&str → Duration` projection (a future admission-webhook that
4920 /// reads a `:rate-limit` shape off a CR spec's `raw string` value
4921 /// before it's promoted to a validated typed slot, a future
4922 /// `feira lint` shape-probe that reads the author-surface bytes
4923 /// verbatim) now reach for exactly one typed dispatch on the
4924 /// substrate primitive.
4925 ///
4926 /// Same "closed-set typed-enum discriminator with canonical
4927 /// projections per axis" discipline the sibling [`Self::as_suffix`]
4928 /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
4929 /// methods carry — this associated method closes the fifth (and last
4930 /// unlifted) projection axis on the arm-table, so the closed-set enum
4931 /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
4932 /// consumer of the `:politicas :rate-limit :window` axis reaches
4933 /// through. A future rate-limit-unit addition (a `"d"` day suffix
4934 /// once Envoy's `rate_limit_action` grows daily-bucket support, a
4935 /// `"ms"` sub-second window once high-throughput per-edge policies
4936 /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
4937 /// variant plus one arm per method — the compiler enforces
4938 /// exhaustiveness on every consumer's `match self` arms and picks
4939 /// the new unit up by construction across all five projections.
4940 #[must_use]
4941 pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
4942 Self::from_suffix(suffix).map(Self::window)
4943 }
4944}
4945
4946/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
4947/// every consumer that formats a canonical rate-limit unit as user-
4948/// facing text (future M4 admission-webhook rejection bodies naming
4949/// the accepted-suffix set, future `feira app graph` per-`:politicas`
4950/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
4951/// codec's parse arm accepts and the render arm emits. Same
4952/// as_str-through-Display convergence discipline the sibling
4953/// [`PlacementStrategy`], [`crate::CaixaKind`],
4954/// [`crate::supervisor::RestartStrategy`], and
4955/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
4956impl std::fmt::Display for RateLimitUnit {
4957 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4958 f.write_str(self.as_suffix())
4959 }
4960}
4961
4962/// Substrate-canonical [`AsRef<str>`] projection on the M3
4963/// `:politicas :rate-limit` closed-set typed unit-suffix enum —
4964/// routes through the same [`RateLimitUnit::as_suffix`] `pub const fn`
4965/// scalar accessor the paired [`std::fmt::Display`] impl already
4966/// delegates through, so any future consumer that binds a
4967/// [`RateLimitUnit`] through the standard-library `impl AsRef<str>`
4968/// bound (a [`std::process::Command::arg`] shell-out that composes the
4969/// canonical suffix into an Envoy sidecar config-CLI's per-`:politicas`
4970/// `--rate-limit-unit <s|m|h>` arg on the future
4971/// `CiliumClusterwideEnvoyConfig` overlay MESH-COMPOSITION §III.2 #3
4972/// names, a `tracing::field::Value::Str`-arm structured-log recorder
4973/// on the future `app-operator`'s per-`:politicas :rate-limit`
4974/// reconcile step, a [`std::collections::HashMap`] lookup keyed on
4975/// the canonical suffix through `map.get::<str>(unit.as_ref())` on a
4976/// future per-unit token-bucket-refill dispatch table the future M4
4977/// admission-webhook rejection body composes) reaches the paired
4978/// `"s"` / `"m"` / `"h"` byte-string through one substrate-primitive
4979/// dispatch rather than an open-coded `.as_suffix()` re-inlining at
4980/// every wire-up.
4981///
4982/// Deliberately routes through the canonical suffix axis, not the
4983/// second-magnitude [`RateLimitUnit::window`] axis — `AsRef<str>` and
4984/// [`fmt::Display`] land on the same author-surface-canonical byte-
4985/// string the codec's parse and render arms both dispatch on, while
4986/// the token-bucket-refill period stays reachable only through the
4987/// explicit [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`]
4988/// paths.
4989///
4990/// Same "route the trait impl through the substrate-primitive
4991/// accessor" discipline the sibling [`crate::CaixaVersion`]
4992/// [`AsRef<str>`] impl (16d5c7e), the paired M2
4993/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
4994/// (63eb1a4), the paired M2 [`crate::supervisor::RestartPolicy`]
4995/// [`AsRef<str>`] impl (419ea81), the M3
4996/// [`PlacementStrategy`] [`AsRef<str>`] impl (d86edd2), and the
4997/// top-level [`crate::CaixaKind`] [`AsRef<str>`] impl (cd2091f) carry
4998/// — closes the substrate primitive's [`AsRef<str>`] projection axis
4999/// onto the last remaining closed-set typed enum with a
5000/// [`fmt::Display`] surface, so every closed-set typed enum / newtype
5001/// on the caixa surface (top-level `:kind`, both M2
5002/// `:supervisor`-slot per-child and sibling-restart typed enums, the
5003/// M3 `:placement :estrategia` typed enum, the M3
5004/// `:politicas :rate-limit` unit-suffix typed enum, and the `:versao`
5005/// typed newtype) now carries the paired [`AsRef<str>`] +
5006/// [`fmt::Display`] + `as_*` triple through one lifted-const family.
5007///
5008/// Pinned load-bearing by
5009/// [`tests::rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor`]
5010/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
5011/// three-arm closed set) and
5012/// [`tests::rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor`]
5013/// (three-path convergence: `AsRef<str>` + `Display` + `as_suffix`
5014/// all resolve to the same byte-string per arm) — any future silent
5015/// detour that routes the impl through a divergent projection (a
5016/// per-arm inline `match self { … }` re-inlining that opens a compile-
5017/// time link to the un-lifted arm-literal, a swap onto the
5018/// second-magnitude [`RateLimitUnit::window`] axis that would collide
5019/// the canonical-suffix / token-bucket-refill two-axis split) trips at
5020/// caixa-core test time under `assert_eq!` rather than at a downstream
5021/// `impl AsRef<str>`-bound consumer's silent split.
5022impl AsRef<str> for RateLimitUnit {
5023 fn as_ref(&self) -> &str {
5024 self.as_suffix()
5025 }
5026}
5027
5028/// Trait-idiomatic reverse projection on the M3-mesh-primitive-defining
5029/// [`RateLimitUnit`] closed-set typed enum — routes byte-for-byte through
5030/// the paired substrate-primitive [`RateLimitUnit::from_suffix`]
5031/// `Option<Self>` accessor so every future consumer that binds a
5032/// canonical `:politicas :rate-limit` unit-suffix byte-string through the
5033/// standard-library `.try_into()` / [`TryFrom`] axis (a future
5034/// `feira app policy --rate-limit-unit <s|m|h>` CLI arg-parse that
5035/// composes into `let unit: RateLimitUnit = s.try_into()?`, a future
5036/// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook that folds a
5037/// `spec.politicas.rateLimit.unit: String` field through
5038/// `RateLimitUnit::try_from(&s)?`, a generic `<T: TryFrom<&str>>`-bound
5039/// loader over any of the substrate's closed-set typed enums) reaches
5040/// the same three-arm accept-set the sibling
5041/// [`RateLimitUnit::from_suffix`] resolver parses through and the sibling
5042/// [`RateLimitUnit::as_suffix`] emits, rather than an open-coded per-arm
5043/// `match s { "s" => …, "m" => …, "h" => …, _ => … }` cascade whose
5044/// arm-set has no compile-time link back to the substrate primitive.
5045///
5046/// Complements the pre-existing forward-projection triple
5047/// ([`std::fmt::Display`], [`AsRef<str>`], [`RateLimitUnit::as_suffix`])
5048/// with the paired trait-idiomatic reverse-projection axis: Rust-side
5049/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
5050/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so
5051/// a caller who can project *out to* a `&str` can also project *in
5052/// from* one. The [`TryFrom<&str>`] axis is deliberately chosen over
5053/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
5054/// lint the sibling method-named [`RateLimitUnit::from_suffix`] would
5055/// trigger under a `FromStr` impl (the same design tradeoff the peer
5056/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
5057/// [`PlacementStrategy`] (6fd00cd), [`crate::supervisor::RestartStrategy`]
5058/// (5b828ed), [`crate::supervisor::RestartPolicy`] (6fdd0d9), and
5059/// [`WitShape`] (5472902) blocks note) — this impl closes the trait-
5060/// idiomatic reverse axis without disturbing the method-named
5061/// `from_suffix` shape the peer closed-set typed enums already carry.
5062///
5063/// `type Error = ()` matches the sibling [`RateLimitUnit::from_suffix`]'s
5064/// `Option<Self>` return-shape's deliberate deferral of error typing:
5065/// the caller picks the diagnostic form appropriate for its use site (a
5066/// future `feira app policy --rate-limit-unit` arg-parse composes its
5067/// own per-verb "unknown rate-limit unit: <arg> — accepted: {…}"
5068/// message enumerating [`RateLimitUnit::ALL`], a future M4 admission-
5069/// webhook rejection body wraps the `Err(())` outcome with the accepted-
5070/// set enumeration for operator diagnostics, a `Result::map_err` at the
5071/// call site lifts the unit-error to a per-verb error type). Same shape
5072/// the peer sibling reverse-projection axes carry.
5073///
5074/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
5075/// set the [`RateLimitUnit::from_suffix`] resolver dispatches through,
5076/// so any future arm addition (a `"d"` day suffix once Envoy's
5077/// `rate_limit_action` grows daily-bucket support, a `"ms"` sub-second
5078/// window once high-throughput per-edge policies come into scope per
5079/// MESH-COMPOSITION §III.2 #3 — both trajectory items the sibling
5080/// [`RateLimitUnit::window_from_suffix`] doc block already names) grows
5081/// the trait-idiomatic axis by construction — one caixa-core edit on
5082/// [`RateLimitUnit::from_suffix`] extends both the method-named reverse
5083/// projection every existing consumer keys off and the trait-idiomatic
5084/// reverse projection this impl exposes, without a coordinated rewrite
5085/// across every future `TryFrom<&str>`-bound consumer's arm-set.
5086///
5087/// Extends the substrate-wide closed-set-enum trait-idiomatic reverse-
5088/// projection family ([`crate::CaixaKind`] via 3c83606,
5089/// [`crate::CaixaDialeto`] via bf33136, [`PlacementStrategy`] via
5090/// 6fd00cd, [`crate::supervisor::RestartStrategy`] via 5b828ed,
5091/// [`crate::supervisor::RestartPolicy`] via 6fdd0d9, [`WitShape`] via
5092/// 5472902) onto the third M3-mesh-primitive-defining slot enum on the
5093/// caixa surface — the `:politicas :rate-limit` unit-suffix closed set
5094/// the caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
5095/// `local_rate_limit.token_bucket.fill_interval` overlay emission, and
5096/// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-
5097/// webhook's per-`:politicas` accept-set validation.
5098///
5099/// Pinned load-bearing by
5100/// [`tests::rate_limit_unit_try_from_str_routes_through_from_suffix_accessor`]
5101/// (byte-parity pin against [`RateLimitUnit::from_suffix`] across the
5102/// three-arm accept-set) and
5103/// [`tests::rate_limit_unit_try_from_str_rejects_unknown_byte_strings`]
5104/// (rejection witness against silent accept-set widening).
5105impl TryFrom<&str> for RateLimitUnit {
5106 type Error = ();
5107
5108 fn try_from(s: &str) -> Result<Self, Self::Error> {
5109 Self::from_suffix(s).ok_or(())
5110 }
5111}
5112
5113/// Standard-library trait-idiomatic forward projection on the
5114/// [`RateLimitUnit`] closed-set typed enum. Routes byte-for-byte through
5115/// the paired substrate-primitive [`RateLimitUnit::as_suffix`]
5116/// `pub const fn` accessor so `<&'static str>::from(unit)` /
5117/// `unit.into::<&'static str>()` reaches the same three-arm `"s"` /
5118/// `"m"` / `"h"` canonical-suffix emit-set the sibling method-named
5119/// accessor dispatches through and the sibling
5120/// [`std::fmt::Display for RateLimitUnit`] / [`AsRef<str> for RateLimitUnit`]
5121/// impls also route through.
5122///
5123/// Extends the substrate-wide closed-set-enum trait-idiomatic
5124/// forward-projection family
5125/// ([`crate::supervisor::RestartStrategy`] via 523157d,
5126/// [`crate::supervisor::RestartPolicy`] via 9fb37d0,
5127/// [`crate::CaixaKind`] via edb827b,
5128/// [`crate::CaixaDialeto`] via c189a6f,
5129/// [`PlacementStrategy`] via afa3562,
5130/// [`WitShape`] via 56998ec) onto the third
5131/// M3-mesh-primitive-defining slot enum on the caixa surface — the
5132/// `:politicas :rate-limit` canonical-unit-suffix closed set the
5133/// caixa-mesh renderer keys off end-to-end for per-Aplicacao Envoy
5134/// `local_rate_limit.token_bucket.fill_interval` overlay emission.
5135/// Pairs with the sibling [`TryFrom<&str> for RateLimitUnit`] impl
5136/// (bf78400) to close the two-way `Self ↔ &'static str` round-trip on
5137/// the trait-idiomatic axis pair, mirroring the pre-existing
5138/// method-named [`RateLimitUnit::as_suffix`] +
5139/// [`RateLimitUnit::from_suffix`] pair on the substrate-primitive axis
5140/// pair.
5141///
5142/// Return type is `&'static str` by construction — every
5143/// [`RateLimitUnit::as_suffix`] arm resolves to an inline
5144/// `"s"` / `"m"` / `"h"` `&'static str` literal, so the trait's
5145/// return-type promise is upheld structurally without a
5146/// [`String::leak`] cast or a per-arm inline literal outside the paired
5147/// [`RateLimitUnit::as_suffix`] dispatch.
5148///
5149/// Deliberately routes through the canonical-suffix axis, not the
5150/// second-magnitude [`RateLimitUnit::window`] axis — every closed-set
5151/// forward-projection path on the caixa surface lands on the same
5152/// author-surface-canonical byte-string the codec's parse and render
5153/// arms both dispatch on, while the token-bucket-refill period stays
5154/// reachable only through the explicit [`RateLimitUnit::window`] /
5155/// [`RateLimitUnit::from_window`] paths.
5156///
5157/// The paired [`RateLimitUnit::as_suffix`] accessor's three-arm emit-set
5158/// is the single source of truth — every future arm addition (a `"d"`
5159/// day suffix once Envoy's `rate_limit_action` grows daily-bucket
5160/// support, a `"ms"` sub-second window once high-throughput per-edge
5161/// policies come into scope per MESH-COMPOSITION §III.2 #3 — both
5162/// trajectory items the sibling [`RateLimitUnit::window_from_suffix`]
5163/// doc block already names) grows the trait-idiomatic forward axis by
5164/// construction: one caixa-core edit on [`RateLimitUnit::as_suffix`]
5165/// extends every one of the sibling forward-projection paths
5166/// ([`std::fmt::Display`], [`AsRef<str>`], [`RateLimitUnit::as_suffix`]
5167/// itself, and this [`From<Self> for &'static str`]) without a
5168/// coordinated rewrite across every future `Into<&'static str>`-bound
5169/// consumer's arm-set.
5170///
5171/// Pinned load-bearing by
5172/// [`tests::rate_limit_unit_from_into_static_str_routes_through_as_suffix_accessor`]
5173/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
5174/// three-arm emit-set, plus a `const`-context materialization witness
5175/// for the `&'static str` lifetime promise routed through the paired
5176/// [`RateLimitUnit::as_suffix`] `pub const fn` accessor, plus a paired
5177/// `.into()` shape assertion covering the blanket-derived
5178/// `Into<&'static str>` shape) and
5179/// [`tests::rate_limit_unit_from_into_static_str_and_as_suffix_partition_the_emit_set`]
5180/// (partition pin asserting `<&'static str as
5181/// From<RateLimitUnit>>::from` and [`RateLimitUnit::as_suffix`] agree on
5182/// every arm, plus a two-way direct round-trip witness through the
5183/// paired trait-idiomatic [`TryFrom<&str>`] axis that closes the
5184/// two-way `Self ↔ &'static str` round-trip on the trait-idiomatic axis
5185/// pair — the emit-side [`RateLimitUnit::as_suffix`] and the parse-side
5186/// [`RateLimitUnit::from_suffix`] dispatch on the same three inline
5187/// canonical-suffix byte-strings by construction, so round-tripping
5188/// composes the two trait impls directly).
5189impl From<RateLimitUnit> for &'static str {
5190 fn from(unit: RateLimitUnit) -> &'static str {
5191 unit.as_suffix()
5192 }
5193}
5194
5195/// Upper-bound ceiling on the `:politicas :timeout` axis — every
5196/// validated [`MeshPolicy::timeout`] past
5197/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
5198/// (inclusive on both ends, integer-millisecond magnitudes by the
5199/// canonical-form gate immediately preceding).
5200///
5201/// The typed field is `Option<Duration>` (the zero-floor arm
5202/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
5203/// `Duration::ZERO`, and the canonical-form arm
5204/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
5205/// sub-millisecond residue), so a programmatic struct literal
5206/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
5207/// 24h) and the equivalent author-surface form
5208/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
5209/// integer-hour magnitude) both round-trip cleanly through serde — a
5210/// structurally unbounded `Duration` ceiling. A `:timeout` value far
5211/// above the documented production-playbook band (Envoy default `15s`,
5212/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
5213/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
5214/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
5215/// at `~3600s`) silently degenerates the mesh-policy contract: the
5216/// per-call deadline is structurally so long that no realistic
5217/// synchronous-`:contratos` traversal can reach it, so the typed slot
5218/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
5219/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
5220/// blocking" degenerates to a nominal-only contract on the
5221/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
5222/// the sibling `:politicas :retries` axis and the
5223/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
5224/// `:politicas :circuit-breaker :max-failures` axis — all three close
5225/// the "structurally unbounded ceiling on a typed `:politicas` axis"
5226/// footgun the prior zero-floor-and-canonical-form-only checks left
5227/// open.
5228///
5229/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
5230/// shared duration codec emits (`"<n>h"` for any integer-hour
5231/// magnitude) — every value in the canonical authoring form's
5232/// `<integer><unit>` grammar at or below this cap renders to a clean
5233/// canonical string. The cap sits an order of magnitude above every
5234/// documented production-playbook recommendation band (Envoy default
5235/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
5236/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
5237/// configured maximum (`proxy_read_timeout` typical max `3600s`),
5238/// below the clearly-pathological "effectively no timeout" floor
5239/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
5240/// want for a long-running synchronous workflow, but a hard wall above
5241/// which the mesh-level deadline is structurally a non-deadline.
5242/// Lifted as a typed `pub const` so the bound has exactly one source
5243/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5244/// materializer's admission webhook and the caixa-mesh-side
5245/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
5246/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
5247/// other typed upper bound in this crate carries
5248/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
5249/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5250/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5251/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5252pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
5253
5254/// Upper-bound ceiling on the `:politicas :retries` axis — every
5255/// validated [`MeshPolicy::retries`] past
5256/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
5257///
5258/// The typed slot is `Option<u32>` (`None` = no retries on transient
5259/// failure; `Some(0)` already rejected by the
5260/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
5261/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
5262/// .. }`) and the equivalent author-surface form
5263/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
5264/// serde / the codec — a structurally unbounded `u32` ceiling. The
5265/// runtime substrate that consumes the value (Envoy's
5266/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
5267/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
5268/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
5269/// admission cap is 10) translates a four-billion-retry policy into a
5270/// thundering-herd amplification vector on transient failure — the
5271/// caller's one request fans out to `retries` server-side calls per
5272/// edge per traversal, multiplying load by `(retries+1)^depth` across
5273/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
5274/// invariant "no infinite blocking" pairs with a no-runaway-amplification
5275/// invariant on the retry axis; both belong at the typed-slot layer.
5276///
5277/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
5278/// upstream mesh-policy schema that documents one) and sits above the
5279/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
5280/// every documented production playbook): a value the author can
5281/// plausibly want, but a hard wall above which the policy is
5282/// structurally a footgun. Lifted as a typed `pub const` so the bound
5283/// has exactly one source of truth — a future axis reaching for the
5284/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5285/// materializer's admission webhook, the caixa-mesh-side
5286/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
5287/// one place. Same shape every other typed upper bound in this crate
5288/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5289/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5290/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
5291/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5292pub const POLICY_RETRIES_MAX: u32 = 10;
5293
5294/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
5295/// axis — every validated [`CircuitBreaker::max_failures`] past
5296/// [`AplicacaoSpec::validate_politicas`] lies in
5297/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
5298///
5299/// The typed field is `u32` (the zero-floor arm
5300/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
5301/// `0` — a breaker that trips on the first call), so a programmatic
5302/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
5303/// and the equivalent author-surface form
5304/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
5305/// cleanly through serde — a structurally unbounded `u32` ceiling. A
5306/// `max_failures` value far above the documented production-playbook
5307/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
5308/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
5309/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
5310/// typical 5–50) silently disables the breaker's protection role:
5311/// the threshold is structurally so high that no realistic
5312/// failures-per-`:window` traffic shape can reach it, so the breaker
5313/// never trips and the typed slot becomes a no-op carried on every
5314/// emitted Envoy / Cilium L7 overlay. Pairs with the
5315/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
5316/// axis — both close the "structurally unbounded `u32` ceiling on a
5317/// typed policy axis" footgun the prior zero-floor-only checks left
5318/// open.
5319///
5320/// The `1000` ceiling sits an order of magnitude above every
5321/// documented upstream production-playbook recommendation band (the
5322/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
5323/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
5324/// the clearly-pathological "effectively no protection"
5325/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
5326/// plausibly want at hyperscale, but a hard wall above which the
5327/// policy is structurally a no-op. Lifted as a typed `pub const` so
5328/// the bound has exactly one source of truth — the future M4
5329/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
5330/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
5331/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
5332/// one place. Same shape every other typed upper bound in this crate
5333/// carries ([`POLICY_RETRIES_MAX`],
5334/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5335/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5336/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5337pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
5338
5339/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
5340/// every validated [`CircuitBreaker::window`] past
5341/// [`AplicacaoSpec::validate_politicas`] lies in
5342/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
5343/// integer-millisecond magnitudes by the canonical-form gate
5344/// immediately preceding).
5345///
5346/// The typed field is `Duration` (the zero-floor arm
5347/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
5348/// `Duration::ZERO`, and the canonical-form arm
5349/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
5350/// sub-millisecond residue), so a programmatic struct literal
5351/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
5352/// and the equivalent author-surface form
5353/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
5354/// integer-hour magnitude) both round-trip cleanly through serde — a
5355/// structurally unbounded `Duration` ceiling. A `:window` value far
5356/// above the documented production-playbook band (Hystrix
5357/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
5358/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
5359/// Istio `outlierDetection.interval` default `10s`, Envoy
5360/// `outlier_detection.interval` default `10s`, AWS App Mesh
5361/// circuit-breaker time-window typical `30s..=300s`) degenerates the
5362/// breaker's role: a rolling-window failure counter whose window is
5363/// hours long is operationally a lifetime counter, the breaker's
5364/// "recent failures" memory is structurally so long that transient
5365/// failures are never forgotten, and the typed slot becomes a no-op
5366/// trigger that trips once and stays tripped for the lifetime of the
5367/// component carried on every emitted Envoy / Cilium L7 overlay.
5368///
5369/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
5370/// shared duration codec emits (`"<n>h"` for any integer-hour
5371/// magnitude) — every value in the canonical authoring form's
5372/// `<integer><unit>` grammar at or below this cap renders to a clean
5373/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
5374/// cap on the first typed-`Duration` `:politicas` axis: the two
5375/// duration-typed `:politicas` axes now share a single uniform top
5376/// edge so the next typed-slot wiring (the future caixa-mesh
5377/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
5378/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
5379/// admission webhook) reaches for either field knowing the value is
5380/// in `1ms..=1h` without re-validating at the renderer layer. The cap
5381/// sits two orders of magnitude above every documented upstream
5382/// production-playbook recommendation band (Hystrix / resilience4j /
5383/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
5384/// and below the clearly-pathological "rolling window degenerates to
5385/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
5386/// author can plausibly want for a very-low-traffic long-tail
5387/// failure-detection window, but a hard wall above which the breaker's
5388/// rolling-window contract is structurally a lifetime-counter contract.
5389/// Lifted as a typed `pub const` so the bound has exactly one source
5390/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5391/// materializer's admission webhook and the caixa-mesh-side
5392/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
5393/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
5394/// other typed upper bound in this crate carries
5395/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5396/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
5397/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5398/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5399/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5400pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
5401
5402/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
5403/// every validated [`RateLimit::rate`] past
5404/// [`AplicacaoSpec::validate_politicas`] lies in
5405/// `1..=POLICY_RATE_LIMIT_MAX`.
5406///
5407/// The typed field is `u32` (the zero-floor arm
5408/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
5409/// zero-rate limit denies every request, the canonical "I forgot
5410/// that 0 means deny-everything" footgun), so a programmatic struct
5411/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
5412/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
5413/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
5414/// round-trip cleanly through serde — a structurally unbounded `u32`
5415/// ceiling. The runtime substrate consuming the value (Envoy's
5416/// `local_rate_limit.token_bucket.max_tokens`, the future
5417/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
5418/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
5419/// rate-limit into a no-op rate-limiter: the bucket capacity is
5420/// structurally so high no realistic per-edge traffic shape can
5421/// drain it, the limiter never trips, and the typed slot becomes a
5422/// "rate-limit declared, no enforcement" footgun — the canonical
5423/// declared-but-inert shape every other `:politicas` cap arm
5424/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
5425/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
5426///
5427/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
5428/// above every documented upstream production-playbook recommendation
5429/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
5430/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
5431/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
5432/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
5433/// `limit_req_zone` typical `1..=1_000` RPS) and below the
5434/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
5435/// `u32::MAX`): a value the author can plausibly want at hyperscale
5436/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
5437/// /h-window arm), but a hard wall above which the policy is
5438/// structurally a no-op carried verbatim on every emitted Envoy /
5439/// Cilium L7 overlay. The cap brackets all three canonical windows
5440/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
5441/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
5442/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
5443/// per-endpoint API band). Lifted as a typed `pub const` so the bound
5444/// has exactly one source of truth — the future M4
5445/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
5446/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
5447/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
5448/// one place. Same shape every other typed upper bound in this crate
5449/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5450/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5451/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
5452/// [`crate::LIMITS_WALL_CLOCK_MAX`],
5453/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
5454/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
5455pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
5456
5457// `:entrada :host` total-length and per-label cap axes route through
5458// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
5459// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
5460// pair of aplicacao-private aliases the previous `validate_entrada_host`
5461// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
5462// = 63`) were structurally the same K8s Gateway API v1 Hostname
5463// admission-schema bounds — the total-length cap on the OpenAPI
5464// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
5465// same regex — that the peer axes at the caixa-core::render level pin,
5466// so hoisting both readers onto the shared lifted constants closes the
5467// third-occurrence duplication threshold structurally: the M4
5468// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
5469// label validator, the future per-`Certificate` SAN emitter, and every
5470// other per-Gateway-API-Hostname landing site reach the same one place
5471// as the `:entrada :host` gate does — no per-axis alias drift surface
5472// between them, by construction.
5473
5474/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
5475/// extractor expression — the upper bound `validate_placement_shard_key`
5476/// enforces on every well-shaped shard-key past validate. The realistic
5477/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
5478/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
5479/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
5480/// `:placement :affinity` / `:placement :clusters` identifier-shaped
5481/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
5482/// in `:shard-key`" footgun at validate time rather than at the future
5483/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
5484const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
5485
5486/// Reject `:membros :caixa` values the K8s apiserver would refuse at
5487/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
5488/// that maps the shared parser-shaped reason into the
5489/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
5490/// is self-locating (the offending `caixa:` is named verbatim) and
5491/// the author can grep their caixa.lisp for `:caixa "<name>"` and
5492/// fix it in one edit. Same diagnostic shape as
5493/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
5494/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
5495fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
5496 // Empty is already gated by `MembroCaixaEmpty` at the call site;
5497 // re-checking here keeps the predicate usable from any future
5498 // call site (the M4 CR materializer) without an empty-check
5499 // footgun. The shared
5500 // [`crate::render::require_valid_dns_1123_label`] helper brackets
5501 // the empty-first + shape cascade every peer name axis
5502 // (`:placement :clusters`, `:placement :affinity`, `:contratos
5503 // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
5504 // `:upgrade-from :module`) routes through, so drift between the
5505 // eight axes' accepted DNS-1123-label sets is structurally
5506 // impossible.
5507 crate::render::require_valid_dns_1123_label(
5508 caixa,
5509 || AplicacaoError::MembroCaixaEmpty,
5510 |reason| AplicacaoError::membro_caixa_invalid(caixa, reason),
5511 )
5512}
5513
5514/// Reject `:placement :clusters` entries the K8s apiserver would refuse
5515/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
5516/// that maps the shared parser-shaped reason into the
5517/// [`AplicacaoError::PlacementClusterInvalid`] variant.
5518///
5519/// Cluster names land in DNS-1123-label territory across every consumer:
5520/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
5521/// the `lareira-fleet-programs` aggregator applies to scope programs to
5522/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
5523/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
5524/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
5525/// cluster identity the M4 CR materializer round-trips. Each apiserver-
5526/// side schema enforces the DNS-1123 label rule on admission; a
5527/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
5528/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
5529/// mistaken-identity slug) silently passes the prior empty-/duplicate-
5530/// only gate and the failure surfaces as a no-match at filter time —
5531/// the workload doesn't land in the named cluster, with no diagnostic
5532/// naming the offending `:clusters` entry. Lifting the gate to caixa-
5533/// build time mirrors the `:membros :caixa` value-shape trajectory
5534/// (3f9d7a0) on the peer name axis.
5535///
5536/// The diagnostic carries the offending `cluster:` verbatim plus a
5537/// parser-shaped `reason:` naming the specific violation, so the
5538/// author can grep their caixa.lisp for `:clusters` and fix it in
5539/// one edit. Same diagnostic shape as
5540/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
5541fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
5542 // Empty is already gated by `PlacementClusterEmpty` at the call
5543 // site; re-checking here keeps the predicate usable from any
5544 // future call site (the M4 CR materializer's per-cluster validator)
5545 // without an empty-check footgun. Routes through the shared
5546 // [`crate::render::require_valid_dns_1123_label`] gate the peer
5547 // name axes each land on.
5548 crate::render::require_valid_dns_1123_label(
5549 cluster,
5550 || AplicacaoError::PlacementClusterEmpty,
5551 |reason| AplicacaoError::placement_cluster_invalid(cluster, reason),
5552 )
5553}
5554
5555/// Reject `:placement :affinity` hints whose shape can never legitimately
5556/// land in any downstream selector or label-keyed routing axis. Thin
5557/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
5558/// shared parser-shaped reason into the
5559/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
5560/// diagnostic is self-locating (the offending `:affinity` is named
5561/// verbatim) and the author can grep their caixa.lisp for
5562/// `:affinity "<hint>"` and fix it in one edit.
5563///
5564/// The `:affinity` slot carries a placement-engine hint — canonical
5565/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
5566/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
5567/// compression overlay and the future M4 placement-engine's per-hint
5568/// routing axis. Each downstream consumer (caixa-mesh's
5569/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
5570/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5571/// `spec.placement.affinity` admission rule, the future M4 per-hint
5572/// node-affinity / pod-affinity rule generator keying off the same
5573/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
5574/// selector) requires the value to be a DNS-1123 label — K8s label
5575/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
5576/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
5577/// admission rule the apiserver enforces.
5578///
5579/// Until this gate landed an `:affinity "DataLocality"` (the canonical
5580/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
5581/// Python-module-name leak), `:affinity "data.locality"` (the
5582/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
5583/// `:affinity "data-locality-"` (boundary-hyphen violation),
5584/// `:affinity "data locality"` (paste-from-doc whitespace),
5585/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
5586/// 64-byte over-cap slug silently passed the empty-only check and the
5587/// failure surfaced as a no-match at the M3 Adaptive compression
5588/// overlay's filter time (`placement.affinity` carried a malformed
5589/// value, no node matched, the workload landed on the default
5590/// heuristic) — the canonical "declared-but-inert" footgun mirroring
5591/// the empty-:affinity / empty-shard-key / zero-:politicas /
5592/// empty-:contratos-target gates already close on every other
5593/// declare-but-no-opinion axis. Lifting the rejection to a build-time
5594/// gate closes the fifth typed slot on the Aplicacao surface to land
5595/// on the canonical DNS-1123 label floor (after the four Servico-name
5596/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
5597/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
5598/// b0e8748).
5599///
5600/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
5601/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
5602/// validated values are guaranteed-accepted by the apiserver without
5603/// re-validation at any downstream renderer or admission layer.
5604fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
5605 // Empty is gated separately at the call site for a self-locating
5606 // diagnostic; re-checking here keeps the predicate usable from any
5607 // future call site (the M4 CR materializer's per-affinity
5608 // validator) without an empty-check footgun. Routes through the
5609 // shared [`crate::render::require_valid_dns_1123_label`] gate the
5610 // peer name axes each land on.
5611 crate::render::require_valid_dns_1123_label(
5612 affinity,
5613 || AplicacaoError::PlacementAffinityEmpty,
5614 |reason| AplicacaoError::placement_affinity_invalid(affinity, reason),
5615 )
5616}
5617
5618/// Reject `:placement :shard-key` extractor expressions whose shape can
5619/// never legitimately drive the future M4 Akka-style cluster-sharding
5620/// reconciler's hash-extractor pass. Maps the per-byte / length checks
5621/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
5622/// diagnostic is self-locating (the offending `:shard-key` value is
5623/// named verbatim alongside the parser-shaped reason) and the author can
5624/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
5625/// edit.
5626///
5627/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
5628/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
5629/// expression naming the message property to hash on. The realistic
5630/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
5631/// property name; `$tenantId` — Akka entity-id placeholder;
5632/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
5633/// `${tenant}` — interpolation-style template) all sit in the printable
5634/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
5635/// multi-line blob landing in `:shard-key`, an embedded space from a
5636/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
5637/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
5638/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
5639/// check and the failure surfaces at the future M4 reconciler's hash
5640/// pass as a runtime extractor-evaluation error far from the source
5641/// `caixa.lisp`, with no field naming which member's `:shard-key`
5642/// carried the offending value.
5643///
5644/// The contract — the printable ASCII single-token intersection-floor
5645/// every Akka-style entity-id extractor implementation admits:
5646///
5647/// - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
5648/// peer DNS-1123-label-shaped `:placement :affinity` /
5649/// `:placement :clusters` identifier axes; realistic shard-keys sit
5650/// well under 32 bytes, the cap surfaces paste-from-doc multi-line
5651/// blob footguns at validate time;
5652/// - every byte in the printable ASCII range `0x21..=0x7E` —
5653/// rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
5654/// `"$tenantId\n"` from paste-from-aligned-doc /
5655/// paste-from-shell-heredoc), control characters (`\x00..\x1F`,
5656/// `\x7F` — the canonical "embedded null from a copy-paste-binary
5657/// footgun"), and non-ASCII bytes (`"$tenàntId"` —
5658/// un-Punycode-encoded IDN that round-trips inconsistently across
5659/// NFC/NFD normalization).
5660///
5661/// The accepted set is broader than the DNS-1123 label floor the peer
5662/// `:placement :clusters` / `:placement :affinity` axes use because the
5663/// `:shard-key` value is not a K8s `metadata.name` / label-selector
5664/// landing site; it's an extractor expression the future Akka-style
5665/// reconciler reads as a property reference. The realistic forms
5666/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
5667/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
5668/// but every Akka-style entity-id extractor parses. The
5669/// printable-ASCII-token floor accepts every shape any such extractor
5670/// would accept while rejecting the cross-implementation footguns
5671/// (whitespace breaks token boundaries; non-ASCII round-trips
5672/// inconsistently across YAML emitters and NFC/NFD normalization;
5673/// control characters silently corrupt the next read).
5674///
5675/// Until this gate landed `validate_placement` only refused the
5676/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
5677/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
5678/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
5679/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
5680/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
5681/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
5682/// control character from paste-from-binary, the 64-byte over-cap
5683/// paste-from-doc multi-line slug) silently passed validate. The future
5684/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
5685/// would then surface the malformed value either as a runtime
5686/// extractor-evaluation error (whitespace breaks the extractor's token
5687/// boundary, no match) or as a silently-different shard assignment
5688/// across YAML emitters (non-ASCII normalizes differently between the
5689/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
5690/// parser, the same entity ID maps to two distinct shards on a
5691/// re-render). Lifting the shape gate to caixa-build time makes the
5692/// extractor-floor invariant a structural property of every validated
5693/// `Placement`: every `Sharded` placement past `validate_placement` has
5694/// a `:shard-key` the future M4 reconciler can hash without
5695/// re-validating at the runtime layer.
5696///
5697/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
5698/// [`AplicacaoError::ContratoSubjectInvalid`] /
5699/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
5700/// on the peer `:contratos` payload axes — each lifts the
5701/// runtime-side parser's intersection-floor to a caixa-build-time gate,
5702/// closing the canonical "this passed validate but the runtime parser
5703/// rejected it" surprise.
5704fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
5705 // Empty is gated separately at the call site via the more
5706 // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
5707 // re-checking here keeps the predicate usable from any future call
5708 // site (the M4 CR materializer's per-shard-key validator) without
5709 // an empty-check footgun.
5710 if key.is_empty() {
5711 return Err(AplicacaoError::ShardedKeyEmpty);
5712 }
5713 if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
5714 return Err(AplicacaoError::shard_key_invalid(
5715 key,
5716 format!(
5717 "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
5718 (got {} bytes; realistic Akka-style entity-id extractor expressions \
5719 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
5720 well under 32 bytes, this length suggests a paste-from-doc \
5721 multi-line blob landed in `:shard-key` instead of a single-token \
5722 extractor expression)",
5723 key.len()
5724 ),
5725 ));
5726 }
5727 for &b in key.as_bytes() {
5728 if (0x21..=0x7E).contains(&b) {
5729 continue;
5730 }
5731 let reason = if b == b' ' {
5732 "contains a space (Akka-style entity-id extractor expressions are \
5733 single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
5734 whitespace breaks the extractor's token boundary at the runtime layer, \
5735 and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
5736 a multi-token blob in one `:shard-key` slot)"
5737 .to_string()
5738 } else if b == b'\t' {
5739 "contains a tab character (paste-from-aligned-doc footgun; the \
5740 Akka-style entity-id extractor reads `:shard-key` as a single-token \
5741 reference, embedded whitespace breaks the token boundary at the \
5742 runtime hash-extractor pass)"
5743 .to_string()
5744 } else if b == b'\n' || b == b'\r' {
5745 format!(
5746 "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
5747 paste-from-multiline-doc footgun; the Akka-style entity-id \
5748 extractor reads `:shard-key` as a single-token reference, embedded \
5749 newlines either truncate the value at the YAML emitter layer or \
5750 break the token boundary at the runtime hash-extractor pass)"
5751 )
5752 } else if b < 0x20 || b == 0x7F {
5753 format!(
5754 "contains control character 0x{b:02x} (the canonical \
5755 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
5756 control characters silently corrupt round-trip serialization \
5757 across YAML emitters and break the runtime hash-extractor's \
5758 single-token parser)"
5759 )
5760 } else {
5761 format!(
5762 "contains non-ASCII byte 0x{b:02x} (the canonical \
5763 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
5764 inconsistently across NFC/NFD normalization on APFS / ext4 / \
5765 across YAML emitter implementations — the same entity ID can \
5766 silently map to two distinct shards on a re-render. Use a \
5767 printable-ASCII extractor expression like `tenantId`, \
5768 `$tenantId`, or `metadata.tenantId`)"
5769 )
5770 };
5771 return Err(AplicacaoError::shard_key_invalid(key, reason));
5772 }
5773 Ok(())
5774}
5775
5776/// Reject `:contratos :de` / `:contratos :para` values whose shape
5777/// can never legitimately match a validated `:membros :caixa`. Thin
5778/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
5779/// shared parser-shaped reason into the
5780/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
5781/// diagnostic is self-locating (which slot — `:de` or `:para` — and
5782/// the offending value verbatim) and the author can grep their
5783/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
5784/// one edit.
5785///
5786/// Until this gate landed an empty or DNS-1123-malformed `:de` /
5787/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
5788/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
5789/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
5790/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
5791/// un-Punycode-encoded IDN) silently passed the per-axis check and
5792/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
5793/// membership lookup — diagnostic-framed as "this caixa is not in
5794/// `:membros`" when the root cause is "this `:de` value is not a
5795/// well-shaped Servico-name identifier and could never legitimately
5796/// match any validated member". Because every `:membros :caixa` is
5797/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
5798/// `names` HashSet structurally never contains an empty / malformed
5799/// string, so the membership lookup arm misframes every empty /
5800/// malformed input. Lifting the shape arm ahead of the lookup
5801/// preserves the legitimate `ContratoMemberMissing` arm (a
5802/// well-shaped `:de` that simply isn't in `:membros` — a phantom
5803/// reference) while routing every structurally-impossible-to-match
5804/// input through the narrower self-locating shape diagnostic.
5805///
5806/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
5807/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
5808/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
5809/// to land on the canonical [`crate::render::is_dns_1123_label`]
5810/// floor. The `slot: &'static str` field carries the kebab-case
5811/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
5812/// per-callback-slot diagnostic shape and the
5813/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
5814/// (85f102c) cross-list-tag pattern.
5815fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
5816 // Routes through the shared
5817 // [`crate::render::require_valid_dns_1123_label`] gate the peer
5818 // name axes each land on. The `slot: &'static str` field flows
5819 // through both error variants so the diagnostic names which
5820 // per-edge axis (`:de` vs `:para`) the offending value came from.
5821 crate::render::require_valid_dns_1123_label(
5822 caixa,
5823 || AplicacaoError::contrato_caixa_empty(slot),
5824 |reason| AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
5825 )
5826}
5827
5828/// Reject `:entrada :para` values whose shape can never legitimately
5829/// match a validated `:membros :caixa`. Thin wrapper around
5830/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
5831/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
5832/// variant, so the diagnostic is self-locating (the offending
5833/// `:entrada :para` value is named verbatim) and the author can grep
5834/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
5835///
5836/// Until this gate landed an empty or DNS-1123-malformed `:entrada
5837/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
5838/// ADR typo, `:para "my_cart"` the Python-module-name leak,
5839/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
5840/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
5841/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
5842/// silently passed the per-axis check and surfaced as
5843/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
5844/// — diagnostic-framed as "this caixa is not in `:membros`" when the
5845/// root cause is "this `:entrada :para` value is not a well-shaped
5846/// Servico-name identifier and could never legitimately match any
5847/// validated member". Because every `:membros :caixa` is shape-
5848/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
5849/// `HashSet` structurally never contains an empty / malformed string,
5850/// so the membership lookup arm misframes every empty / malformed
5851/// input. Lifting the shape arm ahead of the lookup preserves the
5852/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
5853/// simply isn't in `:membros` — a phantom reference) while routing
5854/// every structurally-impossible-to-match input through the narrower
5855/// self-locating shape diagnostic.
5856///
5857/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
5858/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
5859/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
5860/// fourth and last Aplicacao-level Servico-name reference axis to
5861/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
5862/// No `slot: &'static str` field because there is only one axis
5863/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
5864/// the simpler shape mirrors [`validate_membro_caixa`] and
5865/// [`validate_placement_cluster`].
5866fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
5867 // Empty is gated separately at the call site for a self-locating
5868 // diagnostic; re-checking here keeps the predicate usable from any
5869 // future call site (the M4 CR materializer's per-`:entrada`
5870 // validator) without an empty-check footgun. Routes through the
5871 // shared [`crate::render::require_valid_dns_1123_label`] gate the
5872 // peer name axes each land on.
5873 crate::render::require_valid_dns_1123_label(
5874 para,
5875 || AplicacaoError::EntradaParaEmpty,
5876 |reason| AplicacaoError::entrada_para_invalid(para, reason),
5877 )
5878}
5879
5880/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
5881/// would refuse at admission time. The contract — exactly the regex
5882/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
5883/// and `HTTPRoute.spec.hostnames[]`,
5884/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
5885/// (max length 253; per-label max length 63):
5886///
5887/// - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
5888/// uppercase, no underscore, no Unicode/IDN — IDN must be
5889/// pre-encoded as Punycode `xn--…` by the author);
5890/// - exactly one optional leading wildcard label (`*.`); a wildcard
5891/// in any non-leading label position is rejected;
5892/// - each `.`-separated label is 1..=63 bytes, with non-hyphen
5893/// alphanumeric at both boundaries (no `-foo`, no `foo-`);
5894/// - total length 1..=253 bytes;
5895/// - no IPv4 literal (Gateway API forbids IP literals);
5896/// - no scheme (`https://`, `http://`), no port (`:8080`), no
5897/// whitespace, no path (`/`).
5898///
5899/// Lifted as a typed gate (rather than an inline cascade in
5900/// `validate()`) so the contract lives in one place — every future
5901/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5902/// materializer's host validator, the future per-`:entrada` SAN
5903/// emission for cert-manager Certificates, the multi-`:entrada`
5904/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
5905/// for the same predicate, not its own. Same compounding shape as
5906/// `is_canonical_rate_limit_window` (808017c) and
5907/// [`WitTarget::label`] (previously the free `contrato_target_label`
5908/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
5909/// per-variant label match is compiler-checked-exhaustive).
5910///
5911/// The diagnostic carries the offending `host:` verbatim plus a
5912/// parser-shaped `reason:` naming the specific violation, so the
5913/// author can grep their caixa.lisp for `:host "<host>"` and fix it
5914/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
5915/// (9888b13).
5916fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
5917 // Empty is already gated by `EmptyEntradaHost` at the call site;
5918 // re-checking here keeps the predicate usable from any future
5919 // call site (M4 CR materializer) without an empty-check footgun.
5920 if host.is_empty() {
5921 return Err(AplicacaoError::EmptyEntradaHost);
5922 }
5923 if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
5924 return Err(AplicacaoError::entrada_host_invalid(
5925 host,
5926 format!(
5927 "exceeds Gateway API v1 Hostname max length of {cap} bytes \
5928 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
5929 host.len(),
5930 cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
5931 ),
5932 ));
5933 }
5934 if host.contains("://") {
5935 return Err(AplicacaoError::entrada_host_invalid(
5936 host,
5937 "must not carry a scheme (drop the `https://` or `http://` prefix; \
5938 Gateway API takes the bare hostname)",
5939 ));
5940 }
5941 if host.contains('/') {
5942 return Err(AplicacaoError::entrada_host_invalid(
5943 host,
5944 "must not carry a path (drop the `/…` suffix; Gateway API path \
5945 matching is in `:entrada :paths`)",
5946 ));
5947 }
5948 // After the `://` scheme-prefix and `/` path arms have ruled out the
5949 // two `:`-bearing shapes the Gateway API actively rejects with
5950 // location-shaped diagnostics, any remaining `:` in the host body is
5951 // either the canonical "I put the port in the `:host` slot"
5952 // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
5953 // slot lives one axis away on the same `:entrada` block) or an
5954 // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
5955 // Hostname forbids identically to the IPv4-literal arm below. Both
5956 // shapes silently fell through the `://` and `/` arms before this
5957 // lift and surfaced as a deep `label "<rest>:<port>" contains
5958 // invalid character ':'` diagnostic from the per-byte loop near the
5959 // bottom of this predicate, which named the offending byte but not
5960 // the canonical authoring fix — for the port case the author has to
5961 // know the `:entrada` block carries a separate `:port u16` slot
5962 // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
5963 // move the value over; for the IPv6 case the author has to know
5964 // Gateway API v1 forbids IP literals across the board. The contract
5965 // doc-comment above already promises "no port (`:8080`)" verbatim
5966 // in the rejected-shape enumeration but the predicate's
5967 // implementation refused the `:` only as a side-effect of the
5968 // per-label `[a-z0-9-]` character-class loop; this arm brings the
5969 // implementation in line with the documented contract by surfacing
5970 // the canonical fix at the top-level shape gate, peer with how the
5971 // `://` arm names the scheme prefix and the `/` arm names the
5972 // `:entrada :paths` axis. Same compounding trajectory the recent
5973 // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
5974 // — the typed slot's rejected set matches the apiserver's rejected
5975 // set, structurally, with a self-locating diagnostic at the
5976 // offending axis instead of a deep parser-shape leak.
5977 if host.contains(':') {
5978 return Err(AplicacaoError::entrada_host_invalid(
5979 host,
5980 "must not contain `:` (the port belongs in the `:entrada :port` \
5981 slot — a separate `u16` axis on the same `:entrada` block, \
5982 defaulting to 8080 — not in the host body; drop the `:<port>` \
5983 suffix and author the bare hostname. If you intended an IPv6 \
5984 literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
5985 Hostname forbids IP literals identically to the IPv4-literal \
5986 arm — use a DNS name)",
5987 ));
5988 }
5989 // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
5990 // predicate — the same single source of truth every peer
5991 // ASCII-whitespace scan in caixa-core flows through: the four
5992 // typed-magnitude codec sites (`limits::parse_byte_size` backing
5993 // `:limits :memory`, `limits::parse_duration` backing `:limits
5994 // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
5995 // `aplicacao::rate_limit_codec::parse` backing `:politicas
5996 // :rate-limit`) and the shared duration codec
5997 // (`supervisor::duration_codec::parse`) backing `:supervisor
5998 // :restart-window` / `:politicas :timeout` / `:politicas
5999 // :circuit-breaker :window`. This landing closes the last string-typed
6000 // slot in caixa-core still calling `.bytes().any(|b|
6001 // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
6002 // across every typed slot now shares one predicate, so a future
6003 // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
6004 // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
6005 // deliberately excluded from the peer non-ASCII predicate) can
6006 // extend at this shared site in one edit rather than seven
6007 // independent scans diverging over time. Naming the offending byte
6008 // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
6009 // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
6010 // the offending byte verbatim" discipline every peer codec site
6011 // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
6012 // / `supervisor.rs:823` / `aplicacao.rs:1640`).
6013 if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
6014 return Err(AplicacaoError::entrada_host_invalid(
6015 host,
6016 format!(
6017 "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
6018 Hostname is a single-token DNS name — leading, trailing, \
6019 or embedded whitespace breaks the K8s apiserver's Hostname \
6020 regex at admission time; the paste-from-aligned-doc / \
6021 paste-from-shell-history / paste-from-CSV footgun silently \
6022 lands a multi-token blob in `:entrada :host`. Strip every \
6023 whitespace byte and author the bare hostname — space \
6024 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
6025 refuse identically)"
6026 ),
6027 ));
6028 }
6029 // Peer of the ASCII-whitespace scan above: route the non-ASCII
6030 // subset of Unicode `White_Space` through the shared
6031 // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
6032 // single source of truth every peer non-ASCII-whitespace scan in
6033 // caixa-core flows through: `limits::parse_byte_size` (`:limits
6034 // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
6035 // `limits::parse_millicores` (`:limits :cpu`),
6036 // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
6037 // and `supervisor::duration_codec::parse` (`:supervisor
6038 // :restart-window` / `:politicas :timeout` / `:politicas
6039 // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
6040 // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
6041 // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
6042 // paste-from-web-doc), or an EM-SPACE-split host
6043 // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
6044 // survived this predicate's ASCII byte-scan (none of the UTF-8
6045 // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
6046 // `u8::is_ascii_whitespace`), then landed on the per-label
6047 // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
6048 // predicate with the generic `label "…" must start and end with an
6049 // alphanumeric` diagnostic — a "far from source at build-time"
6050 // leak that names the label-shape violation but not the
6051 // paste-from-typography origin the author actually needs to fix.
6052 // Peer with the four codec sites the 1b75b38 landing pinned: the
6053 // typed slot's diagnostic axis names the offending codepoint
6054 // (`U+XXXX`) verbatim rather than laundering the value through a
6055 // downstream label-shape arm, so the author can grep their
6056 // caixa.lisp for the invisible codepoint at the surfaced position
6057 // rather than eyeball a multi-byte host for embedded NBSP / LINE
6058 // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
6059 // discipline the peer ASCII-whitespace arm (720ac3b) carries:
6060 // drift between any two typed-slot sites' non-ASCII-whitespace
6061 // rejection set becomes a single-edit fix at the shared predicate
6062 // rather than N independent inline scans diverging over time, and
6063 // a future stricter classification (BOM `\u{FEFF}` / ZWSP
6064 // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
6065 // `char::is_whitespace`" class the peer non-ASCII predicate's
6066 // doc-comment names as the follow-up trajectory) extends at the
6067 // shared predicate in one edit rather than seven.
6068 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
6069 return Err(AplicacaoError::entrada_host_invalid(
6070 host,
6071 format!(
6072 "contains non-ASCII Unicode whitespace character {ch:?} \
6073 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
6074 single-token DNS name limited to `[a-z0-9-]` labels; \
6075 the paste-from-typography footgun silently lands an \
6076 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
6077 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
6078 `U+3000`, and every other member of the Unicode \
6079 `White_Space` property outside the ASCII byte range) \
6080 in `:entrada :host`, which the K8s apiserver's \
6081 Hostname regex refuses at admission time far from the \
6082 caixa.lisp source line. Strip every non-ASCII \
6083 whitespace character and author the bare hostname \
6084 with only ASCII bytes (write \"checkout.quero.cloud\" \
6085 verbatim)",
6086 codepoint = ch as u32,
6087 ),
6088 ));
6089 }
6090
6091 // Strip the optional single leading wildcard label *before* the
6092 // trailing-dot check so the bare `"*."` form surfaces the more
6093 // self-locating "wildcard without domain" diagnostic instead of
6094 // the generic "trailing dot" one.
6095 let (had_wildcard, rest) = match host.strip_prefix("*.") {
6096 Some(r) => (true, r),
6097 None => (false, host),
6098 };
6099 if had_wildcard && rest.is_empty() {
6100 return Err(AplicacaoError::entrada_host_invalid(
6101 host,
6102 "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)",
6103 ));
6104 }
6105 if rest.contains('*') {
6106 return Err(AplicacaoError::entrada_host_invalid(
6107 host,
6108 "wildcard `*` is allowed only as the first label (`*.example.com`); \
6109 no inner or trailing `*` labels",
6110 ));
6111 }
6112 if rest.ends_with('.') {
6113 return Err(AplicacaoError::entrada_host_invalid(
6114 host,
6115 "must not have a trailing `.` (Gateway API hostnames are not \
6116 fully-qualified with a root dot; the apiserver regex rejects \
6117 trailing dots)",
6118 ));
6119 }
6120
6121 // Reject pure IPv4 literals: four dot-separated labels, every
6122 // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
6123 // literals as Hostnames.
6124 let labels: Vec<&str> = rest.split('.').collect();
6125 if labels.len() == 4
6126 && labels
6127 .iter()
6128 .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
6129 {
6130 return Err(AplicacaoError::entrada_host_invalid(
6131 host,
6132 "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
6133 literals; use a DNS name)",
6134 ));
6135 }
6136
6137 // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
6138 // hyphen, with non-hyphen at both boundaries.
6139 for label in &labels {
6140 if label.is_empty() {
6141 return Err(AplicacaoError::entrada_host_invalid(
6142 host,
6143 "has an empty label (consecutive `..` or a leading `.`)",
6144 ));
6145 }
6146 if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
6147 return Err(AplicacaoError::entrada_host_invalid(
6148 host,
6149 format!(
6150 "label {label:?} exceeds DNS-1123 label max length of \
6151 {cap} bytes (got {} bytes)",
6152 label.len(),
6153 cap = crate::render::DNS_1123_LABEL_MAX_LEN,
6154 ),
6155 ));
6156 }
6157 let bytes = label.as_bytes();
6158 if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
6159 return Err(AplicacaoError::entrada_host_invalid(
6160 host,
6161 format!(
6162 "label {label:?} must start and end with an alphanumeric \
6163 (no leading or trailing `-`)"
6164 ),
6165 ));
6166 }
6167 for &b in bytes {
6168 let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
6169 if !valid {
6170 let msg = if b.is_ascii_uppercase() {
6171 format!(
6172 "label {label:?} contains uppercase character {ch:?} \
6173 (Gateway API hostnames are lowercase-only; use {lower:?})",
6174 ch = b as char,
6175 lower = label.to_ascii_lowercase()
6176 )
6177 } else if b == b'_' {
6178 format!(
6179 "label {label:?} contains `_` (Gateway API hostnames \
6180 allow only `[a-z0-9-]`; use `-` instead)"
6181 )
6182 } else {
6183 format!(
6184 "label {label:?} contains invalid character {ch:?} \
6185 (Gateway API hostnames allow only `[a-z0-9-]`)",
6186 ch = b as char
6187 )
6188 };
6189 return Err(AplicacaoError::entrada_host_invalid(host, msg));
6190 }
6191 }
6192 }
6193 Ok(())
6194}
6195
6196/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
6197/// would refuse at admission time. Thin wrapper around
6198/// [`crate::render::is_gateway_api_http_path`] that maps the shared
6199/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
6200/// variant, preserving the more self-locating
6201/// [`AplicacaoError::EntradaPathEmpty`] /
6202/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
6203/// path fails those narrower invariants first.
6204///
6205/// The contract is the canonical HTTP-path grammar — `1..=
6206/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
6207/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
6208/// whitespace/control/non-ASCII bytes — shared with the
6209/// `:contratos :endpoint` axis through the lifted predicate so drift
6210/// between either landing site and the K8s apiserver-side
6211/// HTTPPathMatch.value OpenAPI schema is a build error visible at
6212/// the predicate, not a per-renderer "this passed validate but failed
6213/// admission" surprise. The diagnostic carries the offending `path:`
6214/// verbatim plus a parser-shaped `reason:` naming the specific
6215/// violation, so the author can grep their caixa.lisp for `:paths`
6216/// and fix it in one edit. Same diagnostic shape as
6217/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
6218/// axis.
6219fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
6220 // Empty and missing-leading-`/` are already gated at the call
6221 // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
6222 // checking here keeps the per-axis narrower diagnostics in force
6223 // when the predicate is reached directly (and `is_gateway_api_http_path`
6224 // itself defends against `bytes[0]`-style indexing on empty
6225 // input).
6226 if path.is_empty() {
6227 return Err(AplicacaoError::EntradaPathEmpty);
6228 }
6229 if !path.starts_with('/') {
6230 return Err(AplicacaoError::entrada_path_not_absolute(path));
6231 }
6232 crate::render::is_gateway_api_http_path(path)
6233 .map_err(|reason| AplicacaoError::entrada_path_invalid(path, reason))
6234}
6235
6236mod rate_limit_codec {
6237 // `Duration` is no longer named here — the codec routes through
6238 // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
6239 // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
6240 // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
6241 // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
6242 // closed-set enum's arm-table rather than through vestigial free-helper
6243 // delegates.
6244 use super::{RateLimit, RateLimitUnit};
6245 use serde::{Deserializer, Serializer};
6246
6247 pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
6248 // Route through the canonical [`crate::render::serialize_option_via_str`]
6249 // — the substrate-side single-owner primitive for the forward
6250 // arm of the typed-magnitude codec family. See its docstring
6251 // for the full sibling roster.
6252 crate::render::serialize_option_via_str(v, s, render)
6253 }
6254
6255 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
6256 // Route through the canonical [`crate::render::deserialize_option_via_str`]
6257 // — the substrate-side single-owner primitive for the reverse
6258 // arm of the typed-magnitude codec family. See its docstring
6259 // for the full sibling roster.
6260 crate::render::deserialize_option_via_str(d, parse)
6261 }
6262
6263 fn parse(s: &str) -> Result<RateLimit, String> {
6264 // Paired whitespace-rejection arm — same canonical-form
6265 // render-determinism discipline as the peer
6266 // `limits::parse_byte_size` / `limits::parse_duration` /
6267 // `limits::parse_millicores` /
6268 // `supervisor::duration_codec::parse` sites: the ASCII
6269 // byte-scan closes the WhatWG-conformant whitespace bytes
6270 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
6271 // `char::is_whitespace` scan closes the strictly-complementary
6272 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
6273 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
6274 // codepoints) that `str::trim` at parse entry silently strips.
6275 // Either drift class would round-trip through `render` to a
6276 // *different* canonical form on next emit — breaking the
6277 // THEORY.md Part V render-determinism contract on
6278 // `:politicas :rate-limit`.
6279 //
6280 // Routed through the lifted [`crate::render::reject_whitespace`]
6281 // primitive — the substrate-side single-owner paired-arm gate
6282 // every typed-magnitude codec in caixa-core shares.
6283 crate::render::reject_whitespace::<String, _, _>(
6284 s,
6285 |b| {
6286 format!(
6287 "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
6288 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
6289 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
6290 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
6291 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
6292 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
6293 on first serialize — breaking the THEORY.md Part V render-determinism \
6294 contract every typed slot carries. Strip every whitespace byte (write \
6295 `\"100/s\"` verbatim)"
6296 )
6297 },
6298 |ch| {
6299 format!(
6300 "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
6301 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
6302 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
6303 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
6304 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
6305 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
6306 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
6307 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
6308 silently strips it at parse entry, and the value round-trips through \
6309 `render` to a *different* canonical form (`\"100/s\"`) on first \
6310 serialize — breaking the THEORY.md Part V render-determinism contract \
6311 every typed slot carries. Strip every non-ASCII whitespace character \
6312 (write `\"100/s\"` verbatim with only ASCII bytes)",
6313 cp = ch as u32
6314 )
6315 },
6316 )?;
6317 let s = s.trim();
6318 let (rate_str, unit) = s
6319 .split_once('/')
6320 .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
6321 let rate_trim = rate_str.trim();
6322 // The canonical authoring form for `:politicas :rate-limit` is
6323 // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
6324 // non-negative integer with no decimal point and no leading
6325 // sign, so the parser's accepted set must match for
6326 // serialize/deserialize to round-trip without canonical-form
6327 // drift. Until this gate landed the parser accepted any
6328 // `u32::from_str`-shaped magnitude — and current Rust
6329 // `u32::from_str` permissively accepts a leading `+` (`"+100"`
6330 // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
6331 // serde silently round-tripped to `"100/s"` on the next emit
6332 // (a *different* canonical string) — breaking the THEORY.md
6333 // Part V render-determinism contract on the fifth typed-codec
6334 // surface in caixa-core (peer with the four duration codecs the
6335 // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
6336 // already covered: `supervisor::duration_codec` backing three
6337 // typed-duration slots, `limits::parse_duration` backing
6338 // `:limits :wall-clock`, `limits::parse_byte_size` backing
6339 // `:limits :memory`). The fractional / decimal-shaped sibling
6340 // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
6341 // existing rejection arm, but the diagnostic is value-laundered
6342 // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
6343 // doesn't name the canonical-form remediation or the round-trip
6344 // drift the next emit would produce); this gate lifts the
6345 // fractional arm onto the same canonical-form diagnostic the
6346 // peer codecs carry.
6347 //
6348 // Strict canonical form: every byte of the magnitude is an
6349 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
6350 // inputs the gate distinguishes "non-canonical-but-numeric"
6351 // (parses as f64 or i64 — surfaced with a self-locating
6352 // diagnostic naming the canonical authoring form and the
6353 // round-trip drift the rejected shape would produce on first
6354 // serialize) from "garbage" (parses as neither — surfaced with
6355 // the existing narrower `"not a u32"` wording so its
6356 // diagnostic shape remains stable for the parser-shape footgun
6357 // case).
6358 //
6359 // Routed through the lifted
6360 // [`crate::render::is_digit_only_magnitude`] predicate — the
6361 // same source of truth the four peer typed-magnitude codec
6362 // sites share.
6363 let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
6364 if !digit_only {
6365 let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
6366 if numeric {
6367 return Err(format!(
6368 "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
6369 canonical authoring form for `:politicas :rate-limit` is \
6370 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
6371 with no decimal point and no leading `+` / `-` sign. A fractional / \
6372 signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
6373 through `render` to a *different* canonical form (`\"1/s\"`, \
6374 `\"100/s\"`, parser-reject) on first serialize — breaking the \
6375 THEORY.md Part V render-determinism contract every typed slot \
6376 carries. Pick an integer rate that fits the desired window \
6377 (write `\"6000/m\"` instead of `\"1.66/s\"`)"
6378 ));
6379 }
6380 return Err(format!("rate-limit rate {rate_str:?} not a u32"));
6381 }
6382 // Leading-zero arm — peer with the prior `"+100/s"` arm above
6383 // (4eeae98's predecessor) on the same canonical-form
6384 // render-determinism axis. The digit-only gate accepts
6385 // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
6386 // them losslessly (= 100, 0, 7), but `render` emits the
6387 // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
6388 // a *different* canonical string on the next emit, breaking
6389 // the THEORY.md Part V render-determinism contract the same
6390 // way `"+100/s"` did before the leading-`+` arm landed. The
6391 // single-byte magnitude `"0"` itself round-trips losslessly
6392 // through `render` (`render(0)` emits `"0/s"`) — the
6393 // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
6394 // what refuses rate-zero authoring, so `"0/s"` stays in the
6395 // accepted set at this codec layer and the diagnostic
6396 // partitioning between canonical-form drift (this arm) and
6397 // semantic-zero (the downstream gate) remains stable.
6398 // Peer with the future leading-zero arms on the three peer
6399 // typed-magnitude codecs the trajectory acknowledges:
6400 // `supervisor::duration_codec`, `limits::parse_duration`,
6401 // `limits::parse_byte_size` — each carries the same
6402 // canonical-form-drift class today; this gate lands the
6403 // discipline on the fourth typed-magnitude codec in
6404 // caixa-core first because the peer `"+100/s"` arm above is
6405 // the closest predecessor on the trajectory.
6406 //
6407 // Routed through the lifted
6408 // [`crate::render::is_leading_zero_padded_magnitude`]
6409 // predicate — the same source of truth the four peer
6410 // typed-magnitude codec sites share.
6411 if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
6412 return Err(format!(
6413 "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
6414 canonical authoring form for `:politicas :rate-limit` is \
6415 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
6416 with no leading-zero padding on the magnitude. A leading-zero magnitude \
6417 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
6418 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
6419 first serialize — breaking the THEORY.md Part V render-determinism \
6420 contract every typed slot carries. Strip the leading zeros (write \
6421 `\"100/s\"` instead of `\"0100/s\"`)"
6422 ));
6423 }
6424 // The digit-only gate guarantees every byte is `[0-9]`, and
6425 // the leading-zero arm above guarantees the magnitude is
6426 // either the single byte `"0"` or starts with `[1-9]`, so
6427 // the only way `u32::from_str` can fail here is overflow
6428 // (the magnitude exceeds `u32::MAX`). Surface that with an
6429 // overflow-shaped wording so the diagnostic names the
6430 // offending magnitude verbatim rather than collapsing onto
6431 // the non-canonical arm. Same shape
6432 // `supervisor::duration_codec` (1c55a2a) carries on the peer
6433 // duration-codec axis.
6434 let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
6435 format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
6436 })?;
6437 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
6438 // the closed-set typed enum [`super::RateLimitUnit`]; this parse
6439 // arm reads the `&str → Duration` projection through the
6440 // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
6441 // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
6442 // with [`super::RateLimitUnit::window`]) rather than the vestigial
6443 // module-private `rate_limit_window_from_unit` free helper the
6444 // predecessor 61421a6 left as the last unlifted delegate on this
6445 // axis. One typed dispatch on the substrate primitive instead of
6446 // one runtime call through the free-helper delegate; the sole
6447 // production consumer of the `&str → Duration` axis (this parse
6448 // arm) now reaches for exactly one typed method on the closed-set
6449 // enum, sibling to the codec's render arm's
6450 // [`super::RateLimit::canonical_unit`] dispatch on the paired
6451 // `Duration → RateLimitUnit` axis and to the validate gate's
6452 // [`super::RateLimit::canonical_unit`] shape-probe on the
6453 // canonical-window axis. A future rate-limit-unit addition (a
6454 // `"d"` day suffix once Envoy's `rate_limit_action` grows
6455 // daily-bucket support, a `"ms"` sub-second window once
6456 // high-throughput per-edge policies come into scope per
6457 // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
6458 // on the closed-set enum, and the compiler enforces exhaustiveness
6459 // on every consumer's `match self` arms — this parse arm's
6460 // accepted-suffix set, the render arm's emitted-suffix set, the
6461 // validate gate's canonical-window set, and every future
6462 // per-`:contratos`-edge rate-limit-override overlay all pick it up
6463 // by construction.
6464 let unit = unit.trim();
6465 let window = RateLimitUnit::window_from_suffix(unit)
6466 .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
6467 Ok(RateLimit { rate, window })
6468 }
6469
6470 fn render(rl: RateLimit) -> String {
6471 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
6472 // module scope on the closed-set typed enum [`super::RateLimitUnit`];
6473 // this render arm reads the `Duration → RateLimitUnit` projection
6474 // through the substrate primitive [`super::RateLimit::canonical_unit`]
6475 // (returns `None` on every non-canonical window — the sub-second /
6476 // non-`{1, 60, 3600}` shapes the validate gate rejects), then
6477 // formats the returned typed enum through its
6478 // [`std::fmt::Display`] impl (which routes through
6479 // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
6480 // the substrate primitive instead of one runtime `find_map`
6481 // walk through the free-helper delegate chain
6482 // [`super::rate_limit_window_unit`] (the vestigial free helper's
6483 // sole production consumer was this arm; every other consumer of
6484 // the `Duration → unit` axis — the validate gate below and the
6485 // future M4 per-Aplicacao Envoy config reconciler — now reads
6486 // the same typed method).
6487 //
6488 // A future rate-limit-unit addition (a `"d"` day suffix once
6489 // Envoy's `rate_limit_action` grows daily-bucket support) is
6490 // one variant + one arm per method on the closed-set enum, and
6491 // the compiler enforces exhaustiveness on every consumer's
6492 // `match self` arms — the codec's `parse` accepted-suffix set,
6493 // this render arm's emitted-suffix set, the validate gate's
6494 // canonical-window set, and every future per-`:contratos`-edge
6495 // rate-limit-override overlay all pick it up by construction.
6496 if let Some(unit) = rl.canonical_unit() {
6497 format!("{}/{unit}", rl.rate())
6498 } else {
6499 // Defensive fallback for non-canonical windows. Note:
6500 // [`AplicacaoSpec::validate_politicas`] rejects any
6501 // non-canonical `:rate-limit :window` via
6502 // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
6503 // a validated `RateLimit` never reaches this branch. The
6504 // emitted `<n>/<k>s` form is *not* round-trippable through
6505 // [`parse`] (which accepts only the closed-set
6506 // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
6507 // explicit count) — the validate gate is what makes the
6508 // round-trip a structural property; this branch exists only
6509 // so a programmatic non-validated serialize doesn't panic.
6510 format!("{}/{}s", rl.rate(), rl.window().as_secs())
6511 }
6512 }
6513}
6514
6515// ── placement strategy ───────────────────────────────────────────────
6516
6517/// How the Aplicacao distributes across clusters. Three options:
6518///
6519/// - `SingleNode` — one cluster runs the app at a time; takeover on
6520/// death (Erlang/OTP distributed-app semantics).
6521/// - `Replicated` — every named cluster runs an instance (active-active).
6522/// - `Sharded` — entities distribute by hash key across clusters
6523/// (Akka cluster sharding).
6524#[derive(
6525 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
6526)]
6527pub enum PlacementStrategy {
6528 SingleNode,
6529 Replicated,
6530 Sharded,
6531}
6532
6533/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
6534/// distribution-strategy default for the `:placement :estrategia` axis —
6535/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
6536/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
6537/// so every substrate-side consumer that resolves "what
6538/// [`PlacementStrategy`] variant does an author-omitted `:placement
6539/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
6540/// primitive [`PlacementStrategy`].
6541///
6542/// The `:placement :estrategia` default axis has three production
6543/// consumers on the substrate side today: the [`Default for
6544/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
6545/// impl's struct-literal `estrategia` field, and the serde-side
6546/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
6547/// author-omitted `:placement :estrategia` scalar through the [`Default
6548/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
6549/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
6550/// impl and implicit `PlacementStrategy::default()` routes at the sibling
6551/// consumers, with no compile-time link back to the paired
6552/// [`crate::manifest::Caixa::aplicacao_view`] fold's
6553/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
6554/// production consumer that resolves an author-omitted `:placement` slot
6555/// (entirely omitted, not just the `:estrategia` scalar within a declared
6556/// `:placement` block) through [`Placement::default`] which then routes
6557/// through this same discriminator. A future coherent rebrand of the
6558/// `:placement :estrategia` default (a widening to `Sharded` once the
6559/// substrate discovers hash-keyed distribution as the more common
6560/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
6561/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
6562/// names, a per-cluster overlay the operator pins through a future
6563/// `:placement-overrides` slot) would have had to migrate a lifted
6564/// discriminator on one path and open-coded discriminators on the peers
6565/// in lockstep or the four consumers would silently drift out of
6566/// pairing. Lifting the resolution rule to a typed `pub const` on the
6567/// substrate primitive means the M3-mesh-canonical `:placement
6568/// :estrategia` default migrates as one unit on any future axis change.
6569///
6570/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
6571/// §II.2's active-active-across-every-named-cluster arm — the closest
6572/// canonical M3 production reference the substrate carries, matching the
6573/// caixa-mesh default axis every M3 renderer already keys off (a
6574/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
6575/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
6576/// under the substrate's fleet-programs aggregator without an explicit
6577/// `:placement :estrategia` override). The two alternatives the closed
6578/// [`PlacementStrategy::ALL`] accept-set carries
6579/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
6580/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
6581/// Akka-style hash-keyed distribution across clusters,
6582/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
6583/// postures an author declares explicitly, never a posture an omitted
6584/// slot should silently assume.
6585///
6586/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
6587/// exactly one source of truth on the `:placement :estrategia` axis, on
6588/// the same substrate-primitive lift discipline the sibling M2
6589/// per-supervisor default set carries
6590/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
6591/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
6592/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
6593/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
6594/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
6595/// ([`crate::render::DEFAULT_NAMESPACE`],
6596/// [`crate::render::DEFAULT_LIBRARY_NAME`],
6597/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
6598/// the M3 mesh-primitive-defining slot family to converge onto the
6599/// substrate-primitive-lift discipline the M2 supervisor-slot family
6600/// already carries end-to-end.
6601pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
6602
6603impl Default for PlacementStrategy {
6604 fn default() -> Self {
6605 // Route the [`Default for PlacementStrategy`] impl through the
6606 // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
6607 // `pub const` rather than a raw `Self::Replicated` arm — one
6608 // source of truth for the M3-mesh-canonical active-active-
6609 // across-every-named-cluster `:placement :estrategia` default
6610 // (MESH-COMPOSITION §II.2), on the same substrate-primitive
6611 // lift discipline the sibling M2 per-supervisor default set
6612 // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
6613 // paired halves) carries end-to-end. Pinned by
6614 // `placement_strategy_default_routes_through_lifted_default`.
6615 PLACEMENT_ESTRATEGIA_DEFAULT
6616 }
6617}
6618
6619impl PlacementStrategy {
6620 /// Exhaustive iteration surface for every consumer that reads the
6621 /// full closed-set (the future M4 admission-webhook's accepted-
6622 /// strategy listing in its rejection body, a future `feira app
6623 /// placement --list` CLI-side surfacing of the accepted arm-set,
6624 /// any future round-trip fuzz harness). A future variant addition
6625 /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
6626 /// names as a trajectory item) extends this slice as a single edit
6627 /// and every consumer picks up the new entry by construction — the
6628 /// compiler-checked exhaustiveness on the sibling method `match`
6629 /// arms is the build-time guarantee that no arm forgets to grow.
6630 /// Same shape as the sibling closed-set typed enums'
6631 /// [`RateLimitUnit::ALL`] (6bce03d) and
6632 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6633 /// surfaces — the third closed-set typed enum on the caixa surface
6634 /// to converge onto the same discipline.
6635 pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
6636
6637 /// Canonical camelCase-schema discriminator scalar this variant
6638 /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
6639 /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
6640 /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6641 /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
6642 /// every substrate consumer that dispatches on the strategy (the
6643 /// `lareira-fleet-programs` aggregator, the future `app-operator`
6644 /// reconciler, the M3 Adaptive compression pass) reads the same
6645 /// byte-string the `Serialize` derive emits — the pin test in
6646 /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
6647 /// asserts the two paths agree.
6648 #[must_use]
6649 pub const fn as_str(self) -> &'static str {
6650 match self {
6651 Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
6652 Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
6653 Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
6654 }
6655 }
6656
6657 /// Substrate-canonical reverse projection on the `:placement
6658 /// :estrategia` closed-set axis — parses the camelCase-schema
6659 /// discriminator scalar back to the typed variant, or `None` when
6660 /// `s` is outside the closed-set arm-string set [`Self::as_str`]
6661 /// emits. Dispatches on the same lifted
6662 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
6663 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6664 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
6665 /// [`Self::as_str`] emitter walks, so the parse and emit halves of
6666 /// the round-trip migrate through one caixa-core edit on any future
6667 /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
6668 /// §II.5 hint names as a trajectory item lands one variant + one
6669 /// arm per method and the compiler enforces exhaustiveness on every
6670 /// consumer's `match self` arms).
6671 ///
6672 /// Prior to this lift the substrate carried only the forward
6673 /// `Self → &str` projection (the [`Self::as_str`] emitter, the
6674 /// [`std::fmt::Display`] impl routed through it, the `Serialize`
6675 /// derive that emits the same byte-string under
6676 /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
6677 /// consumer that wanted to parse a wire-form strategy scalar had to
6678 /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
6679 /// => …, "Sharded" => …, _ => … }` cascade that expressed no
6680 /// compile-time link back to the typed variant's canonical lifted
6681 /// constant. A future variant rename or a per-arm serde-attribute
6682 /// drift would silently split the wire byte-string one non-serde
6683 /// consumer parsed from the one the emitter wrote, with the
6684 /// failure surfacing at parse time far from the rebrand commit.
6685 ///
6686 /// Same closed-set-reverse-projection discipline the sibling
6687 /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
6688 /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
6689 /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
6690 /// defining `:placement :estrategia` closed-set axis, the third
6691 /// substrate-side closed-set typed enum to converge on the two-way
6692 /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
6693 /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
6694 /// and side-step the [`std::str::FromStr`]-collision clippy
6695 /// (`clippy::should_implement_trait`) the plain `from_str` name
6696 /// carries; a future explicit [`std::str::FromStr`] impl can layer
6697 /// on top by delegating to this canonical arm-dispatch method.
6698 ///
6699 /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
6700 /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
6701 /// picks the diagnostic form appropriate for its use site — a
6702 /// future `feira app placement --set` CLI-side arg-parse that wants
6703 /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
6704 /// Sharded)"` diagnostic builds one on top by iterating
6705 /// [`Self::ALL`], while the future M4 admission-webhook's rejection
6706 /// path folds `None` onto its per-CR structured refusal body.
6707 #[must_use]
6708 pub fn from_wire(s: &str) -> Option<Self> {
6709 match s {
6710 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
6711 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
6712 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
6713 _ => None,
6714 }
6715 }
6716
6717 /// Substrate-canonical per-arm predicate naming the cross-slot
6718 /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
6719 /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
6720 /// consumes the paired [`Placement::shard_key`] axis (and therefore
6721 /// requires — and is the only strategy that permits — a non-empty
6722 /// `:shard-key` on the paired slot). Today the accept-set is the
6723 /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
6724 /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
6725 /// per-entity extractor expression; `SingleNode` (Erlang/OTP
6726 /// distributed-app takeover — §II.1) and `Replicated` (active-active
6727 /// across every named cluster) have no hash-keyed routing axis to
6728 /// consume the slot and refuse a declared-but-inert `:shard-key`
6729 /// through [`AplicacaoError::ShardKeyOnNonSharded`].
6730 ///
6731 /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
6732 /// satisfies `placement.shard_key().is_some() ==
6733 /// placement.estrategia().requires_shard_key()` by construction — the
6734 /// cross-slot partition the pin
6735 /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
6736 /// locks load-bearing, so every downstream consumer that reaches for
6737 /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6738 /// CR materializer's per-CR shard-key resolver, the future
6739 /// [`feira app graph --shard-key`] per-Aplicacao column, the future
6740 /// per-cluster Akka-style cluster-sharding reconciler's per-entity
6741 /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
6742 /// shard-key requirement probe, a future author-facing tatara-lisp
6743 /// linter that flags `(:placement (:estrategia Replicated :shard-key
6744 /// "tenantId"))` shapes before `feira lint` reaches
6745 /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
6746 /// the substrate primitive — the predicate names *the cross-slot
6747 /// invariant*, not the arm identity.
6748 ///
6749 /// Prior to this lift the "does this strategy consume `:shard-key`"
6750 /// classification lived under the `gen_platform::IsVariant`-derived
6751 /// [`Self::is_sharded`] predicate at three fixture-builder sites in
6752 /// this crate (the [`tests::placement_strategy_variants_round_trip`]
6753 /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
6754 /// } else { None }` cascade, the
6755 /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
6756 /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
6757 /// "tenantId".to_string())` cascade, and the
6758 /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
6759 /// per-variant spec-mutator's identical `.is_sharded().then(…)`
6760 /// cascade). Each site conflated two semantically distinct questions:
6761 /// "is the variant `Sharded`?" (arm-identity, what
6762 /// [`Self::is_sharded`] answers) and "does the variant consume
6763 /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
6764 /// The two questions land on the same three-way answer under today's
6765 /// closed accept-set (both trip on the singleton `{Sharded}`), but a
6766 /// future arm addition that consumed `:shard-key` under a different
6767 /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
6768 /// §II.5 roadmap-hint names that hash-partitions across the cluster
6769 /// pool by client-IP hash rather than an author-declared extractor
6770 /// expression, a hypothetical `WeightedShard` variant that carries a
6771 /// shard-key + per-cluster weight table under a promoted M5
6772 /// adaptive-placement engine) or an addition that did *not* consume
6773 /// `:shard-key` on a semantically Sharded-shaped arm would silently
6774 /// split the two questions. Any consumer that read
6775 /// `.is_sharded().then(…)` for the shard-key requirement gate would
6776 /// silently misclassify the new arm as non-consuming — a fixture
6777 /// builder would omit `:shard-key` where the new arm required one and
6778 /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
6779 /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
6780 /// commit, a future M4 CR materializer would fall through the
6781 /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
6782 /// silently emit an empty extractor at the Akka reconciler layer.
6783 ///
6784 /// Lifting the classification as a substrate-primitive method on the
6785 /// closed-set typed enum names the cross-slot invariant on the
6786 /// primitive that owns the partition: every future arm addition
6787 /// declares its `:shard-key` consumption in one place (this predicate's
6788 /// `match self` arm-set), and every downstream consumer that reaches
6789 /// for the paired shape reads through one typed dispatch. Same
6790 /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
6791 /// per-arm predicate on the pre-projection WIT-shape axis and the
6792 /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
6793 /// paired predicate on the post-projection typed-view axis — a
6794 /// per-arm semantic-classification predicate paired with the
6795 /// arm-identity predicate the derive already emits, closing the drift
6796 /// footgun on the cross-slot invariant axis.
6797 ///
6798 /// Method-named `requires_shard_key` (not `has_shard_key`, not
6799 /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
6800 /// invariant reads as "this strategy *requires* the paired
6801 /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
6802 /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
6803 /// merely omit it. The `has_*` framing would read as an accessor
6804 /// (returning the presence of an already-carried value) rather than a
6805 /// requirement (naming the invariant the paired slot must satisfy).
6806 /// Returns `bool` (not `Option<()>` or a marker-type witness), same
6807 /// shape as the sibling [`WitContract::is_capability`] /
6808 /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
6809 /// arm-family, so every consumer reaches for `.requires_shard_key()`
6810 /// as a drop-in replacement for the `.is_sharded()` conflated read
6811 /// without a return-shape migration.
6812 #[must_use]
6813 pub const fn requires_shard_key(self) -> bool {
6814 match self {
6815 Self::Sharded => true,
6816 Self::SingleNode | Self::Replicated => false,
6817 }
6818 }
6819}
6820
6821// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
6822// cross-slot-invariant per-arm predicate: the module-scope const-eval
6823// assertions below trip at caixa-core build time (not test time) if a
6824// future edit rewires the predicate's arm-set away from the singleton
6825// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
6826// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
6827// runtime pin covers the same truth-table with a more descriptive
6828// diagnostic on failure; these const-eval items add a build-time failure
6829// surface strictly stronger than the runtime pin (a downstream renderer's
6830// `const`-context reader that composed against a rebound predicate would
6831// still surface here before the test suite even ran) and side-step the
6832// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
6833// would otherwise accumulate on the caixa-core module baseline.
6834const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
6835const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
6836const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
6837
6838/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
6839/// the pretty-printed byte-string every consumer that formats the strategy
6840/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
6841/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
6842/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
6843/// per-Aplicacao strategy line, the future M4 CR materializer's per-
6844/// admission-webhook rejection body) reaches for the same lifted
6845/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
6846/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6847/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
6848/// `Serialize` derive already emits under
6849/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
6850/// [`PlacementStrategy::as_str`] helper already returns.
6851///
6852/// Until this lift landed the sibling OTP-shape typed enums —
6853/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
6854/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
6855/// so [`std::fmt::Display`] routes through the same discriminant string
6856/// the wire format emits) — carried a stable [`std::fmt::Display`]
6857/// surface but [`PlacementStrategy`] did not; every consumer reaching
6858/// for a strategy byte-string past the wire format had to pick between
6859/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
6860/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
6861/// derive), any two of which a future variant rename or
6862/// `#[serde(rename_all = "kebab-case")]` attribute would silently
6863/// desynchronize — with the failure surfacing as a downstream renderer /
6864/// operator's per-strategy dispatch reading one spelling while the wire
6865/// format emitted another, far from the source rebrand commit and with
6866/// no field naming the drift. Routing `Display` through
6867/// [`PlacementStrategy::as_str`] makes the three paths
6868/// (`Debug` for structural inspection, `Display` for user-facing text,
6869/// `Serialize` for the wire format) converge on the same lifted
6870/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
6871/// the diagnostic byte-string, and the pretty-printed byte-string move
6872/// as a single unit through one canonical declaration each, by
6873/// construction. Same trajectory as [`PlacementStrategy::as_str`]
6874/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
6875/// closes the third path.
6876///
6877/// Pin tests
6878/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
6879/// and
6880/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
6881/// assert the three paths agree byte-for-byte on every variant, so a
6882/// future variant rename or per-arm serde attribute drift is a build
6883/// error visible at caixa-core test time, not a silent per-consumer
6884/// dispatch miss at apply / reconcile time.
6885impl std::fmt::Display for PlacementStrategy {
6886 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6887 f.write_str(self.as_str())
6888 }
6889}
6890
6891/// Substrate-canonical [`AsRef<str>`] projection on the M3
6892/// per-Aplicacao distribution-strategy [`PlacementStrategy`] closed-set
6893/// typed enum — routes through the same [`PlacementStrategy::as_str`]
6894/// `pub const fn` scalar accessor the paired [`std::fmt::Display`] impl
6895/// and the un-`rename`d [`serde::Serialize`] derive already key off, so
6896/// any future consumer that binds a [`PlacementStrategy`] through the
6897/// standard-library `impl AsRef<str>` bound (a future `feira app
6898/// placement --set <arm>` verb that composes the emitted
6899/// `PascalCase`/camelCase wire scalar into a
6900/// [`std::process::Command::arg`] shell-out of the future
6901/// `lareira-fleet-programs` aggregator's per-Aplicacao gate, a
6902/// per-Aplicacao structured-log recorder on the future `app-operator`'s
6903/// hierarchical reconciliation surface that accepts `impl AsRef<str>`
6904/// at the `tracing::field::Value` `Str`-arm, a
6905/// [`std::collections::HashMap`] lookup keyed on the strategy wire byte
6906/// through `map.get::<str>(strategy.as_ref())` on a future
6907/// per-strategy dispatch table the M5 adaptive-placement engine
6908/// composes) reaches the paired
6909/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
6910/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6911/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted-const
6912/// through one substrate-primitive dispatch rather than an open-coded
6913/// `.as_str()` projection at every wire-up.
6914///
6915/// Peer of the sibling [`std::fmt::Display`] impl on the same
6916/// primitive — both delegate to the shared
6917/// [`PlacementStrategy::as_str`] `pub const fn` accessor, so
6918/// [`format!("{v}")`], `v.as_str()`, and `<PlacementStrategy as
6919/// AsRef<str>>::as_ref(&v)` resolve to the same byte-string per
6920/// instance by construction. A future variant rename or `#[serde(rename_all
6921/// = "kebab-case")]` attribute-drift on the enum reaches every one of
6922/// the three paths (plus the wire-format `Serialize` derive that
6923/// already routes through the same lifted const) through exactly one
6924/// caixa-core edit.
6925///
6926/// Same "route the trait impl through the substrate-primitive
6927/// accessor" discipline the sibling [`crate::CaixaVersion`]
6928/// [`AsRef<str>`] impl (16d5c7e), the paired M2
6929/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
6930/// (63eb1a4), and the paired M2 [`crate::supervisor::RestartPolicy`]
6931/// [`AsRef<str>`] impl (419ea81) carry — closes the M2/M3
6932/// closed-set-typed-enum family's standard-library [`AsRef<str>`]
6933/// projection axis onto the last remaining M3 mesh-primitive-defining
6934/// slot, so every OTP/mesh-shape closed-set typed enum on the caixa
6935/// surface now carries the paired [`AsRef<str>`] + [`fmt::Display`] +
6936/// `as_str` triple through one lifted `M3_PLACEMENT_ESTRATEGIA_*` /
6937/// `SUPERVISOR_*` const. Rust-side newtype/typed-enum convention pairs
6938/// [`AsRef<str>`] and [`fmt::Display`] on the same primitive so a
6939/// caller who has one has both; before this lift,
6940/// [`PlacementStrategy`] carried [`fmt::Display`] but not the paired
6941/// [`AsRef<str>`] impl the convention names.
6942///
6943/// Pinned load-bearing by
6944/// [`tests::placement_strategy_as_ref_str_routes_through_as_str_accessor`]
6945/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
6946/// three-arm closed set) and
6947/// [`tests::placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`]
6948/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
6949/// resolve to the same lifted `M3_PLACEMENT_ESTRATEGIA_*` const per
6950/// arm) — any future silent detour that routes the impl through a
6951/// divergent projection (a per-arm inline `match self { … }`
6952/// re-inlining that opens a compile-time link to the un-lifted
6953/// arm-literal, a swap onto the kebab-case
6954/// [`gen_platform::Discriminant`] catalog identity that would collide
6955/// the wire axis with the dispatcher-catalog axis) trips at
6956/// caixa-core test time under `assert_eq!` rather than at a downstream
6957/// `impl AsRef<str>`-bound consumer's silent split.
6958impl AsRef<str> for PlacementStrategy {
6959 fn as_ref(&self) -> &str {
6960 self.as_str()
6961 }
6962}
6963
6964/// Trait-idiomatic reverse projection on the M3-mesh-primitive-defining
6965/// [`PlacementStrategy`] closed-set typed enum — routes byte-for-byte
6966/// through the paired substrate-primitive [`PlacementStrategy::from_wire`]
6967/// `Option<Self>` accessor so every future consumer that binds a
6968/// camelCase-schema `:placement :estrategia` wire byte-string through the
6969/// standard-library `.try_into()` / [`TryFrom`] axis (a future `feira app
6970/// placement --set <SingleNode|Replicated|Sharded>` CLI arg-parse that
6971/// composes into `let estrategia: PlacementStrategy = s.try_into()?`, a
6972/// future `mesh.pleme.io/v1alpha1/Aplicacao` CR admission-webhook that
6973/// folds a `spec.placement.estrategia: String` field through
6974/// `PlacementStrategy::try_from(&s)?`, a generic `<T: TryFrom<&str>>`-
6975/// bound loader over any of the substrate's closed-set typed enums)
6976/// reaches the same three-arm accept-set the sibling
6977/// [`PlacementStrategy::from_wire`] resolver parses through and the
6978/// sibling [`PlacementStrategy::as_str`] emits, rather than an open-coded
6979/// per-arm `match s { "SingleNode" => …, "Replicated" => …, "Sharded" =>
6980/// …, _ => … }` cascade whose arm-set has no compile-time link back to
6981/// the substrate primitive.
6982///
6983/// Complements the pre-existing forward-projection triple
6984/// ([`std::fmt::Display`], [`AsRef<str>`], [`PlacementStrategy::as_str`])
6985/// with the paired trait-idiomatic reverse-projection axis: Rust-side
6986/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
6987/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
6988/// caller who can project *out to* a `&str` can also project *in from*
6989/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
6990/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
6991/// lint the sibling method-named [`PlacementStrategy::from_wire`] would
6992/// trigger under a `FromStr` impl (the same design tradeoff the peer
6993/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
6994/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks note)
6995/// — this impl closes the trait-idiomatic reverse axis without
6996/// disturbing the method-named `from_wire` shape every sibling closed-set
6997/// typed enum on the substrate already carries.
6998///
6999/// `type Error = ()` matches the sibling [`PlacementStrategy::from_wire`]'s
7000/// `Option<Self>` return-shape's deliberate deferral of error typing:
7001/// the caller picks the diagnostic form appropriate for its use site (a
7002/// future `feira app placement --set` arg-parse composes its own per-verb
7003/// "unknown strategy: <arg> — accepted: {…}" message enumerating
7004/// [`PlacementStrategy::ALL`], a future M4 admission-webhook rejection
7005/// body wraps the `Err(())` outcome with the accepted-set enumeration for
7006/// operator diagnostics, a `Result::map_err` at the call site lifts the
7007/// unit-error to a per-verb error type).
7008///
7009/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
7010/// set the [`PlacementStrategy::from_wire`] resolver dispatches through,
7011/// so any future arm addition (an `Anycast` mesh-anycast arm the
7012/// MESH-COMPOSITION §II.5 hint names as a trajectory item) grows the
7013/// trait-idiomatic axis by construction — one caixa-core edit on
7014/// [`PlacementStrategy::from_wire`] extends both the method-named reverse
7015/// projection every existing consumer keys off and the trait-idiomatic
7016/// reverse projection this impl exposes, without a coordinated rewrite
7017/// across every future `TryFrom<&str>`-bound consumer's arm-set.
7018///
7019/// Extends the substrate-wide closed-set-enum reverse-projection family
7020/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
7021/// bf33136) onto the first M3-mesh-primitive-defining slot enum on the
7022/// caixa surface — the `:placement :estrategia` closed set the
7023/// caixa-mesh renderer keys off end-to-end.
7024///
7025/// Pinned load-bearing by
7026/// [`tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7027/// (byte-parity pin against [`PlacementStrategy::from_wire`] across the
7028/// three-arm accept-set) and
7029/// [`tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7030/// (rejection witness against silent accept-set widening).
7031impl TryFrom<&str> for PlacementStrategy {
7032 type Error = ();
7033
7034 fn try_from(s: &str) -> Result<Self, Self::Error> {
7035 Self::from_wire(s).ok_or(())
7036 }
7037}
7038
7039/// Trait-idiomatic forward projection on the M3-mesh-primitive-defining
7040/// [`PlacementStrategy`] closed-set typed enum — routes byte-for-byte
7041/// through the paired substrate-primitive [`PlacementStrategy::as_str`]
7042/// `pub const fn` accessor via `strategy.as_str()`. Return type is
7043/// `&'static str` by construction — every [`PlacementStrategy::as_str`]
7044/// arm resolves to a paired lifted
7045/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
7046/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
7047/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] `pub const &str`
7048/// with static lifetime, so the trait's return-type promise is upheld
7049/// structurally without a `String::leak()` cast or a per-arm inline
7050/// literal.
7051///
7052/// Complements the pre-existing forward-projection triple
7053/// ([`std::fmt::Display`], [`AsRef<str>`], [`PlacementStrategy::as_str`])
7054/// with the trait-idiomatic forward-projection axis: Rust-side
7055/// newtype/typed-enum convention pairs [`TryFrom<&str>`] with the mirror-
7056/// image [`From<Self> for &'static str`] on the same primitive so a
7057/// caller who can project *in from* a `&str` via the trait axis can also
7058/// project *out to* one under a `'static`-lifetime bound. The
7059/// [`AsRef<str>`] impl already carries the same emit-set on the borrowed
7060/// return path; this impl closes the trait-idiomatic axis pair with the
7061/// stricter `&'static str` lifetime the sibling [`AsRef<str>`] cannot
7062/// promise (its return borrows from `&self`, not from the
7063/// [`PlacementStrategy::as_str`] `pub const fn`'s static-string result).
7064///
7065/// Same "route the trait impl through the substrate-primitive accessor"
7066/// discipline the sibling [`crate::supervisor::RestartStrategy`]
7067/// `From<Self> for &'static str` impl (523157d — first-mover on this
7068/// forward-projection family), [`crate::supervisor::RestartPolicy`]
7069/// `From<Self> for &'static str` impl (9fb37d0 — second peer, closing
7070/// the M2 OTP-shape sibling pair), [`crate::CaixaKind`]
7071/// `From<Self> for &'static str` impl (edb827b — third peer, opening
7072/// the campaign onto the top-level caixa surface), and
7073/// [`crate::CaixaDialeto`] `From<Self> for &'static str` impl (c189a6f
7074/// — fourth peer, extending onto the dialect-classification axis)
7075/// carry — extends the substrate primitive's trait-idiomatic forward-
7076/// projection axis onto the fifth closed-set fieldless typed enum on
7077/// the caixa surface: the M3-mesh-primitive-defining `:placement
7078/// :estrategia` closed-set axis the caixa-mesh renderer keys off end-
7079/// to-end, previously carrying the paired [`std::fmt::Display`] /
7080/// [`AsRef<str>`] / [`PlacementStrategy::as_str`] / [`TryFrom<&str>`] /
7081/// [`PlacementStrategy::from_wire`] forward+reverse projections but not
7082/// yet the trait-idiomatic forward projection with the `&'static str`
7083/// lifetime bound.
7084///
7085/// Same shape as the sibling [`crate::CaixaDialeto`] axis pair:
7086/// [`PlacementStrategy::as_str`] output and
7087/// [`PlacementStrategy::from_wire`] input share the same camelCase-
7088/// schema `PascalCase` vocabulary by construction (the same three
7089/// lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants
7090/// dispatch on both halves) — the trait-idiomatic axis pair
7091/// ([`From<Self> for &'static str`] + [`TryFrom<&str> for Self`])
7092/// therefore round-trips directly, without an intermediate wire-vocab
7093/// hop the peer [`crate::CaixaKind`] axis pair requires. This lift
7094/// extends the "direct round-trip" precedent
7095/// [`crate::CaixaDialeto`] (c189a6f) established onto the first M3-
7096/// mesh-primitive-defining slot enum.
7097///
7098/// The paired [`PlacementStrategy::as_str`] accessor's three-arm emit-
7099/// set is the single source of truth — every future arm addition (an
7100/// `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint names as
7101/// a trajectory item, a hypothetical `WeightedShard` variant that
7102/// carries a shard-key + per-cluster weight table under a promoted M5
7103/// adaptive-placement engine) grows the trait-idiomatic forward axis
7104/// by construction: one caixa-core edit on
7105/// [`PlacementStrategy::as_str`] extends every one of the sibling
7106/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
7107/// [`PlacementStrategy::as_str`] itself, and this [`From<Self> for
7108/// &'static str`]) without a coordinated rewrite across every future
7109/// `Into<&'static str>`-bound consumer's arm-set. This lift closes the
7110/// fifth peer on the trait-idiomatic forward-projection campaign the
7111/// recently-landed peer commits opened; the remaining nine closed-set
7112/// typed enums on the caixa substrate surface (`WitShape`,
7113/// `RateLimitUnit`, `PathShapeViolation`, `InvariantKind`,
7114/// `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
7115/// `FerriteRuntime`) are the future targets of this campaign.
7116///
7117/// Pinned load-bearing by
7118/// [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
7119/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
7120/// three-arm emit-set, plus a `const`-context materialization witness
7121/// for the `&'static str` lifetime promise routed through the paired
7122/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] lifted constants, plus
7123/// a paired `.into()` shape assertion covering the blanket-derived
7124/// `Into<&'static str>` shape) and
7125/// [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
7126/// (partition pin asserting `<&'static str as
7127/// From<PlacementStrategy>>::from` and [`PlacementStrategy::as_str`]
7128/// agree on every arm, plus a two-way direct round-trip witness through
7129/// the paired trait-idiomatic [`TryFrom<&str>`] axis that closes the
7130/// two-way `Self ↔ &'static str` round-trip on the trait-idiomatic
7131/// axis pair without the wire-vocab intermediate the peer
7132/// [`crate::CaixaKind`] axis pair requires — the emit-side
7133/// [`PlacementStrategy::as_str`] and the parse-side
7134/// [`PlacementStrategy::from_wire`] dispatch on the same three lifted
7135/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants by
7136/// construction, so round-tripping composes the two trait impls
7137/// directly).
7138impl From<PlacementStrategy> for &'static str {
7139 fn from(strategy: PlacementStrategy) -> &'static str {
7140 strategy.as_str()
7141 }
7142}
7143
7144/// Where the Aplicacao runs.
7145#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
7146#[serde(rename_all = "camelCase")]
7147pub struct Placement {
7148 /// Distribution strategy.
7149 #[serde(default)]
7150 pub estrategia: PlacementStrategy,
7151
7152 /// Named clusters that host this Aplicacao. Required for
7153 /// `Replicated` and `SingleNode`; for `Sharded` declares the
7154 /// shard pool.
7155 #[serde(default)]
7156 pub clusters: Vec<String>,
7157
7158 /// Optional hint to the placement engine: `"data-locality"`,
7159 /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
7160 #[serde(default, skip_serializing_if = "Option::is_none")]
7161 pub affinity: Option<String>,
7162
7163 /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
7164 #[serde(default, skip_serializing_if = "Option::is_none")]
7165 pub shard_key: Option<String>,
7166}
7167
7168impl Placement {
7169 /// Substrate-canonical per-`:placement` Akka-cluster-sharding
7170 /// `:shard-key` extractor-expression scalar accessor every consumer
7171 /// of the Aplicacao's hash-keyed distribution routing keys off —
7172 /// returns the author-declared `:placement :shard-key` byte-string
7173 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
7174 /// own `Option<String>` storage; `None` when the slot is absent
7175 /// (the canonical shape under `:estrategia Replicated` /
7176 /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
7177 /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
7178 /// partition — `validate` refuses any `Placement` past this call
7179 /// that lands `Some` on a non-`Sharded` strategy or `None` on
7180 /// `Sharded`).
7181 ///
7182 /// The `:placement :shard-key` slot carries the Akka-style
7183 /// cluster-sharding entity-id extractor expression
7184 /// (MESH-COMPOSITION §II.4) — validated by
7185 /// [`validate_placement_shard_key`] to be a non-empty printable-
7186 /// ASCII single-token reference (`tenantId`, `$tenantId`,
7187 /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
7188 /// future M4 Akka-style cluster-sharding reconciler hashes without
7189 /// re-validating at the runtime layer), and every downstream
7190 /// consumer that reads the key keys off this scalar (the
7191 /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
7192 /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
7193 /// declared-but-inert refusal diagnostic, the caixa-mesh
7194 /// per-Aplicacao `placement.shardKey` emit path the substrate
7195 /// operator's per-entity hash-routing reader consumes, the future
7196 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7197 /// per-shard-key resolver).
7198 ///
7199 /// Prior to this lift the `.shard_key` field was accessed inline at
7200 /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
7201 /// `Sharded` arm's `match &self.placement.shard_key { None => …,
7202 /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
7203 /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
7204 /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
7205 /// — two open-coded field-accesses that expressed no compile-time
7206 /// link back to the typed slot. A future extension of the
7207 /// `:placement :shard-key` axis to a richer author surface — a
7208 /// per-cluster override the operator pins through a future
7209 /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
7210 /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
7211 /// alias table the M4 CR materializer resolves per-CR, a
7212 /// per-Aplicacao dynamic `:shard-key` derivation the future
7213 /// adaptive placement engine computes from `:affinity` weights —
7214 /// would have had to be threaded through both open-coded copies in
7215 /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
7216 /// arm refusal would silently disagree on which extractor
7217 /// expression a given Placement resolves to. Lifting the resolution
7218 /// rule to a typed method on the substrate primitive means every
7219 /// downstream consumer of the Aplicacao's per-`:placement`
7220 /// hash-key surface reaches for exactly one typed dispatch — the
7221 /// resolver's accept-set migrates as a unit on any future axis
7222 /// addition.
7223 ///
7224 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
7225 /// [`WitContract::destination`] / [`WitContract::world_ref`]
7226 /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
7227 /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
7228 /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
7229 /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
7230 /// typed dispatch on the substrate primitive, thin projections at
7231 /// each consumer" discipline extended onto the per-`:placement`
7232 /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
7233 /// First `Option<&str>`-return accessor on the M3 mesh-slot family
7234 /// — opens the "optional per-slot scalar" projection pattern the
7235 /// sibling per-`:placement` `:affinity`, per-`:politicas`
7236 /// `:rate-limit` future lifts fold on. Named `shard_key()` to
7237 /// match the storage field's name; the accessor's identity name
7238 /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
7239 /// slot's docstring already carries.
7240 #[must_use]
7241 pub const fn shard_key(&self) -> Option<&str> {
7242 match &self.shard_key {
7243 Some(s) => Some(s.as_str()),
7244 None => None,
7245 }
7246 }
7247
7248 /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
7249 /// compression-hint scalar accessor every weighting-consumer of the
7250 /// Aplicacao's per-hint routing surface keys off — returns the
7251 /// author-declared `:placement :affinity` byte-string verbatim as
7252 /// an `Option<&str>`, borrowed from the typed slot's own
7253 /// `Option<String>` storage; `None` when the slot is absent (the
7254 /// canonical shape of an Aplicacao that leaves the compression
7255 /// weighting up to the placement engine's cluster-default arm — no
7256 /// author-authored `data-locality` / `low-latency` / etc. hint
7257 /// biases the routing).
7258 ///
7259 /// The `:placement :affinity` slot carries the M3 Adaptive-
7260 /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
7261 /// by [`validate_placement_affinity`] to be a DNS-1123 label
7262 /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
7263 /// K8s-conformant label-selector shape every apiserver-side pod-
7264 /// affinity / node-affinity materializer already gates on
7265 /// admission), and every downstream consumer that reads the hint
7266 /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
7267 /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
7268 /// `placement.affinity` overlay emit path the substrate operator's
7269 /// per-hint weighting-consumer reads, the future M4
7270 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
7271 /// pod-affinity / node-affinity selector resolver).
7272 ///
7273 /// Prior to this lift the `.affinity` field was accessed inline at
7274 /// the sole caixa-core site — the
7275 /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
7276 /// `if let Some(a) = &self.placement.affinity { …
7277 /// validate_placement_affinity(a)? … }` cascade — one open-coded
7278 /// field-access that expressed no compile-time link back to the
7279 /// typed slot. A future extension of the `:placement :affinity`
7280 /// axis to a richer author surface — a per-cluster override the
7281 /// operator pins through a future `:placement :affinity-overrides`
7282 /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
7283 /// tenant hint alias table the M4 CR materializer resolves per-CR,
7284 /// a per-Aplicacao dynamic `:affinity` derivation the future
7285 /// adaptive placement engine computes from `:clusters` topology —
7286 /// would have had to be threaded through the open-coded copy in
7287 /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
7288 /// materializer reader that landed on the axis, or the per-hint
7289 /// value-shape gate and its downstream weighting consumers would
7290 /// silently disagree on which hint a given Placement resolves to.
7291 /// Lifting the resolution rule to a typed method on the substrate
7292 /// primitive means every downstream consumer of the Aplicacao's
7293 /// per-`:placement` compression-hint surface reaches for exactly
7294 /// one typed dispatch — the resolver's accept-set migrates as a
7295 /// unit on any future axis addition.
7296 ///
7297 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
7298 /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
7299 /// optional-scalar axis — same "one typed dispatch on the substrate
7300 /// primitive, thin projections at each consumer" discipline extended
7301 /// onto the per-`:placement` M3-Adaptive-compression-hint
7302 /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
7303 /// return accessor on the M3 mesh-slot family; closes the last
7304 /// un-lifted per-`:placement` `Option<String>` axis. Named
7305 /// `affinity()` to match the storage field's name; the accessor's
7306 /// identity name maps onto the canonical MESH-COMPOSITION §II.4
7307 /// vocabulary the slot's docstring already carries.
7308 #[must_use]
7309 pub const fn affinity(&self) -> Option<&str> {
7310 match &self.affinity {
7311 Some(s) => Some(s.as_str()),
7312 None => None,
7313 }
7314 }
7315
7316 /// Substrate-canonical per-`:placement` `:estrategia` distribution-
7317 /// strategy scalar accessor every consumer that dispatches on the
7318 /// Aplicacao's per-cluster distribution shape keys off — returns the
7319 /// author-declared `:placement :estrategia` variant verbatim as a
7320 /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
7321 /// `PlacementStrategy` storage.
7322 ///
7323 /// The `:placement :estrategia` slot carries the closed-set
7324 /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
7325 /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
7326 /// `Replicated` — active-active across every named cluster; `Sharded`
7327 /// — Akka-style hash-keyed entity distribution across the cluster pool
7328 /// per §II.4) that every downstream consumer of the Aplicacao's
7329 /// per-cluster fan-out shape keys off. Validated by
7330 /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
7331 /// the sibling `:shard-key` axis (`shard_key.is_some() ==
7332 /// matches!(estrategia, Sharded)` — the cross-slot partition the
7333 /// [`Placement::shard_key`] accessor's docstring pins), and every
7334 /// downstream consumer that reads the strategy keys off this scalar
7335 /// (the [`AplicacaoSpec::validate_placement`]
7336 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
7337 /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
7338 /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
7339 /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
7340 /// declared-but-inert refusal's
7341 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
7342 /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
7343 /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
7344 /// emit path the substrate operator's per-strategy fan-out reader
7345 /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
7346 /// materializer's per-strategy admission-webhook resolver).
7347 ///
7348 /// Prior to this lift the `.estrategia` field was accessed inline at
7349 /// four sites — the [`AplicacaoSpec::validate_placement`]
7350 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
7351 /// `estrategia: self.placement.estrategia`, the same method's
7352 /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
7353 /// partition dispatch, the non-`Sharded`-arm
7354 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
7355 /// `estrategia: self.placement.estrategia`, and the `feira app graph`
7356 /// per-Aplicacao strategy print line at
7357 /// `println!("… {} …", spec.placement.estrategia, …)`
7358 /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
7359 /// expressed no compile-time link back to the typed slot. A future
7360 /// extension of the `:placement :estrategia` axis to a richer author
7361 /// surface (a per-cluster override the operator pins through a future
7362 /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
7363 /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
7364 /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
7365 /// derivation the future adaptive placement engine computes from
7366 /// `:affinity` + `:clusters` topology) would have had to be threaded
7367 /// through every open-coded copy in lockstep — one consumer reading
7368 /// the raw variant while a peer read the operator-resolved variant
7369 /// would silently split the `PlacementWithoutClusters` /
7370 /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
7371 /// partition-dispatch input, a two-consumer split at the validator
7372 /// far from the source `caixa.lisp` with no field naming the
7373 /// strategy-drift root cause. Lifting the resolution rule to a typed
7374 /// method on the substrate primitive means every downstream consumer
7375 /// of the Aplicacao's per-`:placement` distribution-strategy surface
7376 /// reaches for exactly one typed dispatch — the resolver's accept-set
7377 /// migrates as a unit on any future axis addition.
7378 ///
7379 /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
7380 /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
7381 /// same "one typed dispatch on the substrate primitive, thin
7382 /// projections at each consumer" discipline extended onto the
7383 /// per-`:placement` distribution-strategy `Copy`-composite-enum
7384 /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
7385 /// family; first `Copy`-return accessor on the M3 mesh-slot
7386 /// `Placement` type — companion to the sibling per-`:placement`
7387 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
7388 /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
7389 /// optional-scalar axes, closing the last unlifted per-`:placement`
7390 /// scalar-value axis (the closed-set `PlacementStrategy`
7391 /// distribution-strategy discriminator) so every downstream
7392 /// per-`:placement` reader now routes through a typed dispatch on
7393 /// the substrate primitive. Named `estrategia()` to match the storage
7394 /// field's name; the accessor's identity name maps onto the
7395 /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
7396 /// already carries. Declared `pub const fn` (matching the peer M3
7397 /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
7398 /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
7399 /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
7400 /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
7401 /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
7402 /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
7403 /// [`RateLimit`] — every one a `pub const fn`) so every future
7404 /// substrate-side `const`-context consumer of the resolved
7405 /// distribution-strategy variant (a `const _: () = assert!(…)`
7406 /// module-scope invariant pin on a per-fixture typed [`Placement`],
7407 /// a future M4 admission-webhook `const fn` resolver over a typed
7408 /// [`Placement`], any `const fn` composer that fans on the strategy
7409 /// at compile time) reaches through the same typed dispatch on the
7410 /// substrate primitive at const-eval time as at runtime. Pinned by
7411 /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
7412 /// const-eval posture at module scope via `const _:() = …` items so
7413 /// any future accidental downgrade to non-`const` trips at caixa-core
7414 /// build time.
7415 #[must_use]
7416 pub const fn estrategia(&self) -> PlacementStrategy {
7417 self.estrategia
7418 }
7419
7420 /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
7421 /// per-cluster distribution-target slice accessor every consumer that
7422 /// walks the Aplicacao's declared cluster-pool keys off — returns the
7423 /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
7424 /// `&[String]` slice-view, borrowed from the typed slot's own
7425 /// `Vec<String>` storage (a zero-copy slice-view over the same
7426 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
7427 /// through). Non-optional: the empty slice is the load-bearing
7428 /// pre-validation sentinel every downstream consumer of the paired
7429 /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
7430 /// off — every strategy in the closed
7431 /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
7432 /// requires a non-empty list (`SingleNode` / `Replicated` use the
7433 /// list as hosting / takeover candidates per Erlang/OTP distributed-
7434 /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
7435 /// shard pool per Akka cluster-sharding convention, §II.4), so the
7436 /// `.is_empty()` probe is the shared pre-condition every
7437 /// [`AplicacaoSpec::validate_placement`] arm heads on.
7438 ///
7439 /// The `:placement :clusters` slot carries the K8s-conformant DNS-
7440 /// 1123-label per-cluster distribution-target list — the same
7441 /// set-not-multiset shape the sibling `:membros :caixa` /
7442 /// `:children :caixa` axes carry (`validate_placement`'s per-entry
7443 /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
7444 /// pins the shape). Every downstream consumer that fans on the list
7445 /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
7446 /// pre-flight `.is_empty()` probe that trips
7447 /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
7448 /// per-cluster value-shape + duplicate-detection fan-out loop, the
7449 /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
7450 /// that materializes the list verbatim onto every
7451 /// programs.yaml entry the substrate operator's per-cluster
7452 /// `placement.clusters | contains .Values.cluster` filter reads,
7453 /// the `feira app graph` per-Aplicacao cluster print line, the
7454 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7455 /// per-cluster admission-webhook fan-out, the future M5 adaptive-
7456 /// placement engine's cluster-topology reader).
7457 ///
7458 /// Prior to this lift the `.clusters` `Vec<String>` was accessed
7459 /// inline at three production sites — the
7460 /// [`AplicacaoSpec::validate_placement`] pre-flight
7461 /// `self.placement.clusters.is_empty()` refusal probe, the same
7462 /// method's per-cluster validate loop's
7463 /// `for c in &self.placement.clusters` traversal head, and the
7464 /// `feira app graph` per-Aplicacao print line's
7465 /// `spec.placement.clusters` `{:?}` formatter argument
7466 /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
7467 /// that expressed no compile-time link back to the typed slot. A
7468 /// future extension of the `:placement :clusters` axis to a richer
7469 /// author surface (a per-tenant cluster-pool overlay the operator
7470 /// pins through a future `:placement :clusters-overrides` slot the
7471 /// MESH-COMPOSITION §V cross-cluster-federation roadmap
7472 /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
7473 /// the future M5 adaptive-placement engine computes from
7474 /// `:affinity` weights + live cluster-topology probes, a promotion
7475 /// of the plain `Vec<String>` to a richer `{static, dynamic}`
7476 /// partition once the substrate operator's cluster-membership
7477 /// reconciler comes into typed scope) would have had to be threaded
7478 /// through all three open-coded copies in lockstep or one consumer
7479 /// would silently disagree with the peers on which cluster-pool a
7480 /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
7481 /// reading the raw slot while the peer per-cluster validate loop
7482 /// read an operator-resolved slot would silently split the paired
7483 /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
7484 /// `PlacementClusterDuplicate` refusal cascade's actual traversal
7485 /// input from the pre-flight input, a three-consumer split at the
7486 /// validator and formatter far from the source `caixa.lisp` with
7487 /// no field naming the cluster-pool-drift root cause. Lifting the
7488 /// resolution rule to a typed method on the substrate primitive
7489 /// means every downstream consumer of the Aplicacao's
7490 /// per-`:placement` cluster-pool surface reaches for exactly one
7491 /// typed dispatch — the resolver's accept-set migrates as a unit
7492 /// on any future axis addition.
7493 ///
7494 /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
7495 /// slot — sibling to the seed M2
7496 /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
7497 /// slice-return accessor on the peer per-`:supervisor` static-
7498 /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
7499 /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
7500 /// primitive, thin projections at each consumer" discipline. The
7501 /// three peer `Vec`-carry axes still unlifted at the time of this
7502 /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
7503 /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
7504 /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
7505 /// [`crate::UpgradeFromEntry::instructions`]
7506 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
7507 /// — inherit this accessor's discipline as future compounding runs
7508 /// migrate their consumers onto the shared slice-return shape.
7509 /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
7510 /// type, sibling to the two `Option<&str>`-return
7511 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
7512 /// (74ec2d3) accessors and the `Copy`-return
7513 /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
7514 /// unlifted per-`:placement` field axis (the `Vec<String>`
7515 /// distribution-target-list carrier) so every downstream
7516 /// per-`:placement` reader now routes through a typed dispatch on
7517 /// the substrate primitive. Named `clusters()` to match the storage
7518 /// field's name verbatim and the tatara-lisp author-surface term
7519 /// (`:clusters`) the field's own docstring already carries; the
7520 /// accessor's identity maps onto the canonical MESH-COMPOSITION
7521 /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
7522 /// for. Returns `&[String]` (not `&Vec<String>`) because every
7523 /// downstream consumer of the cluster list treats it as a read-only
7524 /// sequence — the slice-view is the narrowest borrow that supports
7525 /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
7526 /// `.len()`) without leaking the backing `Vec`'s
7527 /// grow/push/reserve surface that no consumer of the typed view
7528 /// reaches for (the storage-side `Vec` remains reachable through
7529 /// the `pub clusters` field for the mutation-carrying serde
7530 /// round-trip and per-test fixture-mutation paths).
7531 #[must_use]
7532 pub const fn clusters(&self) -> &[String] {
7533 self.clusters.as_slice()
7534 }
7535}
7536
7537impl Default for Placement {
7538 fn default() -> Self {
7539 Self {
7540 // Route the struct-literal `estrategia` default arm through
7541 // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
7542 // typed `pub const` rather than the transitively-derived
7543 // [`PlacementStrategy::default`] route — one source of truth
7544 // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
7545 // active-active-across-every-named-cluster arm
7546 // (MESH-COMPOSITION §II.2) that both this struct-literal
7547 // altitude and the sibling [`Default for PlacementStrategy`]
7548 // impl already key off through the same substrate primitive.
7549 // Pinned by
7550 // `placement_default_estrategia_routes_through_lifted_default`.
7551 estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
7552 clusters: Vec::new(),
7553 affinity: None,
7554 shard_key: None,
7555 }
7556 }
7557}
7558
7559// ── external entry point ─────────────────────────────────────────────
7560
7561/// External entry point — what an outside caller sees. Renders to a
7562/// Gateway / Ingress + a route to the named member Servico.
7563#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
7564#[serde(rename_all = "camelCase")]
7565pub struct Entrada {
7566 /// Public hostname (e.g. `"checkout.quero.cloud"`).
7567 pub host: String,
7568
7569 /// Member Servico the gateway routes to. Must be in `:membros`.
7570 pub para: String,
7571
7572 /// Optional path filter — if set, only matching paths route to
7573 /// this Aplicacao (the rest fall through to other route rules).
7574 #[serde(default)]
7575 pub paths: Vec<String>,
7576
7577 /// Default port on the destination Servico (the trigger.service.port).
7578 #[serde(default = "default_port")]
7579 pub port: u16,
7580}
7581
7582impl Entrada {
7583 /// Substrate-canonical per-`:entrada` URL-path fallback resolver
7584 /// every HTTPRoute-aware renderer keys off — returns the author-
7585 /// declared `:entrada :paths` list verbatim when non-empty, and the
7586 /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
7587 /// all fallback otherwise (so an Aplicacao author who declares an
7588 /// external `:entrada` block but no per-path rule surface still
7589 /// gets a route whose sole `HTTPPathMatch` matches every incoming
7590 /// request under the paired
7591 /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
7592 ///
7593 /// Prior to this lift the "if `:entrada :paths` is empty use the
7594 /// substrate catch-all; else return each declared path verbatim"
7595 /// cascade lived inline at
7596 /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
7597 /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
7598 /// per-Aplicacao HTTPRoute per-rule path-list emit site the
7599 /// substrate ships today, with no typed method on the substrate
7600 /// primitive that named the rule. A future path-resolution axis
7601 /// addition — a per-cluster `:entrada :default-path` override the
7602 /// operator pins through a future `:placement`-scoped slot, an
7603 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7604 /// admission-webhook floor that materializes the catch-all before
7605 /// the CR lands, a future per-`:entrada :paths` overlay from a
7606 /// per-cluster policy the future `feira app deploy` pipeline
7607 /// consumes — would have to be threaded through every renderer's
7608 /// inline copy of the cascade in lockstep or one consumer would
7609 /// silently disagree with the peers on which path list a given
7610 /// `:entrada` block resolves to. Lifting the rule to a typed
7611 /// method on the substrate primitive means every downstream
7612 /// HTTPRoute-aware consumer (the M4 CR materializer, the future
7613 /// per-cluster overlay resolver, every future per-Aplicacao
7614 /// snapshot renderer) reaches for exactly one typed dispatch —
7615 /// the resolver's accept-set moves as a unit on any future axis
7616 /// addition.
7617 ///
7618 /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
7619 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
7620 /// per-`:entrada` scalar-value axes — extends the "one typed
7621 /// dispatch on the substrate primitive, thin projections at each
7622 /// consumer" discipline onto the per-`:entrada` path-list
7623 /// resolution axis every HTTPRoute-aware renderer consumes. Same
7624 /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
7625 /// sibling `:politicas` primitive — one typed method on the
7626 /// substrate primitive that names the cascade every renderer
7627 /// otherwise re-inlines.
7628 #[must_use]
7629 pub fn resolved_paths(&self) -> Vec<&str> {
7630 // Route the internal cascade-head + per-entry projection reads
7631 // through the lifted [`Self::paths`] slice accessor rather than
7632 // the raw `self.paths` field access — the substrate-primitive
7633 // per-`:entrada` path-list resolver's two internal reads now
7634 // key off the canonical raw-slot surface every downstream
7635 // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
7636 // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
7637 // entrada summary line's `{:?}` Debug print) routes through, so
7638 // any future rebrand on the typed slot's raw-slot reader lands
7639 // at exactly one place. Same two-consumer coherence discipline
7640 // the sibling `Placement::clusters` (a6e18d7) accessor pins on
7641 // the peer M3 mesh-slot `Vec<String>`-carry axis.
7642 if self.paths().is_empty() {
7643 vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
7644 } else {
7645 self.paths().iter().map(String::as_str).collect()
7646 }
7647 }
7648
7649 /// Substrate-canonical per-`:entrada` DNS-hostname singular
7650 /// accessor every Gateway-API `Listener.hostname` reader keys off
7651 /// — returns the author-declared `:entrada :host` byte-string
7652 /// verbatim as a `&str`, borrowed from the typed slot's own
7653 /// [`String`] storage.
7654 ///
7655 /// Named the "singular" half of the DNS-hostname resolver pair on
7656 /// the substrate primitive: the parent-Gateway per-listener
7657 /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
7658 /// (`Listener.hostname: Option<PreciseHostname>` — at most one
7659 /// hostname per listener), and this accessor is the typed dispatch
7660 /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
7661 /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
7662 /// the per-HTTPRoute `spec.hostnames[]` list axis the same
7663 /// per-Aplicacao ingress-hostname surface projects onto.
7664 ///
7665 /// Prior to this lift the `entrada.host.clone()` byte-string was
7666 /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
7667 /// per-listener singular `hostname:` axis
7668 /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
7669 /// per-HTTPRoute plural `spec.hostnames[]` axis
7670 /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
7671 /// consumers read the same `entrada.host` field but the two-site
7672 /// duplication expressed no compile-time contract that the singular
7673 /// Gateway-listener filter and the plural `HTTPRoute` filter list
7674 /// stay in lockstep on future extensions of the `:entrada` slot to
7675 /// a multi-hostname author surface (an `:entrada :alt-hosts` list
7676 /// overlay, a per-cluster SNI fan-out the operator pins through a
7677 /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
7678 /// Aplicacao` CR materializer's per-listener virtual-host filter
7679 /// admission-webhook overlay). Any such extension would have to be
7680 /// threaded through every renderer's inline copy of the resolution
7681 /// in lockstep or the Gateway listener's `hostname:` filter would
7682 /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
7683 /// — a Gateway-API-conformance divergence whose apply-time symptom
7684 /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
7685 /// `NoMatchingParent` — the API server rejects the route because
7686 /// its `hostnames[]` filter doesn't intersect the parent listener's
7687 /// `hostname` filter) is far from the source `caixa.lisp` and never
7688 /// surfaces in the emitted YAML. Lifting the singular and plural
7689 /// resolvers to typed methods on the substrate primitive means
7690 /// every consumer of the Aplicacao's ingress-hostname surface
7691 /// reaches for exactly one typed dispatch, and the pair-invariant
7692 /// `hostnames() == vec![hostname()]` pinned by the sibling
7693 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
7694 /// keeps the two axes in lockstep by construction.
7695 ///
7696 /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
7697 /// (1449891) path-list resolver on the per-HTTPRoute per-rule
7698 /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
7699 /// the substrate primitive, thin projections at each consumer"
7700 /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
7701 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
7702 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
7703 /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
7704 /// `:entrada` scalar-value + list-value axes.
7705 #[must_use]
7706 pub const fn hostname(&self) -> &str {
7707 self.host.as_str()
7708 }
7709
7710 /// Substrate-canonical per-`:entrada` DNS-hostname plural
7711 /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
7712 /// keys off — returns the singleton `[hostname()]` list under
7713 /// today's single-hostname-per-Aplicacao author surface, and the
7714 /// authoritative multi-hostname list under a future
7715 /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
7716 ///
7717 /// Plural half of the DNS-hostname resolver pair — see the
7718 /// companion [`Entrada::hostname`] docstring for the two-consumer
7719 /// lift + pair-invariant discipline (`hostnames() ==
7720 /// vec![hostname()]`, pinned load-bearing by the sibling
7721 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
7722 /// test).
7723 ///
7724 /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
7725 /// per-`:entrada` plural-list resolver on the per-HTTPRoute
7726 /// per-rule path-list axis — same `Vec<&str>` shape, same
7727 /// substrate-primitive-owns-the-resolver discipline extended to
7728 /// the per-HTTPRoute virtual-host filter-list axis.
7729 #[must_use]
7730 pub fn hostnames(&self) -> Vec<&str> {
7731 vec![self.hostname()]
7732 }
7733
7734 /// Substrate-canonical per-`:entrada` destination-Servico scalar
7735 /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
7736 /// the author-declared `:entrada :para` byte-string verbatim as a
7737 /// `&str`, borrowed from the typed slot's own [`String`] storage.
7738 ///
7739 /// The `:entrada :para` slot names the single member Servico the
7740 /// external Gateway routes to (validated by
7741 /// [`AplicacaoSpec::validate`] to be a
7742 /// [`Membro::caixa`] the Aplicacao declares — a stray
7743 /// `:para` that doesn't name a member is
7744 /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
7745 /// backend-attachment miss at cluster-apply time). Under today's
7746 /// single-destination author surface `:entrada :para` is the ingress
7747 /// apex Servico's canonical identity; under a hypothetical
7748 /// future multi-backend author surface (a `:entrada
7749 /// :split :backends` weighted-fan-out overlay for canary /
7750 /// blue-green traffic-split rollouts, per-path override for
7751 /// path-based per-Servico routing beyond the single-apex model,
7752 /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7753 /// per-CR admission-webhook that promotes the scalar to a
7754 /// weighted list) this accessor is the substrate primitive's typed
7755 /// dispatch every downstream `HTTPRoute`-aware consumer routes
7756 /// through, so the resolution shape migrates as a unit on one
7757 /// caixa-core edit rather than a coordinated rewrite across every
7758 /// renderer's inline field-access.
7759 ///
7760 /// Prior to this lift the `entrada.para` byte-string was accessed
7761 /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
7762 /// `metadata.name` composer's per-destination discriminator arg
7763 /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
7764 /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
7765 /// per-HTTPRoute per-rule `backendRefs[0].name` axis
7766 /// (`entrada.para.clone()`,
7767 /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
7768 /// consumers read the same `entrada.para` field but the two-site
7769 /// duplication expressed no compile-time contract that the HTTPRoute
7770 /// name-discriminator and the per-rule backend name stay in
7771 /// lockstep on future extensions of the `:entrada` slot to a
7772 /// multi-destination author surface. Any such extension would have
7773 /// to be threaded through every renderer's inline copy of the
7774 /// destination projection in lockstep or the HTTPRoute
7775 /// `metadata.name` would silently reference a different destination
7776 /// than its own `backendRefs[]` — an operator-side
7777 /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
7778 /// grep-by-name lookup would land on a route whose `backendRefs[]`
7779 /// silently point at a peer Servico, dropping every external
7780 /// `:entrada` flow at the gateway with the destination-drift root
7781 /// cause invisible in the emitted YAML.
7782 ///
7783 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
7784 /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
7785 /// the per-listener singular / per-HTTPRoute plural filter axes and
7786 /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
7787 /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
7788 /// typed dispatch on the substrate primitive, thin projections at
7789 /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
7790 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
7791 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
7792 /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
7793 /// sibling per-`:entrada` scalar-value + list-value axes — this
7794 /// accessor closes the last unlifted per-`:entrada` scalar axis
7795 /// (the destination-Servico byte-string) so every downstream
7796 /// per-`:entrada` reader now routes through a typed dispatch on
7797 /// the substrate primitive.
7798 #[must_use]
7799 pub const fn destination(&self) -> &str {
7800 self.para.as_str()
7801 }
7802
7803 /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
7804 /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
7805 /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
7806 /// reader keys off — returns the author-declared `:entrada :port`
7807 /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
7808 /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
7809 /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
7810 /// [`AplicacaoError::EntradaPortZero`], not a silent
7811 /// admission-webhook rejection at cluster-apply time).
7812 ///
7813 /// The `:entrada :port` slot carries the destination Servico's
7814 /// canonical in-cluster L4 listener port (`trigger.service.port` on
7815 /// the `pleme-computeunit` library chart), and every downstream
7816 /// consumer that reads the port keys off this scalar (the
7817 /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
7818 /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
7819 /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
7820 /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
7821 /// CR materializer's per-Aplicacao gateway port resolver).
7822 ///
7823 /// Prior to this lift the `.port` field was accessed inline at two
7824 /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
7825 /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
7826 /// the [`AplicacaoSpec::port_for_destination`] resolver's
7827 /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
7828 /// open-coded field-accesses that expressed no compile-time link
7829 /// back to the typed slot. A future extension of the `:entrada :port`
7830 /// axis to a richer author surface — a per-cluster override the
7831 /// operator pins through a future `:placement :default-port` slot the
7832 /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
7833 /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
7834 /// heterogeneous listener ports, an M4
7835 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7836 /// admission-webhook floor that promotes the scalar to a
7837 /// per-destination map — would have had to be threaded through both
7838 /// open-coded copies in lockstep or the structural-floor validator
7839 /// and the [`AplicacaoSpec::port_for_destination`] resolver would
7840 /// silently disagree on which port a given [`Entrada`] resolves to.
7841 /// Lifting the resolution rule to a typed method on the substrate
7842 /// primitive means every downstream consumer of the Aplicacao's
7843 /// per-`:entrada` L4-port surface reaches for exactly one typed
7844 /// dispatch — the resolver's accept-set migrates as a unit on any
7845 /// future axis addition.
7846 ///
7847 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
7848 /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
7849 /// accessors on the per-`:entrada` scalar-value axis — same "one
7850 /// typed dispatch on the substrate primitive, thin projections at
7851 /// each consumer" discipline extended onto the per-`:entrada`
7852 /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
7853 /// the M3 mesh-slot `Entrada` type — closes the last unlifted
7854 /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
7855 /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
7856 /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
7857 /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
7858 /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
7859 /// storage field's name; the accessor's identity name maps onto the
7860 /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
7861 /// already carries. Declared `pub const fn` (matching the peer M3
7862 /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
7863 /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
7864 /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
7865 /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
7866 /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
7867 /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
7868 /// [`RateLimit`], and the sibling per-`:placement`
7869 /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
7870 /// enum scalar axis — every one a `pub const fn`) so every future
7871 /// substrate-side `const`-context consumer of the resolved
7872 /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
7873 /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
7874 /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
7875 /// admission-webhook `const fn` per-CR gateway-port floor over a
7876 /// typed [`Entrada`], any `const fn` composer that fans on the port
7877 /// at compile time) reaches through the same typed dispatch on the
7878 /// substrate primitive at const-eval time as at runtime. Pinned by
7879 /// [`entrada_port_accessor_is_const_fn`] which witnesses the
7880 /// const-eval posture at module scope via `const _:() = …` items so
7881 /// any future accidental downgrade to non-`const` trips at caixa-core
7882 /// build time.
7883 #[must_use]
7884 pub const fn port(&self) -> u16 {
7885 self.port
7886 }
7887
7888 /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
7889 /// slice accessor every HTTPRoute-aware renderer keys off when it
7890 /// wants the raw author-declared path-list (not the fallback-
7891 /// applied projection [`Self::resolved_paths`] returns) — returns
7892 /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
7893 /// borrowed from the typed slot's own [`Vec<String>`] storage.
7894 ///
7895 /// Named the "raw slot" half of the per-`:entrada` path-list resolver
7896 /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
7897 /// (1449891) closes the fallback-applying arm every per-Aplicacao
7898 /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
7899 /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
7900 /// catch-all; non-empty slot → per-entry verbatim projection); this
7901 /// accessor closes the raw-slot arm every consumer that must see the
7902 /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
7903 /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
7904 /// not `Err(EntradaPathEmpty)`, so it cannot route through the
7905 /// fallback-applying sibling; the `feira app graph` per-Aplicacao
7906 /// external-gateway summary line's `{:?}` Debug print — which must
7907 /// name the author's declaration, not the substrate's fallback, so
7908 /// an author reading their graph output can grep their caixa.lisp
7909 /// for the exact list they authored) routes through.
7910 ///
7911 /// Prior to this lift the `.paths` field was accessed inline at four
7912 /// production sites: the two internal reads in [`Self::resolved_paths`]
7913 /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
7914 /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
7915 /// value-shape gate's `for p in &e.paths` traversal head, and the
7916 /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
7917 /// Debug print — four open-coded field-accesses that expressed no
7918 /// compile-time link back to the typed slot. A future extension of
7919 /// the `:entrada :paths` axis to a richer author surface — a
7920 /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
7921 /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
7922 /// spec supports through `matches[].method`), a per-path per-header
7923 /// filter overlay (`matches[].headers[]`), a per-cluster override
7924 /// the operator pins through a future `:placement :path-overlay`
7925 /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7926 /// per-CR admission-webhook that normalized the list at admission
7927 /// time — would have had to be threaded through every open-coded
7928 /// copy in lockstep or the validator's per-entry gate would silently
7929 /// disagree with the renderer's per-entry emit on which list a given
7930 /// `:entrada` block resolves to. Lifting the resolution to a typed
7931 /// method on the substrate primitive means every downstream consumer
7932 /// of the Aplicacao's per-`:entrada` path-list surface reaches for
7933 /// exactly one typed dispatch — the resolver's accept-set migrates
7934 /// as a unit on any future axis addition.
7935 ///
7936 /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
7937 /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
7938 /// carry axis — same "one typed dispatch on the substrate primitive,
7939 /// thin projections at each consumer" discipline extended onto the
7940 /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
7941 /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
7942 /// carrier) so every downstream per-`:entrada` reader now routes
7943 /// through a typed dispatch on the substrate primitive. Returns
7944 /// `&[String]` (not `&Vec<String>`) because every downstream consumer
7945 /// treats the list as a read-only sequence — the slice-view is the
7946 /// narrowest borrow that supports every present + roadmapped consumer
7947 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
7948 /// `Vec`'s grow/push/reserve surface that no consumer of the typed
7949 /// view reaches for (the storage-side `Vec` remains reachable through
7950 /// the `pub paths` field for the mutation-carrying serde round-trip
7951 /// and per-test fixture-mutation paths).
7952 #[must_use]
7953 pub const fn paths(&self) -> &[String] {
7954 self.paths.as_slice()
7955 }
7956}
7957
7958/// Canonical default L4 port every typed Servico exposes on its
7959/// in-cluster K8s Service (the `trigger.service.port` axis the
7960/// `pleme-computeunit` library chart emits, the `:entrada :port` author
7961/// surface defaults to when the author omits the slot, and the
7962/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
7963/// `:entrada` block matches the per-`:contratos` destination Servico).
7964/// The single source of truth all three typed-port consumers reach for:
7965///
7966/// - [`Entrada::port`]'s serde default (via the
7967/// [`default_port`] helper this constant feeds); the author surface
7968/// `(:entrada (:host … :para …))` without an explicit `:port` slot
7969/// reads back as a typed [`Entrada`] carrying this exact value;
7970/// - the
7971/// [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
7972/// emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
7973/// fallback, fired when the typed `:entrada` block doesn't name
7974/// the per-`:contratos` destination Servico — the typed
7975/// `:contratos` graph carries no per-destination port axis (the
7976/// destination port is the destination Servico's
7977/// `lareira-<nome>` chart's `trigger.service.port`, which the
7978/// Aplicacao-level renderer has no visibility into without a
7979/// resolver round-trip), so the renderer falls back to the
7980/// substrate's canonical Servico-port assumption — by
7981/// construction the same value the destination's own
7982/// `pleme-computeunit` chart emits, the same value the
7983/// destination's own typed `:entrada :port` slot defaults to;
7984/// - every future per-Servico renderer the absorption-roadmap
7985/// acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
7986/// CR materializer's per-edge port resolver, the future
7987/// per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
7988/// emitter's per-route bucket key, the future caixa-otel
7989/// collector-pipeline emitter's per-Servico scrape port).
7990///
7991/// Until this lift landed the value `8080` lived at two production-code
7992/// call-sites: the [`default_port`] helper at
7993/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
7994/// and the `.unwrap_or(8080)` literal at
7995/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
7996/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
7997/// resolver). A future Servico-port rebrand — the substrate moving the
7998/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
7999/// gateway grows direct `:80` listeners, to `8443` once the substrate
8000/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
8001/// override the operator pins through a future
8002/// `:placement :default-port` slot — without a coordinated edit on
8003/// both sides would silently emit Servicos listening on one port and
8004/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
8005/// The CNP's apply-time symptom (the policy is admitted but every L4
8006/// flow on the destination Servico's actual port silently drops because
8007/// it doesn't match the whitelisted port) is far from the rebrand
8008/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
8009/// in hubble traces, not in `kubectl describe`. Lifting the literal to
8010/// a shared constant closes the drift footgun structurally — both
8011/// consumers read from the same `u16`, so any rebrand reaches both
8012/// sites by construction.
8013///
8014/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
8015/// per-renderer canonical-K8s-axis constant — the namespace string
8016/// and the canonical Servico port both lived as duplicated literals
8017/// across caixa-core / caixa-mesh / caixa-flux before their respective
8018/// lifts. Same "the typed constant lives in one place" discipline the
8019/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
8020/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
8021/// shared-string axes.
8022///
8023/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
8024pub const DEFAULT_SERVICO_PORT: u16 = 8080;
8025
8026/// Structural floor for the typed `:entrada :port` axis — every
8027/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
8028/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
8029///
8030/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
8031/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
8032/// interprets as "let the kernel pick a free port at bind time", not a
8033/// well-defined destination the substrate's per-`:entrada` Gateway API
8034/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
8035/// carrying `port: 0` degenerates to a nominal-only routing target: the
8036/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
8037/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
8038/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
8039/// at build time rather than at `kubectl apply` time), and the
8040/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
8041/// (caixa-mesh/src/lib.rs:2657 through
8042/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
8043/// [`Entrada::port`] typed value — silently emits a policy whose
8044/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
8045/// actual listener, dropping every L4 flow at the eBPF data plane far
8046/// from the source caixa.lisp with no field naming the port-zero-drift
8047/// root cause.
8048///
8049/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
8050/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
8051/// on the top edge (unlike the peer capped-`u32` `:politicas` /
8052/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
8053/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
8054/// well below `u32::MAX` and therefore need explicit typed caps).
8055///
8056/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
8057/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
8058/// scalar every `(:entrada (:host … :para …))` slot without an explicit
8059/// `:port` inherits through the serde default hook; this constant names
8060/// the accept-set floor every declared port must satisfy. The pair is
8061/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
8062/// substrate's default must satisfy its own accept-set floor by
8063/// construction) — a future rebrand that accidentally moved
8064/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
8065/// negative-cast typo, a per-cluster override the operator pins through
8066/// a future `:placement :default-port` slot that lands out-of-range)
8067/// would silently invalidate the serde-default emission at every
8068/// author-side `(:entrada (:host … :para …))` slot — the compile-time
8069/// invariant pin
8070/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
8071/// closes the drift footgun at caixa-core build time.
8072///
8073/// Lifted as a typed `pub const` (rather than an inline `0` literal at
8074/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
8075/// has exactly one source of truth — the future M4
8076/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
8077/// gateway resolver, the future per-Servico
8078/// `computeunit.trigger.service.port` renderer's per-CR port-value
8079/// validator, and every downstream test-fixture navigator asserting
8080/// the accept-set floor all read from one place. Same shape every
8081/// other typed bracket-floor / bracket-ceiling in this crate carries
8082/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
8083/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
8084/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
8085/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
8086/// [`POLICY_RATE_LIMIT_MAX`]).
8087pub const SERVICO_PORT_MIN: u16 = 1;
8088
8089const fn default_port() -> u16 {
8090 DEFAULT_SERVICO_PORT
8091}
8092
8093// ── the typed view ───────────────────────────────────────────────────
8094
8095/// Typed composition view of the flat Aplicacao slots on
8096/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
8097/// validation + downstream renderer consumption.
8098#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
8099#[serde(rename_all = "camelCase")]
8100pub struct AplicacaoSpec {
8101 pub membros: Vec<Membro>,
8102 pub contratos: Vec<WitContract>,
8103 pub politicas: MeshPolicy,
8104 pub placement: Placement,
8105 pub entrada: Option<Entrada>,
8106}
8107
8108impl AplicacaoSpec {
8109 /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
8110 /// per-Aplicacao member-list slice-return accessor every
8111 /// per-Aplicacao member-list reader keys off — returns the author-
8112 /// declared `:membros` list verbatim as a `&[Membro]` slice-view
8113 /// over the same backing buffer the raw `self.membros.as_slice()`
8114 /// field access borrows from.
8115 ///
8116 /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
8117 /// member list — the load-bearing identity of the application graph
8118 /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
8119 /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
8120 /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
8121 /// accessor) with a `:versao` semver-requirement string (through
8122 /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
8123 /// and every downstream consumer that fans on the member-set keys
8124 /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
8125 /// membership-lookup `HashSet<&str>` seed's collect input, the
8126 /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
8127 /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
8128 /// per-member DNS-1123 / semver-requirement / duplicate-detection
8129 /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
8130 /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
8131 /// programs.yaml per-`:membros` fan-out emitter's per-entry
8132 /// mapping-composition loop, the `feira app graph` per-Aplicacao
8133 /// member-count print line and per-member tree traversal,
8134 /// every future wasm-operator (M4) per-Aplicacao CR materializer's
8135 /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
8136 /// placement engine's per-member weight-topology reader).
8137 ///
8138 /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
8139 /// inline at six production sites — the [`AplicacaoSpec::validate`]
8140 /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
8141 /// [`AplicacaoSpec::validate_membros`]'s pre-flight
8142 /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
8143 /// probe, the same method's per-member `for m in &self.membros`
8144 /// validate-loop traversal head, the
8145 /// [`AplicacaoSpec::detect_sync_cycles`]'s
8146 /// `for m in &self.membros` adjacency-list seed, the
8147 /// [`caixa_mesh::programs_for_aplicacao`] emitter's
8148 /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
8149 /// paired with the peer `for m in &spec.membros` per-entry fan-out
8150 /// loop, and the `feira app graph` per-Aplicacao print line's
8151 /// `spec.membros.len()` count formatter argument paired with the
8152 /// peer `for m in &spec.membros` per-member tree traversal — six
8153 /// open-coded field-accesses that expressed no compile-time link
8154 /// back to the typed slot. A future extension of the `:membros`
8155 /// axis to a richer author surface (a per-cluster member-set
8156 /// overlay the operator pins through a future
8157 /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
8158 /// roadmap acknowledges, a per-tenant member-alias table the M4
8159 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
8160 /// CR at admission time, a per-Aplicacao dynamic member-set
8161 /// derivation the future adaptive-placement engine computes from
8162 /// weighted membership topology, a promotion of the plain
8163 /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
8164 /// Orleans-style virtual-actor dynamic-membership comes into typed
8165 /// scope) would have had to be threaded through all six open-coded
8166 /// copies in lockstep or one consumer would silently disagree with
8167 /// the peers on which member-set a given Aplicacao resolves to —
8168 /// the `HashSet<&str>` name-set seed reading the raw slot while
8169 /// the peer `.is_empty()` refusal probe read an operator-resolved
8170 /// slot would silently split the `:contratos` membership-lookup
8171 /// input from the pre-flight-refusal input, a six-consumer split
8172 /// at the validator + programs.yaml emitter + graph printer far
8173 /// from the source `caixa.lisp` with no field naming the member-
8174 /// set-drift root cause. Lifting the resolution rule to a typed
8175 /// method on the substrate primitive means every downstream
8176 /// consumer of the Aplicacao's per-`:membros` member-list surface
8177 /// reaches for exactly one typed dispatch — the resolver's accept-
8178 /// set migrates as a unit on any future axis addition.
8179 ///
8180 /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
8181 /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
8182 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
8183 /// static-child-list `Vec`-carry axis, and to the M3
8184 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
8185 /// on the peer per-`:placement` distribution-target-list `Vec`-
8186 /// carry axis. Same "one typed dispatch on the substrate primitive,
8187 /// thin projections at each consumer" discipline. The two peer
8188 /// `Vec`-carry axes still unlifted at the time of this lift —
8189 /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
8190 /// WIT-typed edge list) and
8191 /// [`crate::UpgradeFromEntry::instructions`]
8192 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
8193 /// — inherit this accessor's discipline as future compounding runs
8194 /// migrate their consumers onto the shared slice-return shape.
8195 /// First `&[T]`-return accessor on the top-level M3 mesh-slot
8196 /// `AplicacaoSpec` type itself, extending the discipline beyond
8197 /// the inner per-slot types ([`crate::Placement`],
8198 /// [`crate::SupervisorSpec`]) onto the outermost typed composition
8199 /// view every renderer consumes. Named `membros()` to match the
8200 /// storage field's name verbatim and the tatara-lisp author-
8201 /// surface term (`:membros`) the field's own docstring already
8202 /// carries; the accessor's identity maps onto the canonical
8203 /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
8204 /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
8205 /// every downstream consumer of the member list treats it as a
8206 /// read-only sequence — the slice-view is the narrowest borrow
8207 /// that supports every present + roadmapped consumer
8208 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
8209 /// backing `Vec`'s grow/push/reserve surface that no consumer of
8210 /// the typed view reaches for (the storage-side `Vec` remains
8211 /// reachable through the `pub membros` field for the mutation-
8212 /// carrying serde round-trip and per-test fixture-mutation paths).
8213 #[must_use]
8214 pub const fn membros(&self) -> &[Membro] {
8215 self.membros.as_slice()
8216 }
8217
8218 /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
8219 /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
8220 /// accessor every per-Aplicacao contract-list reader keys off —
8221 /// returns the author-declared `:contratos` list verbatim as a
8222 /// `&[WitContract]` slice-view over the same backing buffer the raw
8223 /// `self.contratos.as_slice()` field access borrows from.
8224 ///
8225 /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
8226 /// WIT-typed edge list — the load-bearing set of directed edges
8227 /// on the application graph whose nodes are the `:membros` entries
8228 /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
8229 /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
8230 /// six-tuple is the edge identity every downstream duplicate gate
8231 /// keys off). Every per-`:contratos` entry pairs a `:de` source-
8232 /// Servico caller name + a `:para` destination-Servico callee name
8233 /// (through the lifted [`WitContract::source`] +
8234 /// [`WitContract::destination`] (7f0fd43) accessor pair on the
8235 /// caller/callee-Servico axis) with a `:wit` world-reference
8236 /// (through the lifted [`WitContract::world_ref`] (0804823)
8237 /// accessor) and the target-shape-appropriate payload-carrier
8238 /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
8239 /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
8240 /// (ed22b66) accessor on the per-target-shape payload-carrier
8241 /// axis). Every downstream consumer that fans on the edge-set
8242 /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
8243 /// name-set / self-edge / target-shape / dedup fan-out loop, the
8244 /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
8245 /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
8246 /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
8247 /// grouping loop, the `feira app graph` per-Aplicacao contract-
8248 /// count print line and per-contract tree traversal, every future
8249 /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
8250 /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
8251 /// mesh-policy overlay resolver's per-contract typed-edge weight
8252 /// reader).
8253 ///
8254 /// Prior to this lift the `.contratos` `Vec<WitContract>` was
8255 /// accessed inline at four production sites — the
8256 /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
8257 /// per-edge validate-loop traversal head (which drives every
8258 /// per-edge name-set membership lookup, self-edge check,
8259 /// target-shape dispatch, and dedup `HashSet` insert), the
8260 /// [`AplicacaoSpec::detect_sync_cycles`]'s
8261 /// `for c in &self.contratos` adjacency-list seed head (which
8262 /// drives every per-edge sync-vs-pub-sub partition and per-edge
8263 /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
8264 /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
8265 /// `BTreeMap` grouping loop head (which drives every per-CNP
8266 /// fan-out emit), and the `feira app graph` per-Aplicacao print
8267 /// line's `spec.contratos.len()` count formatter argument paired
8268 /// with the peer `for c in &spec.contratos` per-contract tree
8269 /// traversal — four open-coded field-accesses that expressed no
8270 /// compile-time link back to the typed slot. A future extension
8271 /// of the `:contratos` axis to a richer author surface (a
8272 /// per-cluster contract overlay the operator pins through a
8273 /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
8274 /// federation roadmap acknowledges, a per-tenant edge-policy
8275 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
8276 /// materializer resolves per-CR at admission time, a per-edge
8277 /// weight scalar the future adaptive-placement engine reads to
8278 /// bias sync-subgraph routing, a promotion of the plain
8279 /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
8280 /// once virtual-actor-style dynamic-edge composition comes into
8281 /// typed scope) would have had to be threaded through all four
8282 /// open-coded copies in lockstep or one consumer would silently
8283 /// disagree with the peers on which edge-set a given Aplicacao
8284 /// resolves to — the validator's per-edge dedup `HashSet` seed
8285 /// reading the raw slot while the peer sync-cycle adjacency-list
8286 /// seed read an operator-resolved slot would silently split the
8287 /// build-time edge-set gate from the runtime deadlock-detection
8288 /// gate, a four-consumer split at the validator, the cycle
8289 /// detector, the CNP emitter, and the graph printer far from
8290 /// the source `caixa.lisp` with no field naming the edge-set-
8291 /// drift root cause. Lifting the resolution rule to a typed method on the
8292 /// substrate primitive means every downstream consumer of the
8293 /// Aplicacao's per-`:contratos` edge-list surface reaches for
8294 /// exactly one typed dispatch — the resolver's accept-set
8295 /// migrates as a unit on any future axis addition.
8296 ///
8297 /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
8298 /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
8299 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
8300 /// static-child-list `Vec`-carry axis, to the M3
8301 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
8302 /// on the peer per-`:placement` distribution-target-list `Vec`-
8303 /// carry axis, and to the immediately-adjacent sibling M3
8304 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
8305 /// the peer per-`:membros` node-list `Vec`-carry axis — the
8306 /// per-`:contratos` edge-list accessor is the natural pair of
8307 /// the per-`:membros` node-list accessor (graph edges over graph
8308 /// nodes; every graph-shaped consumer reads both). Same "one
8309 /// typed dispatch on the substrate primitive, thin projections
8310 /// at each consumer" discipline. The last remaining `Vec`-carry
8311 /// axis still unlifted at the time of this lift —
8312 /// [`crate::UpgradeFromEntry::instructions`]
8313 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
8314 /// list) — inherits this accessor's discipline as future
8315 /// compounding runs migrate its consumers onto the shared slice-
8316 /// return shape. Second `&[T]`-return accessor on the top-level
8317 /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
8318 /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
8319 /// `:contratos` are the two `Vec` fields on the outer typed
8320 /// composition view — `:politicas`, `:placement`, `:entrada` are
8321 /// scalar/option-shaped and already route through their per-slot
8322 /// accessor families). Named `contratos()` to match the storage
8323 /// field's name verbatim and the tatara-lisp author-surface term
8324 /// (`:contratos`) the field's own docstring already carries; the
8325 /// accessor's identity maps onto the canonical MESH-COMPOSITION
8326 /// §III.1 vocabulary the slot's docstring already reaches for.
8327 /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
8328 /// every downstream consumer of the contract list treats it as a
8329 /// read-only sequence — the slice-view is the narrowest borrow
8330 /// that supports every present + roadmapped consumer
8331 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
8332 /// backing `Vec`'s grow/push/reserve surface that no consumer of
8333 /// the typed view reaches for (the storage-side `Vec` remains
8334 /// reachable through the `pub contratos` field for the mutation-
8335 /// carrying serde round-trip and per-test fixture-mutation paths).
8336 #[must_use]
8337 pub const fn contratos(&self) -> &[WitContract] {
8338 self.contratos.as_slice()
8339 }
8340
8341 /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
8342 /// per-Aplicacao mesh-policy composite-reference accessor every
8343 /// per-Aplicacao policy-block reader keys off — returns the author-
8344 /// declared `:politicas` composite verbatim as a `&MeshPolicy`
8345 /// reference over the same backing storage the raw `&self.politicas`
8346 /// field access borrows from.
8347 ///
8348 /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
8349 /// mesh-policy composite — the load-bearing container of every
8350 /// mesh-level operational-policy axis every downstream mesh-artifact
8351 /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
8352 /// mesh-policy overlay is the single typed surface a
8353 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
8354 /// from). Every per-`:politicas` axis threads through a lifted
8355 /// per-slot accessor on the [`MeshPolicy`] type: the
8356 /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
8357 /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
8358 /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
8359 /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
8360 /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
8361 /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
8362 /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
8363 /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
8364 /// accessor. Every downstream consumer that reaches for a policy
8365 /// axis first passes through this outer accessor onto the composite
8366 /// and then dispatches onto the per-axis accessor — the two-level
8367 /// dispatch means every per-`:politicas` reader now routes through
8368 /// a typed dispatch on the substrate primitive at both altitudes.
8369 ///
8370 /// Prior to this lift the `.politicas` `MeshPolicy` composite was
8371 /// accessed inline at four production sites — the
8372 /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
8373 /// &self.politicas;` traversal seed (which drives every per-axis
8374 /// zero-floor + upper-cap + canonical-form bracket dispatch through
8375 /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
8376 /// `p.rate_limit()` on the axis-level lifted accessors), the
8377 /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
8378 /// emitter's `spec.politicas.mtls_required()` field-then-accessor
8379 /// chain (which drives every per-`(:de, :para)` CNP
8380 /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
8381 /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
8382 /// timeout + retry overlay emitter's paired
8383 /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
8384 /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
8385 /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
8386 /// open-coded outer-field accesses that expressed no compile-time
8387 /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
8388 /// future extension of the `:politicas` outer axis to a richer
8389 /// author surface (a per-cluster policy overlay the operator pins
8390 /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
8391 /// §V federation roadmap acknowledges, a per-tenant policy-alias
8392 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
8393 /// resolves per-CR at admission time, a per-Aplicacao dynamic
8394 /// policy-composite derivation the future adaptive-placement engine
8395 /// computes from a per-cluster load-topology reader, a promotion of
8396 /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
8397 /// partition once virtual-actor-style dynamic-mesh-policy
8398 /// composition comes into typed scope) would have had to be threaded
8399 /// through all four open-coded copies in lockstep or one consumer
8400 /// would silently disagree with the peers on which mesh-policy
8401 /// composite a given Aplicacao resolves to — the validator's
8402 /// per-axis bracket-dispatch seed reading the raw slot while the
8403 /// peer CNP mTLS-overlay emitter read an operator-resolved slot
8404 /// would silently split the build-time policy-shape gate from the
8405 /// runtime CNP-emission gate, a four-consumer split at the
8406 /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
8407 /// the source `caixa.lisp` with no field naming the policy-drift
8408 /// root cause. Lifting the resolution rule to a typed method on the
8409 /// substrate primitive means every downstream consumer of the
8410 /// Aplicacao's per-`:politicas` mesh-policy composite surface
8411 /// reaches for exactly one typed dispatch — the resolver's accept-
8412 /// set migrates as a unit on any future axis addition.
8413 ///
8414 /// First `&Composite`-return accessor on the top-level M3 mesh-slot
8415 /// `AplicacaoSpec` type itself — sibling to the seed slice-return
8416 /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
8417 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
8418 /// close the two `Vec`-carry axes on the outer typed composition
8419 /// view; the outer `:politicas` composite-reference axis is the
8420 /// natural pair to the paired outer `Vec`-carry accessors on the
8421 /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
8422 /// emitter reads all four axes as one unit (graph nodes + graph
8423 /// edges + mesh policy + placement pool). Peer to the same
8424 /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
8425 /// slot: every M2 `SupervisorSpec`-scoped composite reader
8426 /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
8427 /// `restart_window`, `children`) already routes through the M2
8428 /// `SupervisorSpec` accessor family — this lift extends the same
8429 /// "one typed dispatch on the substrate primitive at the outer
8430 /// composition altitude" discipline to the M3 mesh-slot
8431 /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
8432 /// remaining peer outer-composite axes still unlifted at the time
8433 /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
8434 /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
8435 /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
8436 /// inherit this accessor's discipline as future compounding runs
8437 /// migrate their consumers onto the shared reference-return shape.
8438 /// Named `politicas()` to match the storage field's name verbatim
8439 /// and the tatara-lisp author-surface term (`:politicas`) the
8440 /// field's own docstring already carries; the accessor's identity
8441 /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
8442 /// slot's docstring already reaches for. Returns `&MeshPolicy`
8443 /// (not the owning composite by copy or clone) because every
8444 /// downstream consumer of the mesh-policy composite treats it as a
8445 /// read-only per-axis dispatch source — the reference-view is the
8446 /// narrowest borrow that supports every present + roadmapped
8447 /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
8448 /// emptiness probe) without cloning the composite through every
8449 /// consumer's fast path.
8450 #[must_use]
8451 pub const fn politicas(&self) -> &MeshPolicy {
8452 &self.politicas
8453 }
8454
8455 /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
8456 /// per-Aplicacao distribution-composite composite-reference accessor
8457 /// every per-Aplicacao placement-block reader keys off — returns the
8458 /// author-declared `:placement` composite verbatim as a `&Placement`
8459 /// reference over the same backing storage the raw `&self.placement`
8460 /// field access borrows from.
8461 ///
8462 /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
8463 /// distribution composite — the load-bearing container of every
8464 /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
8465 /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
8466 /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
8467 /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
8468 /// hosting-pool identity, §V for the `M3-Adaptive`-compression
8469 /// `:affinity` hint). Every per-`:placement` axis threads through a
8470 /// lifted per-slot accessor on the [`Placement`] type: the
8471 /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
8472 /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
8473 /// per-cluster distribution-target slice-return accessor, the
8474 /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
8475 /// optional-scalar accessor, and the [`Placement::shard_key`]
8476 /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
8477 /// downstream consumer that reaches for a placement axis first passes
8478 /// through this outer accessor onto the composite and then dispatches
8479 /// onto the per-axis accessor — the two-level dispatch means every
8480 /// per-`:placement` reader now routes through a typed dispatch on the
8481 /// substrate primitive at both altitudes.
8482 ///
8483 /// Prior to this lift the `.placement` `Placement` composite was
8484 /// accessed inline at three production sites — the
8485 /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
8486 /// seed (six `self.placement.<axis>()` field-then-inner-accessor
8487 /// chains: the pre-flight `.clusters().is_empty()` refusal probe
8488 /// paired with the `.estrategia()` diagnostic-carry copy, the per-
8489 /// cluster `.clusters()` validate-loop traversal head, the per-
8490 /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
8491 /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
8492 /// paired with the shape-gate cascade's `.shard_key()` /
8493 /// `.estrategia()` diagnostic-carry pair), the
8494 /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
8495 /// per-entry placement-block emitter's outer
8496 /// `serde_yaml::to_value(&spec.placement)` composite-serialization
8497 /// seed (which fans onto every per-cluster `programs[]` entry as a
8498 /// self-describing distribution overlay the aggregator filters by),
8499 /// and the `feira app graph` per-Aplicacao print line's paired
8500 /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
8501 /// then-inner-accessor chains (which drive the human-readable
8502 /// distribution summary of the typed Aplicacao view) — three open-
8503 /// coded outer-field accesses that expressed no compile-time link
8504 /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
8505 /// extension of the `:placement` outer axis to a richer author surface
8506 /// (a per-cluster placement overlay the operator pins through a
8507 /// future `:placement-overrides` slot the MESH-COMPOSITION §V
8508 /// federation roadmap acknowledges, a per-tenant placement-alias
8509 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
8510 /// resolves per-CR at admission time, a per-Aplicacao dynamic
8511 /// placement-composite derivation the future M5 adaptive-placement
8512 /// engine computes from a per-cluster load-topology reader, a
8513 /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
8514 /// partition once Orleans-style virtual-actor dynamic-placement comes
8515 /// into typed scope) would have had to be threaded through all three
8516 /// open-coded copies in lockstep or one consumer would silently
8517 /// disagree with the peers on which placement composite a given
8518 /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
8519 /// seed reading the raw slot while the peer
8520 /// `programs_for_aplicacao` emitter read an operator-resolved slot
8521 /// would silently split the build-time distribution-shape gate from
8522 /// the runtime programs.yaml distribution-annotation gate, a three-
8523 /// consumer split at the validator, the programs.yaml emitter, and
8524 /// the `feira app graph` printer far from the source `caixa.lisp`
8525 /// with no field naming the placement-drift root cause. Lifting the
8526 /// resolution rule to a typed method on the substrate primitive
8527 /// means every downstream consumer of the Aplicacao's per-
8528 /// `:placement` distribution composite surface reaches for exactly
8529 /// one typed dispatch — the resolver's accept-set migrates as a unit
8530 /// on any future axis addition.
8531 ///
8532 /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
8533 /// `AplicacaoSpec` type itself — sibling to the seed
8534 /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
8535 /// composite-reference accessor on the peer per-`:politicas` outer-
8536 /// composite axis, and to the paired slice-return accessors
8537 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
8538 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
8539 /// the two `Vec`-carry axes on the outer typed composition view; the
8540 /// outer `:placement` composite-reference axis is the natural pair
8541 /// to the peer `:politicas` composite-reference axis on the two
8542 /// operationally-symmetric M3 mesh slots (`:politicas` carries the
8543 /// how-to-run policy overlay, `:placement` carries the where-to-run
8544 /// distribution composite — every whole-Aplicacao mesh-artifact
8545 /// emitter reads both as one unit). Same "one typed dispatch on the
8546 /// substrate primitive, thin projections at each consumer"
8547 /// discipline the peer per-`:politicas` composite-reference axis
8548 /// already routes through. The one remaining outer-composite axis
8549 /// still unlifted at the time of this lift —
8550 /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
8551 /// external-gateway composite) — inherits this accessor's discipline
8552 /// as the next compounding run migrates its consumers onto the shared
8553 /// reference-return shape, closing the outer-composite altitude on
8554 /// every M3 mesh-slot axis. Named `placement()` to match the storage
8555 /// field's name verbatim and the tatara-lisp author-surface term
8556 /// (`:placement`) the field's own docstring already carries; the
8557 /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
8558 /// vocabulary the slot's docstring already reaches for. Returns
8559 /// `&Placement` (not the owning composite by copy or clone) because
8560 /// every downstream consumer of the placement composite treats it as
8561 /// a read-only per-axis dispatch source — the reference-view is the
8562 /// narrowest borrow that supports every present + roadmapped consumer
8563 /// (per-axis accessor dispatch, serde composite-serialization) without
8564 /// cloning the composite through every consumer's fast path.
8565 #[must_use]
8566 pub const fn placement(&self) -> &Placement {
8567 &self.placement
8568 }
8569
8570 /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
8571 /// per-Aplicacao external-gateway composite optional-composite-
8572 /// reference accessor every per-Aplicacao gateway-block reader
8573 /// keys off — returns the author-declared `:entrada` composite
8574 /// verbatim as an `Option<&Entrada>` reference over the same
8575 /// backing storage the raw `self.entrada.as_ref()` field access
8576 /// borrows from, with `None` naming the internal-only mesh shape
8577 /// (the author-omitted `:entrada` slot the K8s Gateway API v1
8578 /// gateway_routes emitter treats as "emit nothing" and the peer
8579 /// `feira app graph` printer treats as "internal-only mesh").
8580 ///
8581 /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
8582 /// external-gateway composite — the load-bearing container of
8583 /// every does-this-Aplicacao-expose-a-public-endpoint axis every
8584 /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
8585 /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
8586 /// hostname axis, §III.4 for the `:para` destination-Servico
8587 /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
8588 /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
8589 /// axis threads through a lifted per-slot accessor on the
8590 /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
8591 /// Gateway-API `Listener.hostname` scalar accessor, the paired
8592 /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
8593 /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
8594 /// backendRefs destination-Servico scalar accessor, the
8595 /// [`Entrada::resolved_paths`] path-fallback resolver, and the
8596 /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
8597 /// scalar accessor. Every downstream consumer that reaches for
8598 /// an entrada axis first passes through this outer accessor onto
8599 /// the composite and then dispatches onto the per-axis accessor
8600 /// — the two-level dispatch means every per-`:entrada` reader
8601 /// now routes through a typed dispatch on the substrate primitive
8602 /// at both altitudes.
8603 ///
8604 /// Prior to this lift the `.entrada` `Option<Entrada>` composite
8605 /// was accessed inline at four production sites — the
8606 /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
8607 /// gate's `if let Some(e) = &self.entrada { … }` traversal head
8608 /// (which drives every per-axis refusal on the composite: the
8609 /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
8610 /// `EntradaMemberMissing` membership lookup against the
8611 /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
8612 /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
8613 /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
8614 /// per-path shape gate on each entry of `e.paths`), the
8615 /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
8616 /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
8617 /// composite-projection seed (which drives the destination-
8618 /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
8619 /// backendRefs port emitter fans on), the
8620 /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
8621 /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
8622 /// early-return seed (which drives the "no `:entrada` ⇒ no
8623 /// external artifacts" partition on the whole-Aplicacao Gateway-
8624 /// API emitter's fan-out), and the `feira app graph` per-
8625 /// Aplicacao print line's `if let Some(e) = &spec.entrada`
8626 /// external-gateway summary emitter (which drives the human-
8627 /// readable `entrada: host → para (paths=…, port=…)` /
8628 /// `entrada: (internal-only mesh)` partition on the typed
8629 /// Aplicacao view) — four open-coded outer-field accesses that
8630 /// expressed no compile-time link back to the typed slot at the
8631 /// [`AplicacaoSpec`] altitude. A future extension of the
8632 /// `:entrada` outer axis to a richer author surface (a
8633 /// multi-`:entrada` list the M4 CR materializer resolves per-CR
8634 /// at admission time so an Aplicacao can expose a public-web +
8635 /// admin-web pair, a per-cluster `:entrada-overrides` slot the
8636 /// MESH-COMPOSITION §V federation roadmap acknowledges so an
8637 /// operator can pin a per-cluster hostname override without
8638 /// re-authoring the `caixa.lisp`, a promotion of the plain
8639 /// `Option<Entrada>` to a richer `{single, multi}` partition once
8640 /// the multi-`:entrada` roadmap lands) would have had to be
8641 /// threaded through all four open-coded copies in lockstep or one
8642 /// consumer would silently disagree with the peers on which
8643 /// entrada composite a given Aplicacao resolves to — the
8644 /// validator's per-axis bracket-dispatch seed reading the raw
8645 /// slot while the peer `gateway_routes` emitter read an
8646 /// operator-resolved slot would silently split the build-time
8647 /// gateway-shape gate from the runtime Gateway + HTTPRoute
8648 /// emission gate, a four-consumer split at the validator, the
8649 /// `port_for_destination` L4-port resolver, the `gateway_routes`
8650 /// emitter, and the `feira app graph` printer far from the
8651 /// source `caixa.lisp` with no field naming the entrada-drift
8652 /// root cause. Lifting the resolution rule to a typed method on
8653 /// the substrate primitive means every downstream consumer of
8654 /// the Aplicacao's per-`:entrada` external-gateway composite
8655 /// surface reaches for exactly one typed dispatch — the
8656 /// resolver's accept-set migrates as a unit on any future axis
8657 /// addition.
8658 ///
8659 /// Third and final `&Composite`-return accessor on the top-level
8660 /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
8661 /// unlifted outer-composite axis on the outer typed composition
8662 /// view, sibling to the seed [`AplicacaoSpec::politicas`]
8663 /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
8664 /// accessor on the per-`:politicas` outer-composite axis and to
8665 /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
8666 /// distribution-composite composite-reference accessor on the
8667 /// per-`:placement` outer-composite axis; extends the outer-
8668 /// composite reference-return discipline the two peers already
8669 /// route through onto the last unlifted per-`AplicacaoSpec`
8670 /// outer-composite axis. The `:entrada` outer-composite axis is
8671 /// the natural pair to the two peer outer-composite axes on the
8672 /// three operationally-symmetric M3 mesh-slot outer composites
8673 /// (`:politicas` carries the how-to-run policy overlay,
8674 /// `:placement` carries the where-to-run distribution composite,
8675 /// `:entrada` carries the who-can-reach-it external-gateway
8676 /// composite — every whole-Aplicacao mesh-artifact emitter reads
8677 /// all three as one unit). Same "one typed dispatch on the
8678 /// substrate primitive, thin projections at each consumer"
8679 /// discipline the peer outer-composite axes already route through.
8680 /// Named `entrada()` to match the storage field's name verbatim
8681 /// and the tatara-lisp author-surface term (`:entrada`) the
8682 /// field's own docstring already carries; the accessor's
8683 /// identity maps onto the canonical MESH-COMPOSITION §III.4
8684 /// vocabulary the slot's docstring already reaches for. Returns
8685 /// `Option<&Entrada>` (not the owning composite by copy or
8686 /// clone) because every downstream consumer of the entrada
8687 /// composite treats it as a read-only per-axis dispatch source
8688 /// — the reference-view is the narrowest borrow that supports
8689 /// every present + roadmapped consumer (per-axis accessor
8690 /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
8691 /// port-fallback projection, early-return partition on the
8692 /// `None` arm) without cloning the composite through every
8693 /// consumer's fast path. The `Option` half of the return-type
8694 /// preserves the load-bearing "author-omitted `:entrada` ⇒
8695 /// internal-only mesh" partition (not a default composite the
8696 /// downstream must reject on emptiness) — the accessor projects
8697 /// the raw `Option<Entrada>` slot's presence bit through the
8698 /// reference-return unchanged.
8699 #[must_use]
8700 pub const fn entrada(&self) -> Option<&Entrada> {
8701 self.entrada.as_ref()
8702 }
8703
8704 /// Validate the typed shape:
8705 /// - `:membros` is non-empty; every entry has a non-empty `:caixa`
8706 /// and a non-empty `:versao`; no two entries share the same
8707 /// `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
8708 /// not a multiset)
8709 /// - every `:contratos` :de + :para must be in `:membros`
8710 /// - no `:contratos` edge is a self-edge (`:de == :para`) — a
8711 /// contract is an inter-Servico edge, so a Servico contracting
8712 /// with itself is a build error under every WIT shape
8713 /// (MESH-COMPOSITION §III.1)
8714 /// - no two `:contratos` entries agree on
8715 /// `(de, para, wit, endpoint, subject, slot)` — the typed-graph
8716 /// edges are a set, not a multiset (peer of the `:membros` /
8717 /// `:placement :clusters` / `:entrada :paths` duplicate gates)
8718 /// - `:entrada :para` must be in `:membros`
8719 /// - `:placement Sharded` must declare `:shard-key` (non-empty);
8720 /// `:placement Replicated`/`SingleNode` must NOT declare
8721 /// `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
8722 /// consumes it (MESH-COMPOSITION §II.4), and the typed partition
8723 /// between strategy and shard-key is symmetric: every validated
8724 /// `Placement` has `shard_key.is_some()` iff `estrategia ==
8725 /// Sharded`
8726 /// - every `:placement` strategy must declare ≥1 `:clusters` entry —
8727 /// `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
8728 /// the shard pool (MESH-COMPOSITION §III.1)
8729 /// - every `:clusters` entry is non-empty and unique
8730 /// - `:placement :affinity`, when set, is non-empty
8731 /// - the synchronous-`:contratos` subgraph is acyclic
8732 /// (MESH-COMPOSITION §III.3)
8733 /// - every declared `:politicas` value is operationally meaningful
8734 /// (zero timeout, zero retries, zero breaker thresholds, zero rate
8735 /// limit are all build errors — MESH-COMPOSITION §V CSE invariants;
8736 /// omit the field instead to express "no policy on this axis")
8737 pub fn validate(&self) -> Result<(), AplicacaoError> {
8738 self.validate_membros()?;
8739
8740 // `:contratos` per-slot gate — folds both structural axes on the
8741 // slot into one substrate primitive: the per-entry cascade (shape
8742 // + membership + self-loop + `:wit` emptiness + WIT-shape ↔
8743 // target + whole-edge dedup) and the cross-edge sync-cycle axis
8744 // ([`AplicacaoSpec::detect_sync_cycles`], MESH-COMPOSITION §III.3
8745 // — pub-sub edges excluded, "acyclic by construction"). Same
8746 // fold-per-axis-plus-cross-axis discipline the sibling
8747 // [`AplicacaoSpec::validate_politicas`] per-slot gate carries via
8748 // [`MeshPolicy::validate`] (f03a154 / 90a6f87), extended here
8749 // onto `:contratos` so every future consumer of the slot (the M4
8750 // admission webhook re-checking `:contratos` after a per-edge
8751 // patch, the per-edge policy resolver MESH-COMPOSITION §III.2 #3
8752 // acknowledges) reaches *both* structural axes through one call.
8753 self.validate_contratos()?;
8754
8755 self.validate_entrada()?;
8756
8757 self.validate_placement()?;
8758
8759 self.validate_politicas()?;
8760
8761 Ok(())
8762 }
8763
8764 /// The `:membros` graph-node name set — the membership oracle every
8765 /// per-Aplicacao name-reference axis resolves against.
8766 ///
8767 /// Three per-Aplicacao axes carry a Servico-name *reference* rather
8768 /// than a Servico-name *declaration*: `:contratos :de`, `:contratos
8769 /// :para`, and `:entrada :para`. Each must resolve to a declared
8770 /// `:membros :caixa` (MESH-COMPOSITION §III.1 — the typed edges and
8771 /// the external gateway both address graph nodes, so a reference to
8772 /// a node the graph does not contain is a build error). All three
8773 /// resolve against *this* set, so the set's construction is the one
8774 /// shared substrate primitive underneath the whole reference-
8775 /// resolution surface.
8776 ///
8777 /// Lifted out of [`AplicacaoSpec::validate`]'s inline
8778 /// `self.membros().iter().map(Membro::nome).collect()` builder so
8779 /// the two per-slot gates that consume it — the per-`:contratos`
8780 /// membership arms still inline at `validate` and the lifted
8781 /// [`AplicacaoSpec::validate_entrada`] below — reach the same
8782 /// oracle through one dispatch rather than each open-coding the
8783 /// projection. Every future consumer on the same axis (the M4
8784 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
8785 /// reference resolver, the per-`:contratos`-edge `:politicas`
8786 /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
8787 /// resolves an edge's endpoints against the same membership set
8788 /// before it can key a per-edge policy off them) inherits the
8789 /// projection through the same call, so a future rebrand of the
8790 /// node-identity axis (a namespace-qualified member name the CR
8791 /// materializer applies per-CR, the `:membros :nome-suffix`
8792 /// overlay §III.2 acknowledges) lands at exactly one place rather
8793 /// than at every reference-resolution site in lockstep. Peer of
8794 /// the sibling per-slot substrate primitives
8795 /// [`MeshPolicy::validate`] (f03a154) and
8796 /// [`WitContract::identity`] on their own axes.
8797 fn membro_names(&self) -> std::collections::HashSet<&str> {
8798 self.membros().iter().map(Membro::nome).collect()
8799 }
8800
8801 /// Reject `:contratos` entries whose endpoints are malformed,
8802 /// reference a Servico outside the graph, self-loop, carry an
8803 /// empty `:wit` shape, duplicate a prior entry on the six-axis
8804 /// identity key, or close a synchronous-edge cycle in the
8805 /// resulting typed graph.
8806 ///
8807 /// The `:contratos` slot is the typed inter-Servico edge set
8808 /// (MESH-COMPOSITION §III.1): each entry is a WIT-typed directed
8809 /// edge whose `:de` / `:para` reference two distinct members and
8810 /// whose `:wit` picks the payload shape the paired L4/L7 renderer
8811 /// (caixa-mesh's per-`(:de, :para)` `CiliumNetworkPolicy` +
8812 /// per-HTTP `HTTPRoute`) fans out on.
8813 ///
8814 /// Two structural axes on the slot are folded into this per-slot
8815 /// gate: the per-entry axis (six per-edge arms, listed below) and
8816 /// the cross-edge synchronous-cycle axis (MESH-COMPOSITION §III.3,
8817 /// dispatched to [`AplicacaoSpec::detect_sync_cycles`] after the
8818 /// per-entry cascade). Same
8819 /// per-axis-plus-cross-axis-fold-into-one-per-slot-gate discipline
8820 /// the sibling [`AplicacaoSpec::validate_politicas`] per-slot gate
8821 /// carries via [`MeshPolicy::validate`] (f03a154 / 90a6f87) on the
8822 /// `:politicas` slot, extended here onto `:contratos`.
8823 ///
8824 /// Six per-entry axes are gated first, in the canonical
8825 /// edge-direction order the paired diagnostics already encode
8826 /// (per-arm value shape before graph-membership lookup; structural
8827 /// self-edge before payload-shape target dispatch; whole-edge dedup
8828 /// last):
8829 ///
8830 /// - per-arm `:de` / `:para` value shape via
8831 /// [`validate_contrato_caixa`] (empty + DNS-1123 grammar),
8832 /// `:de` before `:para`;
8833 /// - per-edge graph-membership against the
8834 /// [`AplicacaoSpec::membro_names`] oracle via
8835 /// [`WitContract::require_endpoints_in`] (folds the twin
8836 /// `:de` / `:para` arms onto one substrate-primitive
8837 /// dispatch), `:de` before `:para`;
8838 /// - structural self-edge via [`WitContract::is_self_loop`]
8839 /// (caller-equals-callee under any WIT shape);
8840 /// - `:wit` emptiness ([`AplicacaoError::EmptyWit`]);
8841 /// - WIT shape ↔ target consistency via [`WitContract::target`]
8842 /// (the four `WitTarget` arms — `Http` / `PubSub` / `Store` /
8843 /// `Capability` — each carry their own required payload field);
8844 /// - six-axis whole-edge dedup via [`WitContract::identity`]
8845 /// ([`ContratoIdentity`]'s `(de, para, wit, endpoint, subject,
8846 /// slot)` tuple).
8847 ///
8848 /// One cross-edge axis is gated last, after the per-entry cascade
8849 /// completes cleanly:
8850 ///
8851 /// - synchronous-edge cycle detection via
8852 /// [`AplicacaoSpec::detect_sync_cycles`] (iterative DFS with
8853 /// three-coloring over the sync-only subgraph, pub-sub edges
8854 /// skipped per MESH-COMPOSITION §III.3 —
8855 /// [`AplicacaoError::ContratoCycle`]). Runs *after* the
8856 /// per-entry cascade so a per-entry defect surfaces through its
8857 /// narrower shape/membership/dedup arm before the cross-edge
8858 /// cycle diagnostic, matching the pre-fold `validate`-side
8859 /// dispatch ordering (`validate_contratos()? →
8860 /// detect_sync_cycles()?`).
8861 ///
8862 /// Lifted out of [`AplicacaoSpec::validate`]'s inline `let mut
8863 /// seen_contracts = …; for c in self.contratos() { … }` block onto
8864 /// a named per-slot gate, closing the last unlifted per-slot gate
8865 /// on the M3 mesh-slot family. Every peer slot already carries the
8866 /// shape ([`AplicacaoSpec::validate_membros`],
8867 /// [`AplicacaoSpec::validate_entrada`],
8868 /// [`AplicacaoSpec::validate_placement`],
8869 /// [`AplicacaoSpec::validate_politicas`]).
8870 ///
8871 /// Self-contained on `&self` — it resolves its own membership
8872 /// oracle through [`AplicacaoSpec::membro_names`] rather than
8873 /// borrowing one threaded down from `validate`, and runs its own
8874 /// cross-edge cycle probe rather than deferring the axis to an
8875 /// outer dispatch — so a future consumer that re-validates *one*
8876 /// slot against a mutated spec (the M4 admission webhook
8877 /// re-checking `:contratos` after a per-`(:de, :para)` edge patch
8878 /// without re-walking `:membros` / `:entrada` / `:placement` /
8879 /// `:politicas`, or the M4 per-edge policy resolver
8880 /// MESH-COMPOSITION §III.2 #3 acknowledges — which resolves an
8881 /// effective per-edge [`MeshPolicy`] and must re-check the edge's
8882 /// own identity closure *and* the sync-cycle invariant before it
8883 /// can key a per-edge override off the endpoint tuple) reaches
8884 /// *both* structural axes on the slot through one call, exactly as
8885 /// [`AplicacaoSpec::validate_politicas`] reaches both per-axis and
8886 /// cross-axis surfaces on `:politicas` through
8887 /// [`MeshPolicy::validate`].
8888 fn validate_contratos(&self) -> Result<(), AplicacaoError> {
8889 let names = self.membro_names();
8890
8891 // Identity key for the typed-edge duplicate gate below: every
8892 // field that distinguishes one contract from another. Two
8893 // entries that agree on all six are *the same edge declared
8894 // twice*, the typed-graph analogue of duplicate `:membros` /
8895 // `:placement :clusters` / `:entrada :paths` entries (which
8896 // are already build errors at this layer). Rejecting it at the
8897 // validate gate closes a renderer-side footgun: caixa-mesh's
8898 // `cilium_network_policies` keys each emitted policy by
8899 // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
8900 // (de, para) and identical payload would land as two K8s
8901 // objects with colliding `metadata.name`, rejected at apply
8902 // time far from the source caixa.lisp.
8903 let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
8904 std::collections::HashSet::new();
8905 for c in self.contratos() {
8906 // Per-axis value-shape gate on every `:contratos` name
8907 // reference, before any graph-membership lookup. Empty +
8908 // DNS-1123-malformed `:de`/`:para` values silently fell
8909 // through to `ContratoMemberMissing` at the lookup arm
8910 // because every `:membros :caixa` is shape-validated
8911 // (3f9d7a0), so the `names` set structurally cannot contain
8912 // an empty / malformed string and the membership-lookup
8913 // diagnostic always misframed the root cause as
8914 // "this caixa is not in `:membros`". The shape gate runs
8915 // ahead of the lookup so structurally-impossible-to-match
8916 // inputs route through the narrower self-locating
8917 // diagnostic, preserving the legitimate "well-shaped
8918 // phantom reference" arm. `:de` runs before `:para` per
8919 // the canonical edge-direction order the existing
8920 // membership lookup, self-edge check, target dispatch,
8921 // and diagnostic strings already use.
8922 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
8923 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
8924 // Per-edge graph-membership gate on the twin `:de` / `:para`
8925 // arms — folded onto the substrate-primitive dispatch
8926 // [`WitContract::require_endpoints_in`] so every per-edge
8927 // consumer of the endpoint-resolution axis (this per-slot
8928 // gate at build time, the M4 admission webhook re-checking
8929 // one edge after a per-`(:de, :para)` patch, the per-edge
8930 // `:politicas` override MESH-COMPOSITION §III.2 #3
8931 // acknowledges) reaches the axis through one call rather
8932 // than re-inlining the twin `if !names.contains(...)`
8933 // cascade. `:de` fires before `:para` inside the primitive,
8934 // preserving byte-equal diagnostic ordering with the
8935 // pre-lift inline cascade.
8936 c.require_endpoints_in(&names)?;
8937 // A `:contratos` entry is an *inter*-Servico contract
8938 // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
8939 // typed edge between two distinct graph nodes. An edge whose
8940 // `:de` equals its `:para` is a Servico contracting with
8941 // itself — a degenerate edge under every WIT shape. Firing
8942 // the gate before the `:wit`/`target()` shape checks means
8943 // the structural "this edge can't exist" error precedes the
8944 // narrower payload-shape diagnostics, and shape-agnostically
8945 // covers all four `WitTarget` arms (HTTP / Store / Capability
8946 // / PubSub) at one point. Peer of the duplicate-`:contratos`
8947 // / duplicate-`:membros` set gates: both reject a structurally
8948 // ill-formed graph at the typed surface, before the renderer
8949 // emits a K8s object that fails or no-ops far from the source
8950 // caixa.lisp.
8951 if c.is_self_loop() {
8952 return Err(AplicacaoError::contrato_self_loop(c));
8953 }
8954 if c.world_ref().is_empty() {
8955 return Err(AplicacaoError::empty_wit(c.edge_pair()));
8956 }
8957 // Shape ↔ target consistency — surfaces "HTTP wit without
8958 // :endpoint", "NATS wit with :endpoint set", etc. as named
8959 // build errors instead of silent renderer drops. Threaded
8960 // through the duplicate-edge diagnostic below (via
8961 // [`WitTarget::label`]) so the "which typed target arm did
8962 // the duplicate carry" question is answered by the typed
8963 // enum's variant discriminator, not by re-probing the raw
8964 // `Option<String>` payload fields.
8965 let target_view = c.target()?;
8966 // Contract identity: (de, para, wit, endpoint, subject, slot).
8967 // Two contracts that match on all six are the same typed edge
8968 // declared twice — author error, not a legitimate variant of
8969 // "same caller-callee pair, different payload" (e.g.
8970 // cart→catalog at /products vs /search), which keeps distinct
8971 // identity keys via the differing endpoint payloads.
8972 let key = c.identity();
8973 crate::render::insert_first_seen(&mut seen_contracts, key, || {
8974 AplicacaoError::contrato_duplicate(c, &target_view)
8975 })?;
8976 }
8977
8978 // Cross-edge cycle axis on the `:contratos` slot — folded into
8979 // the per-slot gate so the two structural axes on `:contratos`
8980 // (per-entry shape + membership + dedup above; cross-edge sync-
8981 // cycle detection here) reach every consumer through one call.
8982 // Same discipline the sibling per-slot compound gate
8983 // [`MeshPolicy::validate`] (f03a154) established on `:politicas`
8984 // — one named per-slot gate that folds *both* per-axis and
8985 // cross-axis surfaces on the same slot onto one substrate
8986 // primitive — extended here onto `:contratos`, closing the last
8987 // per-slot-axis-family that lived split across `validate` (the
8988 // per-entry `validate_contratos` half here and the cross-edge
8989 // `detect_sync_cycles` call the sibling below at `validate`
8990 // dispatched separately).
8991 //
8992 // Runs after the per-entry cascade so a per-entry defect (empty
8993 // arm, unknown endpoint, self-loop, empty `:wit`, WIT-shape ↔
8994 // target inconsistency, whole-edge duplicate) surfaces first
8995 // through its narrower [`AplicacaoError`] arm before the cross-
8996 // edge cycle diagnostic. This matches the pre-lift ordering the
8997 // `validate`-side dispatch used verbatim (`self.validate_contratos()?
8998 // → self.detect_sync_cycles()?`) — the cycle detector was
8999 // already the second `:contratos`-axis gate in the dispatch,
9000 // just at the outer altitude; the fold moves it under the same
9001 // named per-slot gate without reshaping the diagnostic order.
9002 self.detect_sync_cycles()?;
9003
9004 Ok(())
9005 }
9006
9007 /// Reject `:entrada` values that are operationally meaningless,
9008 /// structurally malformed, or reference a Servico outside the
9009 /// graph.
9010 ///
9011 /// The `:entrada` slot is the Aplicacao's single external ingress
9012 /// (MESH-COMPOSITION §III.1): `:host` + `:port` become a K8s
9013 /// Gateway API v1 `Listener`, `:paths` become the paired
9014 /// `HTTPRoute`'s `matches[].path.value` entries, and `:para` names
9015 /// the member the route forwards to. Omitting the slot entirely is
9016 /// the internal-only-mesh partition — an Aplicacao with no external
9017 /// surface — so the `None` arm is a clean pass, not a refusal.
9018 ///
9019 /// Five axes are gated here, in the canonical order the paired
9020 /// diagnostics already encode (reference-resolution before value
9021 /// shape, per-axis emptiness before per-axis grammar):
9022 ///
9023 /// - `:para` — DNS-1123 value shape, then membership against the
9024 /// [`AplicacaoSpec::membro_names`] oracle;
9025 /// - `:host` — emptiness, then the Gateway API hostname grammar;
9026 /// - `:port` — the [`SERVICO_PORT_MIN`] structural floor;
9027 /// - `:paths` — per-entry emptiness, leading-`/`, the Gateway API
9028 /// path grammar, and set-not-multiset uniqueness.
9029 ///
9030 /// Lifted out of [`AplicacaoSpec::validate`]'s inline `if let
9031 /// Some(e) = self.entrada() { … }` block onto a named per-slot
9032 /// gate, the shape the three peer M3 mesh slots already carry
9033 /// ([`AplicacaoSpec::validate_membros`],
9034 /// [`AplicacaoSpec::validate_placement`],
9035 /// [`AplicacaoSpec::validate_politicas`]). Self-contained on
9036 /// `&self` — it resolves its own membership oracle through
9037 /// [`AplicacaoSpec::membro_names`] rather than borrowing one
9038 /// threaded down from `validate` — so a future consumer that
9039 /// re-validates *one* slot against a mutated spec (the M4 admission
9040 /// webhook re-checking `:entrada` after a gateway-host patch
9041 /// without re-walking the whole `:contratos` graph) reaches the
9042 /// axis through one call, exactly as `detect_sync_cycles` is
9043 /// already self-contained for the M4 per-edge policy resolver.
9044 fn validate_entrada(&self) -> Result<(), AplicacaoError> {
9045 let names = self.membro_names();
9046 if let Some(e) = self.entrada() {
9047 // Route the per-`:entrada` composite-reference read
9048 // through the lifted [`AplicacaoSpec::entrada`] accessor
9049 // rather than the raw `&self.entrada` field access — the
9050 // shape-and-membership gate's traversal head is now the
9051 // canonical read-side surface every per-Aplicacao entrada
9052 // consumer routes through, closing the fourth of four
9053 // open-coded outer-field accesses on the per-`:entrada`
9054 // outer-composite axis.
9055 //
9056 // Shape gate on `:entrada :para` runs ahead of the
9057 // membership lookup. Every `:membros :caixa` past
9058 // `validate_membro_caixa` is a valid DNS-1123 label
9059 // (3f9d7a0), so the `names` set structurally cannot
9060 // contain an empty / malformed string and the membership-
9061 // lookup diagnostic always misframed the root cause as
9062 // "this caixa is not in `:membros`". The shape gate
9063 // routes structurally-impossible-to-match inputs through
9064 // the narrower self-locating diagnostic, preserving the
9065 // legitimate "well-shaped phantom reference" arm — the
9066 // same trajectory the peer `:membros :caixa` (3f9d7a0),
9067 // `:placement :clusters` (6c8c00b), and `:contratos :de`
9068 // / `:para` (8d5af6b) axes already follow. This closes
9069 // the fourth and last Aplicacao-level Servico-name
9070 // reference axis on the canonical DNS-1123 floor.
9071 // Route the per-`:entrada :para` byte-string reads through
9072 // the lifted [`Entrada::destination`] accessor rather than
9073 // the raw `e.para` field access — the three
9074 // per-`AplicacaoSpec::validate` `:entrada :para` consumers
9075 // (shape-gate `validate_entrada_para` arg, membership
9076 // lookup, `EntradaMemberMissing` diagnostic carry) now key
9077 // off exactly one typed dispatch on the substrate
9078 // primitive, closing the last unlifted per-`:entrada :para`
9079 // raw-field-access axis on the M3 mesh-slot validator.
9080 // The `.destination().to_string()` at the diagnostic site
9081 // is byte-identical to `.para.clone()` — pinned by the
9082 // sibling `destination_returns_entrada_para_byte_equal` +
9083 // `destination_borrows_from_entrada_para_storage` accessor
9084 // tests — so a future rebrand of the underlying `:para`
9085 // storage (a lift from `String` to a typed
9086 // `ServicoName(String)` newtype, a per-Aplicacao interning
9087 // arena the M4 CR materializer authors, a
9088 // `smol_str::SmolStr` inline-buffer swap) flows through
9089 // the accessor's one body without a coordinated
9090 // per-consumer rewrite across the M3 mesh validator.
9091 validate_entrada_para(e.destination())?;
9092 if !names.contains(e.destination()) {
9093 return Err(AplicacaoError::entrada_member_missing(e));
9094 }
9095 // Route the per-`:entrada :host` byte-string reads through
9096 // the lifted [`Entrada::hostname`] accessor rather than
9097 // the raw `e.host` field access — the emptiness gate and
9098 // the shape-gate `validate_entrada_host` arg now key off
9099 // exactly one typed dispatch on the substrate primitive,
9100 // closing the last unlifted per-`:entrada :host` raw-
9101 // field-access axis on the M3 mesh-slot validator. Peer
9102 // of the sibling per-`:entrada :para` convergence above
9103 // and pinned by the existing
9104 // `hostname_returns_entrada_host_byte_equal` +
9105 // `hostnames_returns_singleton_of_hostname_accessor`
9106 // accessor tests, so any future
9107 // Gateway-API-shaped host renormalization (a wildcard-
9108 // label lift, a trailing-`.` FQDN substitution, an IDNA
9109 // Punycode round-trip the SNI fan-out overlay authors)
9110 // flows through the accessor's one body without a
9111 // coordinated per-consumer rewrite across the M3 mesh
9112 // validator.
9113 if e.hostname().is_empty() {
9114 return Err(AplicacaoError::EmptyEntradaHost);
9115 }
9116 // The `:host` lands verbatim as a K8s Gateway API v1
9117 // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
9118 // both apiserver-validated against the same restrictive
9119 // pattern: lowercase RFC 1123 DNS subdomain, optional
9120 // single leading wildcard label (`*.`), max length 253,
9121 // per-label max length 63, no IP literals, no scheme,
9122 // no port. Until this gate landed `validate()` only
9123 // refused the empty string (`EmptyEntradaHost`); a
9124 // structurally invalid hostname (`"https://example.com"`,
9125 // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
9126 // `"_underscored.example.com"`, `"FOO.example.com"`,
9127 // `"checkout.quero.cloud."`) silently passed validate
9128 // and the apiserver `field is invalid` error surfaced at
9129 // `kubectl apply` time, far from the source caixa.lisp.
9130 // Lifting the gate to caixa-build time mirrors the
9131 // `:entrada :paths` value-shape trajectory (eb3456d) and
9132 // closes the last unstructured `:entrada` axis.
9133 validate_entrada_host(e.hostname())?;
9134 // Structural-floor gate on `:entrada :port`: every
9135 // validated `Entrada::port` past this gate lies in
9136 // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
9137 // type-inferred ceiling closes the top edge, so no companion
9138 // upper-cap arm is needed here — unlike the peer capped-
9139 // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
9140 // `require_positive_bounded_u32` bracket covers both edges).
9141 // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
9142 // accept-set-floor const rather than the prior inline
9143 // `if e.port == 0` byte-check so a future rebrand of the
9144 // accept-set floor (a hypothetical unprivileged-only
9145 // migration lifting the floor to `1024`, a per-cluster
9146 // scoping the operator pins through a future
9147 // `:placement :port-floor` slot as the M4 typed-slot
9148 // trajectory adds it, the future
9149 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
9150 // per-Aplicacao gateway resolver reaching for the same
9151 // floor) is a one-line edit on the canonical
9152 // [`SERVICO_PORT_MIN`] declaration, not a coordinated
9153 // rewrite across the emit site + the pin test + every
9154 // future per-target renderer the substrate adds.
9155 if e.port() < SERVICO_PORT_MIN {
9156 return Err(AplicacaoError::EntradaPortZero);
9157 }
9158 // Each `:entrada :paths` entry becomes a K8s Gateway API
9159 // HTTPRoute `matches[].path.value`. The Gateway API rejects
9160 // values that don't start with `/` for `type: PathPrefix`,
9161 // and an empty value is meaningless. Surface those as build
9162 // errors (MESH-COMPOSITION §III.3) rather than apply-time
9163 // failures. Empty `:paths` itself is fine — caixa-mesh
9164 // falls back to a single `/` catch-all.
9165 let mut seen = std::collections::HashSet::new();
9166 // Route the per-entry value-shape gate's traversal head
9167 // through the lifted [`Entrada::paths`] slice accessor
9168 // rather than the raw `&e.paths` field access — the
9169 // per-Aplicacao `:entrada :paths` validate loop now keys
9170 // off the canonical raw-slot surface every downstream
9171 // per-`:entrada` path-list consumer (the sibling
9172 // [`Entrada::resolved_paths`] fallback-applying resolver
9173 // internal reads, `feira app graph`'s per-Aplicacao entrada
9174 // summary line's `{:?}` Debug print) routes through, so any
9175 // future rebrand on the typed slot's raw-slot reader lands
9176 // at exactly one place. Same convergence discipline as the
9177 // sibling [`Placement::clusters`] (a6e18d7) reader-site
9178 // convergences on the peer M3 mesh-slot `Vec<String>`-carry
9179 // axis.
9180 for p in e.paths() {
9181 if p.is_empty() {
9182 return Err(AplicacaoError::EntradaPathEmpty);
9183 }
9184 if !p.starts_with('/') {
9185 return Err(AplicacaoError::entrada_path_not_absolute(p));
9186 }
9187 // Per-entry value-shape gate: the path lands verbatim
9188 // as a K8s Gateway API HTTPRoute `matches[].path.value`
9189 // (caixa-mesh/src/lib.rs:498), apiserver-validated
9190 // against `maxLength: 1024` + the Gateway API webhook's
9191 // path-grammar rules (no `//`, no `/./`, no `/../`, no
9192 // query/fragment separators, no whitespace, no control
9193 // characters, no non-ASCII bytes). Until this gate
9194 // landed `validate` only refused the empty string and
9195 // missing-leading-slash (eb3456d); a structurally
9196 // invalid path (`"/api?q=1"`, `"/api#frag"`,
9197 // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
9198 // 1025-byte URL-shaped slug) silently passed validate
9199 // and the failure surfaced at `kubectl apply` time as
9200 // a Gateway API webhook rejection, far from the source
9201 // caixa.lisp, with no field naming the offending
9202 // `:paths` entry. Lifting the gate to caixa-build time
9203 // mirrors the `:entrada :host` value-shape trajectory
9204 // (c7d05ec) on the sibling axis — every author surface
9205 // that emits a Gateway API field now matches the
9206 // apiserver's accepted set at validate time.
9207 validate_entrada_path(p)?;
9208 crate::render::insert_first_seen(&mut seen, p.as_str(), || {
9209 AplicacaoError::entrada_path_duplicate(p)
9210 })?;
9211 }
9212 }
9213
9214 Ok(())
9215 }
9216
9217 /// Reject `:membros` values that are operationally meaningless. The
9218 /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
9219 /// every entry names a Servico that participates in the Aplicacao,
9220 /// and the rendered programs.yaml fan-out emits one entry per
9221 /// `:membros`. Three authoring footguns are closed here:
9222 ///
9223 /// - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
9224 /// a `programs:` entry whose `name:` is the empty string, which
9225 /// downstream `lareira-fleet-programs` rejects at template time
9226 /// with a non-localized error;
9227 /// - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
9228 /// an empty semver constraint, so the failure surfaces far from
9229 /// the source caixa.lisp;
9230 /// - duplicate `:caixa` names — two entries with the same name
9231 /// produce duplicate programs.yaml entries (one silently
9232 /// overwrites the other in the cluster's HelmRelease values), and
9233 /// contract membership lookups against `:contratos` collapse the
9234 /// two onto one node, masking authoring mistakes.
9235 ///
9236 /// Same value-shape discipline as `:placement :clusters` (where empty
9237 /// + duplicate cluster names are rejected) and `:entrada :paths`
9238 /// (where empty + duplicate path entries are rejected). Lifting these
9239 /// invariants to the typed surface mirrors the MESH-COMPOSITION
9240 /// §III.3 promise that the `:membros` set — the load-bearing identity
9241 /// of the application graph — is well-formed by construction.
9242 fn validate_membros(&self) -> Result<(), AplicacaoError> {
9243 if self.membros().is_empty() {
9244 return Err(AplicacaoError::NoMembros);
9245 }
9246 let mut seen = std::collections::HashSet::new();
9247 for m in self.membros() {
9248 // Every emitted cluster artifact's `metadata.name` derives
9249 // from a `:membros :caixa` value verbatim — the rendered
9250 // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
9251 // the [`crate::LABEL_PROGRAM`] label value on every CNP
9252 // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
9253 // 272), the composed `CiliumNetworkPolicy` `metadata.name`
9254 // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
9255 // `metadata.name` when the member is the `:entrada :para`
9256 // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
9257 // schema enforces the DNS-1123 label rule on admission;
9258 // a structurally invalid member name (`"Cart"`, `"my_cart"`,
9259 // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
9260 // mistaken-identity slug) silently passes the prior empty-/
9261 // duplicate-only gate and the failure surfaces at `kubectl
9262 // apply` time as a `metadata.name: Invalid value` rejection,
9263 // far from the source caixa.lisp, with no field naming the
9264 // offending `:membros` entry. Lifting the gate to caixa-build
9265 // time mirrors the `:entrada :host` value-shape trajectory
9266 // (c7d05ec) on the peer axis — every author surface that
9267 // emits a K8s name now matches the apiserver's accepted set
9268 // at validate time.
9269 validate_membro_caixa(m.nome())?;
9270 // The author surface for `:versao` is the same Cargo-shaped
9271 // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
9272 // `"*"`) every `:deps` entry carries — and the lacre pipeline
9273 // resolves both axes through the same
9274 // [`crate::version::parse_requirement`] entry-point. The
9275 // shared [`crate::render::require_valid_versao_requirement`]
9276 // helper brackets the empty-first + parse cascade both peer
9277 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
9278 // [`crate::SupervisorSpec::validate`] on `:children :versao`)
9279 // route through, so drift between the three axes' accepted
9280 // requirement sets is structurally impossible and the parse-
9281 // side no-op the empty-first arm closes (semver's empty
9282 // parse yields an implicit `*`) lives in exactly one
9283 // predicate.
9284 crate::render::require_valid_versao_requirement(
9285 m.versao_requirement(),
9286 || AplicacaoError::membro_versao_empty(m.nome()),
9287 |reason| {
9288 AplicacaoError::membro_versao_invalid(m.nome(), m.versao_requirement(), reason)
9289 },
9290 )?;
9291 crate::render::insert_first_seen(&mut seen, m.nome(), || {
9292 AplicacaoError::membro_duplicate(m.nome())
9293 })?;
9294 }
9295 Ok(())
9296 }
9297
9298 /// Reject `:placement` values that are operationally meaningless or
9299 /// internally contradictory. Each strategy variant has the same
9300 /// invariants on `:clusters` (non-empty list, non-empty unique
9301 /// entries) — the §III.1 author surface is uniform on this axis,
9302 /// even though the *meaning* of the list differs by strategy
9303 /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
9304 /// shard pool).
9305 ///
9306 /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
9307 /// are the same authoring footgun closed for `:politicas` zero
9308 /// values and `:entrada` empty paths: the field is *declared* but
9309 /// carries no meaning, so downstream renderers either skip it
9310 /// silently (cluster-fanout drops the empty entry, no diagnostic)
9311 /// or apply it literally and fail at admission time. Lifting both
9312 /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
9313 /// violation is a build error" promise.
9314 ///
9315 /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
9316 /// is required exactly when `:estrategia Sharded` (hash-keyed
9317 /// distribution, Akka cluster-sharding convention, §II.4) and
9318 /// refused on `:estrategia Replicated`/`SingleNode` (where no
9319 /// hash-keyed routing axis consumes it). The partition closes the
9320 /// "I think I configured sharding" footgun where an author writes
9321 /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
9322 /// the typed slot's value silently vanishes at the renderer layer
9323 /// — every validated `Placement` past this call satisfies
9324 /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
9325 fn validate_placement(&self) -> Result<(), AplicacaoError> {
9326 // Every strategy needs at least one named cluster: `Replicated`
9327 // and `SingleNode` use the list as hosting/takeover candidates
9328 // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
9329 // §II.1), while `Sharded` uses it as the shard pool
9330 // (Akka cluster-sharding convention — §II.4). An empty list is
9331 // meaningless under any of the three.
9332 //
9333 // Route the paired pre-flight `.is_empty()` refusal probe and
9334 // the per-cluster validate loop's traversal head through the
9335 // lifted [`Placement::clusters`] slice-return accessor rather
9336 // than the raw `self.placement.clusters` field access — the
9337 // two production consumers of the per-`:placement` cluster-
9338 // pool `Vec`-carry now key off exactly one typed dispatch on
9339 // the substrate primitive, so any future rebrand on the axis
9340 // (a per-tenant cluster-pool overlay the operator pins through
9341 // a future `:placement :clusters-overrides` slot, a per-
9342 // Aplicacao dynamic cluster-pool derivation the future M5
9343 // adaptive-placement engine computes from `:affinity` weights)
9344 // migrates as a single caixa-core edit rather than a
9345 // coordinated rewrite of the paired arms — sibling of the
9346 // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
9347 // arm migration on the per-`:supervisor` static-child-list
9348 // `Vec`-carry axis.
9349 //
9350 // Route the per-`:placement` outer-composite reference read
9351 // through the lifted [`AplicacaoSpec::placement`] outer accessor
9352 // rather than the raw `&self.placement` field access — the
9353 // per-axis bracket-dispatch fan-out below (`p.clusters()`,
9354 // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
9355 // axis-level lifted accessor family) now routes through the
9356 // substrate-primitive typed dispatch at the outer composition
9357 // altitude, the same shape the peer caixa-mesh
9358 // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
9359 // and the sibling `feira app graph` per-Aplicacao print line
9360 // now key off after this accessor lift.
9361 let p = self.placement();
9362 if p.clusters().is_empty() {
9363 // Route the per-`:placement` empty-clusters diagnostic
9364 // through the substrate-primitive
9365 // [`AplicacaoError::placement_without_clusters`] ctor rather
9366 // than the pre-lift three-line open-coded
9367 // `AplicacaoError::PlacementWithoutClusters { estrategia:
9368 // p.estrategia() }` struct-literal — folds the sole in-crate
9369 // wire-up on this variant onto one dispatch matching the
9370 // sibling per-`:placement :clusters` dedup /
9371 // per-`:contratos` self-edge / per-`:upgrade-from :from`
9372 // duplicate substrate-primitive-projection ctors on the
9373 // same `AplicacaoError` / `UpgradeError` envelopes.
9374 return Err(AplicacaoError::placement_without_clusters(p));
9375 }
9376 let mut seen = std::collections::HashSet::new();
9377 for c in p.clusters() {
9378 // Per-entry value-shape gate: the cluster name lands in
9379 // every K8s context / `lareira-fleet-programs` aggregator
9380 // filter / future M4 CR materializer's per-cluster axis
9381 // a validated `:clusters` entry passes through, each
9382 // enforcing the DNS-1123 label rule on admission. Same
9383 // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
9384 // on the peer name axis — both axes' validated values
9385 // are guaranteed-accepted by the apiserver without
9386 // re-validation at any downstream renderer or admission
9387 // layer.
9388 validate_placement_cluster(c)?;
9389 crate::render::insert_first_seen(&mut seen, c.as_str(), || {
9390 // Route the per-`:placement :clusters` dedup diagnostic
9391 // through the substrate-primitive
9392 // [`AplicacaoError::placement_cluster_duplicate`] ctor
9393 // rather than the pre-lift three-line open-coded
9394 // `AplicacaoError::PlacementClusterDuplicate { cluster:
9395 // c.clone() }` struct-literal — folds the sole in-crate
9396 // wire-up on this variant onto one dispatch matching the
9397 // sibling per-`:membros :caixa` / per-`:entrada :paths` /
9398 // per-`:politicas <scalar>` single-slot ctor families on
9399 // the same [`AplicacaoError`] envelope.
9400 AplicacaoError::placement_cluster_duplicate(c)
9401 })?;
9402 }
9403 // Route the per-`:placement :affinity` per-hint value-shape
9404 // gate through the typed [`Placement::affinity`] accessor rather
9405 // than the raw `&self.placement.affinity` field access — the
9406 // sole open-coded field-access site on the per-`:placement`
9407 // M3-Adaptive-compression-hint axis the accessor lift now owns.
9408 // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
9409 // the accessor's `Option<&str>` return type;
9410 // [`validate_placement_affinity`]'s `&str` parameter accepts
9411 // the narrower borrow without a re-allocation, so the routing
9412 // change is byte-for-byte in the pass arm and remains
9413 // byte-for-byte in every failure diagnostic
9414 // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
9415 // String` field is populated inside
9416 // [`validate_placement_affinity`] via the peer `.to_string()`
9417 // path on the same borrowed slice). Peer of the sibling
9418 // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
9419 // routing through [`Placement::shard_key`] at the caixa-core
9420 // site above — extends the "read `:placement` optional-scalars
9421 // through the typed accessor" discipline to the second
9422 // `Option<String>`-shape slot on the M3 mesh-slot family.
9423 //
9424 // Per-hint value-shape gate: the `:affinity` value lands
9425 // verbatim in the M3 Adaptive compression overlay
9426 // (caixa-mesh's `placement.affinity` emission) and every
9427 // future M4 placement-engine routing axis keying off the
9428 // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
9429 // selector — each enforces the DNS-1123 label rule on
9430 // admission. Same typed-shape trajectory as `:placement
9431 // :clusters` (6c8c00b) on the sibling slot and the four
9432 // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
9433 // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
9434 // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
9435 // on the Aplicacao surface to land on the canonical
9436 // [`crate::render::is_dns_1123_label`] floor.
9437 if let Some(a) = p.affinity() {
9438 validate_placement_affinity(a)?;
9439 }
9440 match p.estrategia() {
9441 // Route the `Sharded`-arm shape-gate cascade through the
9442 // typed [`Placement::shard_key`] accessor rather than the
9443 // raw `&self.placement.shard_key` field access — one of the
9444 // two open-coded field-access sites on the per-`:placement`
9445 // Akka-cluster-sharding-key axis the accessor lift now
9446 // owns. The `Some(k)`-bound `k` narrows from `&String` to
9447 // `&str` under the accessor's `Option<&str>` return type;
9448 // `str::is_empty` and [`validate_placement_shard_key`]'s
9449 // `&str` parameter both accept the narrower borrow without
9450 // a re-allocation.
9451 PlacementStrategy::Sharded => match p.shard_key() {
9452 None => return Err(AplicacaoError::ShardedWithoutKey),
9453 Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
9454 // Per-axis value-shape gate on the Akka-cluster-sharding
9455 // `:shard-key` extractor expression. The shape gate runs
9456 // after the more self-locating `ShardedKeyEmpty` arm so
9457 // a `:shard-key ""` surfaces the narrower empty
9458 // diagnostic first; every non-empty `:shard-key` past
9459 // this call is guaranteed to be a printable-ASCII
9460 // single-token reference the future M4 Akka-style
9461 // cluster-sharding reconciler can hash without
9462 // re-validating at the runtime layer. Mirrors the
9463 // payload-axis shape gates on the peer `:contratos`
9464 // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
9465 // 63e18a0 / c4213a4) — each lifts the runtime parser's
9466 // intersection-floor to a caixa-build-time gate.
9467 Some(k) => validate_placement_shard_key(k)?,
9468 },
9469 // `:shard-key` is the Akka-cluster-sharding axis
9470 // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
9471 // across the cluster pool. `Replicated` (active-active across
9472 // every named cluster) and `SingleNode` (Erlang/OTP
9473 // distributed-app takeover/failover, §II.1) have no hash-keyed
9474 // routing axis to consume the slot; downstream renderers
9475 // (caixa-mesh's `placement.shardKey` overlay at
9476 // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
9477 // sharding reconciler) ignore `:shard-key` outside the
9478 // `Sharded` arm by construction. Until this gate landed an
9479 // author who wrote `:placement (:estrategia Replicated
9480 // :shard-key "tenantId")` (an off-by-one strategy typo, a
9481 // copy-paste from a Sharded sibling caixa, the "I think I
9482 // configured sharding" footgun) silently passed validate and
9483 // the typed slot's value vanished at the renderer layer with
9484 // no diagnostic — the canonical "declared-but-inert" footgun
9485 // the empty-:affinity / empty-shard-key / zero-:politicas /
9486 // empty-:contratos-target gates already close on every other
9487 // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
9488 // Lifting the rejection to a build-time gate closes the
9489 // Sharded ↔ non-Sharded partition over the typed
9490 // `:placement` slot: every validated `Placement` past this
9491 // call has `shard_key.is_some()` iff `estrategia ==
9492 // Sharded`, structurally — the future Akka reconciler can
9493 // reach for `placement.shard_key` knowing it's `Some` exactly
9494 // when the strategy consumes it, without re-deriving the
9495 // partition from inline strategy probes.
9496 PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
9497 // Route the non-`Sharded`-arm declared-but-inert refusal
9498 // through the typed [`Placement::shard_key`] accessor —
9499 // the second of the two open-coded field-access sites the
9500 // accessor lift now owns. The `Some(k)`-bound `k` narrows
9501 // from `&String` to `&str`; the `AplicacaoError::
9502 // ShardKeyOnNonSharded { shard_key: String }` diagnostic
9503 // materializes the owned `String` via `k.to_string()`
9504 // (peer to the sibling per-Membro `String`-carry sites
9505 // 4127bb6 routed through `m.nome().to_string()` /
9506 // `m.versao_requirement().to_string()`), so the whole
9507 // `Sharded` ↔ non-`Sharded` partition on the
9508 // `:shard-key` axis now flows through the same typed
9509 // dispatch as the sibling `Sharded`-arm shape gate.
9510 if let Some(k) = p.shard_key() {
9511 return Err(AplicacaoError::shard_key_on_non_sharded(p, k));
9512 }
9513 }
9514 }
9515 Ok(())
9516 }
9517
9518 /// Reject `:politicas` values that are operationally meaningless.
9519 /// Each axis is optional — omitting it expresses "no policy on this
9520 /// axis". Carrying a *zero* value for a declared axis is the bug
9521 /// this function rejects: zero is either
9522 ///
9523 /// - re-interpreted as "infinite" by downstream proxies (Envoy's
9524 /// `RouteAction.timeout = 0s` disables the timeout entirely),
9525 /// directly contradicting MESH-COMPOSITION §V CSE invariant
9526 /// "every Aplicacao declares :politicas :timeout (no infinite
9527 /// blocking)", or
9528 /// - a renderer footgun (a 0-failure circuit breaker trips on the
9529 /// first call; a 0-rate rate-limit denies every request).
9530 ///
9531 /// Lifting these "0 means the opposite of what you think" idioms to
9532 /// the typed Aplicacao surface as build errors mirrors the §III.3
9533 /// promise that contract drift, capability leaks, and cycles are all
9534 /// build errors — not runtime surprises.
9535 fn validate_politicas(&self) -> Result<(), AplicacaoError> {
9536 // Route the whole per-axis + cross-axis `:politicas` cascade
9537 // through the substrate primitive [`MeshPolicy::validate`],
9538 // which folds all six per-axis brackets (`:timeout`,
9539 // `:retries`, `:circuit-breaker :max-failures`,
9540 // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
9541 // window-canonical-form) plus the compound cross-axis fold
9542 // [`MeshPolicy::first_cross_axis_violation`] into one
9543 // `Result<(), AplicacaoError>` return. The whole per-axis-
9544 // brackets + cross-axis-fold cascade collapses to one call, and
9545 // every future [`MeshPolicy`] consumer (the future M4
9546 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
9547 // admission webhook, the per-`:contratos`-edge `:politicas`
9548 // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
9549 // of which resolves an *effective* per-edge [`MeshPolicy`] and
9550 // must emit *the same* diagnostic on the same input as `feira
9551 // build`) reaches through the same substrate-primitive dispatch
9552 // rather than re-inlining the four-per-axis + one-cross-axis
9553 // cascade in lockstep with this validate gate. Same trajectory
9554 // the peer per-kind compound entry gates
9555 // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
9556 // [`crate::render::require_supervisor_view`] (8d8a5c3),
9557 // [`crate::render::require_v0_servico_shape`] (per-Caixa
9558 // layout axis) and the sibling compound cross-axis fold
9559 // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
9560 // extended here onto the per-slot compound entry gate that
9561 // folds both per-axis + cross-axis surfaces on the M3
9562 // mesh-slot family.
9563 self.politicas().validate()
9564 }
9565
9566 /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
9567 /// A synchronous edge is any contract whose typed [`WitTarget`] is
9568 /// `Http`, `Store`, or `Capability` — the caller blocks on the
9569 /// callee, so a cycle would deadlock at runtime. Pub-sub edges
9570 /// (`WitTarget::PubSub`) are skipped: an event publisher does not
9571 /// block on its subscribers, so they can never close a sync loop.
9572 ///
9573 /// Iterative DFS with three-coloring; the reported cycle is the
9574 /// path of caixa names traversed from the back-edge target around
9575 /// to itself, in declaration order. Adjacency lists and DFS roots
9576 /// are visited in `BTreeMap` key order so the diagnostic is
9577 /// deterministic across runs.
9578 ///
9579 /// Now the cross-edge axis of the per-slot compound gate
9580 /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
9581 /// the per-entry cascade rather than at the outer
9582 /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
9583 /// `:contratos` (per-entry shape + membership + dedup; cross-edge
9584 /// sync-cycle) reach every consumer through one call. Kept
9585 /// standalone (rather than inlined) so consumers that want only the
9586 /// cross-edge axis (the M4 per-edge policy resolver
9587 /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
9588 /// mutates one `:contratos` entry and needs to re-probe *just* the
9589 /// cycle invariant against the post-patch adjacency without
9590 /// re-running the per-entry shape/membership/dedup cascade the
9591 /// per-entry-only [M4 admission] fast path already covered) still
9592 /// have a self-contained entry point on the cycle axis.
9593 fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
9594 use std::collections::{BTreeMap, BTreeSet};
9595
9596 #[derive(Clone, Copy, PartialEq, Eq)]
9597 enum Mark {
9598 White,
9599 Gray,
9600 Black,
9601 }
9602
9603 let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
9604 for m in self.membros() {
9605 adj.entry(m.nome()).or_default();
9606 }
9607 for c in self.contratos() {
9608 // target() was already called by validate(); re-running here
9609 // keeps detect_sync_cycles self-contained for callers that
9610 // reuse it (M4 per-edge policy resolver) without revalidating.
9611 //
9612 // The pub-sub-arm check routes through the lifted
9613 // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
9614 // arm-discriminator predicate rather than a raw `matches!(…,
9615 // WitTarget::PubSub { .. })` on the variant so a future
9616 // rebrand on the axis (an M4 per-edge WIT registry split of
9617 // [`WitTarget::PubSub`] into shape-specific peers, a
9618 // per-consumer rename that the accept-set already carries)
9619 // reaches this call site through the derive rather than a
9620 // scattered per-arm `matches!` rewrite — same
9621 // `IsVariant`-derived-arm-discriminator discipline the
9622 // peer closed-set typed enums ([`crate::CaixaKind`] via
9623 // f5bba80, [`PlacementStrategy`] via 766ec63,
9624 // [`crate::supervisor::RestartStrategy`] +
9625 // [`crate::supervisor::RestartPolicy`],
9626 // [`crate::upgrade::UpgradeInstruction`] via 915a934)
9627 // already route through on the substrate's other typed-enum
9628 // arm-discriminator axes.
9629 if c.target()?.is_pubsub() {
9630 continue;
9631 }
9632 adj.entry(c.source()).or_default().insert(c.destination());
9633 }
9634
9635 let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
9636 let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
9637
9638 // Stable DFS root order — BTreeMap iteration is sorted by key.
9639 let roots: Vec<&str> = adj.keys().copied().collect();
9640
9641 // Frame: (node, sorted-neighbours snapshot, next-edge index).
9642 for root in roots {
9643 if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
9644 continue;
9645 }
9646 let root_neighbors: Vec<&str> = adj
9647 .get(root)
9648 .map(|s| s.iter().copied().collect())
9649 .unwrap_or_default();
9650 let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
9651 color.insert(root, Mark::Gray);
9652
9653 loop {
9654 // Read+advance the top frame in one borrow scope so we
9655 // can later mutate the stack (push/pop) without holding
9656 // a borrow across.
9657 let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
9658 let node = top.0;
9659 if top.2 >= top.1.len() {
9660 (node, None)
9661 } else {
9662 let nxt = top.1[top.2];
9663 top.2 += 1;
9664 (node, Some(nxt))
9665 }
9666 });
9667 let Some((node, nxt_opt)) = step else { break };
9668 let Some(nxt) = nxt_opt else {
9669 color.insert(node, Mark::Black);
9670 stack.pop();
9671 continue;
9672 };
9673 let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
9674 match nxt_color {
9675 Mark::Gray => {
9676 // Reconstruct the cycle from `node` back through
9677 // the parent chain to `nxt`, then close.
9678 let mut cycle = Vec::new();
9679 let mut cur = node;
9680 cycle.push(cur.to_string());
9681 while cur != nxt {
9682 match parent.get(cur).copied() {
9683 Some(p) => {
9684 cur = p;
9685 cycle.push(cur.to_string());
9686 }
9687 None => break,
9688 }
9689 }
9690 cycle.reverse();
9691 cycle.push(nxt.to_string());
9692 return Err(AplicacaoError::contrato_cycle(cycle));
9693 }
9694 Mark::White => {
9695 parent.insert(nxt, node);
9696 color.insert(nxt, Mark::Gray);
9697 let nxt_neighbors: Vec<&str> = adj
9698 .get(nxt)
9699 .map(|s| s.iter().copied().collect())
9700 .unwrap_or_default();
9701 stack.push((nxt, nxt_neighbors, 0));
9702 }
9703 Mark::Black => {}
9704 }
9705 }
9706 }
9707 Ok(())
9708 }
9709
9710 /// Substrate-canonical destination-facing TCP port every emitted
9711 /// per-Aplicacao artifact must key `destination`-shaped port axes
9712 /// off. Returns the typed `:entrada :port` scalar when this
9713 /// Aplicacao's `:entrada` block names `destination` under its
9714 /// `:para` axis (the destination Servico *is* the ingress apex, so
9715 /// the substrate honors the author-declared listener port
9716 /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
9717 /// fallback otherwise (every non-apex destination — the internal
9718 /// mesh Servicos `:contratos` reach across, the future per-edge
9719 /// policy resolver's per-destination probe targets, the
9720 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
9721 /// L4 port resolver — reads the same substrate-canonical port floor
9722 /// by construction).
9723 ///
9724 /// Prior to this lift the "if :entrada matches this destination use
9725 /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
9726 /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
9727 /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
9728 /// prior to this lift), with no typed method on the substrate primitive
9729 /// that named the rule. A future per-destination port axis addition
9730 /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
9731 /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
9732 /// per-Servico listener ports land, a per-cluster override the operator
9733 /// pins through a future `:placement :default-port` slot — would have
9734 /// to be threaded through every renderer's inline cascade in lockstep
9735 /// or one consumer would silently disagree on which port a given
9736 /// destination Servico's ingress lands at. Lifting the rule to a
9737 /// typed method on the substrate primitive means the M4 CR
9738 /// materializer, the future per-edge policy resolver, and every
9739 /// downstream test-fixture navigator reach for exactly one typed
9740 /// dispatch — the resolver's accept-set moves as a unit on any
9741 /// future axis addition.
9742 ///
9743 /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
9744 /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
9745 /// the typed primitive, thin projections at each consumer"
9746 /// discipline lifts on the sibling `:contratos` payload / `:politicas
9747 /// :rate-limit` unit-suffix axes; extends the discipline onto the
9748 /// destination-facing port-resolution axis every per-Aplicacao
9749 /// L4-fallback renderer consumes.
9750 #[must_use]
9751 pub fn port_for_destination(&self, destination: &str) -> u16 {
9752 // Route the per-`:entrada` composite-reference read through
9753 // the lifted [`AplicacaoSpec::entrada`] accessor rather than
9754 // the raw `self.entrada.as_ref()` field access — the
9755 // per-destination L4-port fallback resolver's composite-
9756 // projection seed is now the canonical read-side surface
9757 // every per-Aplicacao entrada consumer routes through, peer
9758 // of the sibling `validate` per-`:entrada` shape-and-
9759 // membership gate migration on the same outer-composite
9760 // axis.
9761 // Route the per-`:entrada` apex-destination membership probe
9762 // through the lifted [`Entrada::destination`] accessor rather
9763 // than the raw `e.para == destination` field access — the last
9764 // un-lifted `.para` production-code read site on the per-
9765 // `:entrada` `:para` axis, sibling to the four caixa-core
9766 // consumer sites the peer 15ddd8c converge already routed
9767 // through the accessor (the three
9768 // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
9769 // membership gate sites: the `validate_entrada_para` DNS-1123
9770 // shape gate, the per-`:membros` membership lookup, and the
9771 // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
9772 // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
9773 // `entrada.para`-projection converge at
9774 // caixa-core/src/render.rs (the `gateway_api_http_route_name`
9775 // route-name projection site). Prior to this converge the
9776 // `port_for_destination` resolver was the solitary consumer
9777 // bypassing the typed dispatch on the `.para` axis — the two
9778 // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
9779 // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
9780 // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
9781 // reach through the same accessor family compose with this
9782 // resolver at the emit boundary via the apex-identity
9783 // invariant `spec.port_for_destination(entrada.destination())
9784 // == entrada.port` the sibling
9785 // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
9786 // pin pins across four permutations. A future extension of the
9787 // `:entrada :para` axis to a richer author surface (a per-
9788 // cluster alias overlay the operator pins through a future
9789 // `:placement`-scoped slot, a namespace-qualified rewrite the
9790 // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
9791 // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
9792 // §III.2 acknowledges) that lands on the accessor would silently
9793 // disagree between this resolver and the two `caixa-mesh` emit
9794 // sites — an author-declared `:para "cart"` value the accessor
9795 // rewrote to `"cart-v2"` under a future canary arm would leave
9796 // the resolver's membership arm falling through to
9797 // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
9798 // `.para`) while the peer emit-site consumers landed on the
9799 // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
9800 // silently disagreed on which destination port a given typed
9801 // `:entrada` resolves to at cluster-apply time. Pinned by the
9802 // drift-detection test
9803 // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
9804 // below.
9805 self.entrada()
9806 .filter(|e| e.destination() == destination)
9807 .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
9808 }
9809}
9810
9811/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
9812/// entry may name the Aplicacao's own `:nome`.
9813///
9814/// An Aplicacao that lists itself as a member is a degenerate self-edge in
9815/// the typed graph — the application graph is a DAG rooted at the Aplicacao
9816/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
9817/// Servicos that compose the app; an Aplicacao is never its own constituent),
9818/// and the lacre pipeline's closure-resolution would otherwise be handed a
9819/// node that is its own parent: a one-node cycle it either rejects far from
9820/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
9821/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
9822/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
9823/// label + lacre closure root), a member whose `:caixa` equals the
9824/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
9825/// peer.
9826///
9827/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
9828/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
9829/// gate `validate_upgrade_from_against_versao` and the supervision-tree
9830/// self-parent gate `crate::supervisor::validate_no_self_supervision`
9831/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
9832/// not a tree/mesh edge" discipline, here on the second typed-graph axis
9833/// (the Aplicacao :membros set; the supervision-tree :children list was the
9834/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
9835/// every validated Supervisor's children are distinct from its `:nome`,
9836/// every validated Aplicacao's membros are distinct from its `:nome`. The
9837/// transitive consequence is that `:entrada :para` and `:contratos`
9838/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
9839/// name the Aplicacao itself, without re-deriving the partition.
9840pub fn validate_no_self_membership(
9841 membros: &[Membro],
9842 parent_nome: &str,
9843) -> Result<(), AplicacaoError> {
9844 for m in membros {
9845 if m.nome() == parent_nome {
9846 return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
9847 }
9848 }
9849 Ok(())
9850}
9851
9852#[derive(Debug, Error, PartialEq, Eq)]
9853pub enum AplicacaoError {
9854 #[error("Aplicacao must declare at least one :membros entry")]
9855 NoMembros,
9856 #[error(
9857 ":membros entry has empty :caixa (every member must name a Servico; \
9858 omit the entry instead of carrying an empty name)"
9859 )]
9860 MembroCaixaEmpty,
9861 #[error(
9862 ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
9863 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
9864 name / label value the member name lands in; use a lowercase \
9865 alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
9866 )]
9867 MembroCaixaInvalid { caixa: String, reason: String },
9868 #[error(
9869 ":membros entry {caixa:?} has empty :versao (every member must pin a \
9870 semver constraint that resolves through the lacre pipeline)"
9871 )]
9872 MembroVersaoEmpty { caixa: String },
9873 #[error(
9874 ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
9875 requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
9876 `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
9877 carries; the lacre pipeline resolves both through the same parser)"
9878 )]
9879 MembroVersaoInvalid {
9880 caixa: String,
9881 versao: String,
9882 reason: String,
9883 },
9884 #[error(
9885 ":membros entry {caixa:?} appears more than once (the graph node set \
9886 is a set, not a multiset; duplicate members produce duplicate \
9887 programs.yaml entries and ambiguous :contratos membership lookups)"
9888 )]
9889 MembroDuplicate { caixa: String },
9890 #[error(
9891 "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
9892 never its own constituent Servico (the application graph is a DAG rooted \
9893 at the Aplicacao; :membros names the *other* caixas that compose the \
9894 app, not the app itself). Since every :nome is a globally-unique \
9895 substrate identity, a member naming the Aplicacao's own :nome is a \
9896 one-node lacre-closure recursion, not a coincidentally-named peer; \
9897 drop the self-referential :membros entry or rename it to the actual \
9898 constituent caixa."
9899 )]
9900 MembroIsSelfAplicacao { caixa: String },
9901 #[error(
9902 "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
9903 caixa declared in :membros; omit the contract or fill the {slot} field with a \
9904 member name)"
9905 )]
9906 ContratoCaixaEmpty { slot: &'static str },
9907 #[error(
9908 "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
9909 :contratos {slot} value names a member of :membros, which is itself a \
9910 DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
9911 object the member name lands in — Service, Pod, identity-based Cilium \
9912 selector; use a lowercase alphanumeric + hyphen identifier like \
9913 `\"checkout\"` or `\"cart-v2\"`)"
9914 )]
9915 ContratoCaixaInvalid {
9916 slot: &'static str,
9917 caixa: String,
9918 reason: String,
9919 },
9920 #[error("contrato references caixa {caixa:?} not declared in :membros")]
9921 ContratoMemberMissing { caixa: String },
9922 #[error(
9923 "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
9924 entry is an inter-Servico contract whose :de and :para must name distinct \
9925 :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
9926 the contract, or point :para at the member it actually calls)"
9927 )]
9928 ContratoSelfLoop { caixa: String, wit: String },
9929 #[error("contrato {de:?} → {para:?} has empty :wit")]
9930 EmptyWit { de: String, para: String },
9931 #[error(
9932 "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
9933 {reason} (the substrate dispatches `:wit` values on the canonical \
9934 lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
9935 `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
9936 demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
9937 kebab-case identifier per segment)"
9938 )]
9939 ContratoWitInvalid {
9940 de: String,
9941 para: String,
9942 wit: String,
9943 reason: String,
9944 },
9945 #[error(
9946 ":entrada :para is empty (every :entrada must route to a caixa declared in \
9947 :membros; fill the :para field with a member name)"
9948 )]
9949 EntradaParaEmpty,
9950 #[error(
9951 ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
9952 :entrada :para value names a member of :membros, which is itself a DNS-1123 \
9953 label per the K8s apiserver's `metadata.name` rule on every object the \
9954 member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
9955 Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
9956 `\"checkout\"` or `\"cart-v2\"`)"
9957 )]
9958 EntradaParaInvalid { para: String, reason: String },
9959 #[error(":entrada routes to caixa {para:?} not declared in :membros")]
9960 EntradaMemberMissing { para: String },
9961 #[error(":entrada must declare a non-empty :host")]
9962 EmptyEntradaHost,
9963 #[error(
9964 ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
9965 (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
9966 `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
9967 like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
9968 )]
9969 EntradaHostInvalid { host: String, reason: String },
9970 #[error(":entrada :port must be in 1..=65535, got 0")]
9971 EntradaPortZero,
9972 #[error(":entrada :paths entry is empty (use the empty list to match all)")]
9973 EntradaPathEmpty,
9974 #[error(
9975 ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
9976 )]
9977 EntradaPathNotAbsolute { path: String },
9978 #[error(
9979 ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
9980 value: {reason} (the K8s apiserver enforces the same shape on \
9981 `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
9982 single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
9983 requires percent-encoding `%XX` for non-ASCII and whitespace)"
9984 )]
9985 EntradaPathInvalid { path: String, reason: String },
9986 #[error(":entrada :paths entry {path:?} appears more than once")]
9987 EntradaPathDuplicate { path: String },
9988 #[error(
9989 ":placement {estrategia} requires at least one :clusters entry \
9990 (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
9991 )]
9992 PlacementWithoutClusters { estrategia: PlacementStrategy },
9993 #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
9994 PlacementClusterEmpty,
9995 #[error(
9996 ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
9997 (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
9998 in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
9999 future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
10000 — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
10001 identifier like `\"rio\"` or `\"mar-east\"`)"
10002 )]
10003 PlacementClusterInvalid { cluster: String, reason: String },
10004 #[error(":placement :clusters entry {cluster:?} appears more than once")]
10005 PlacementClusterDuplicate { cluster: String },
10006 #[error(
10007 ":placement :affinity must be non-empty when set (omit :affinity to express \
10008 `no placement hint`)"
10009 )]
10010 PlacementAffinityEmpty,
10011 #[error(
10012 ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
10013 (placement hints land verbatim in the M3 Adaptive compression overlay's \
10014 `placement.affinity` field and in every future M4 placement-engine routing \
10015 axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
10016 selector — both enforce the DNS-1123 label rule on admission; use a \
10017 lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
10018 `\"low-latency\"`, or `\"anti-affinity\"`)"
10019 )]
10020 PlacementAffinityInvalid { affinity: String, reason: String },
10021 #[error(":placement Sharded requires :shard-key")]
10022 ShardedWithoutKey,
10023 #[error(
10024 ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
10025 hashes every entity onto the same shard, defeating sharding entirely)"
10026 )]
10027 ShardedKeyEmpty,
10028 #[error(
10029 ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
10030 entity-id extractor expression: {reason} (the future M4 Akka-style \
10031 cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
10032 as a single-token property reference and hashes the extracted entity ID \
10033 to compute shard placement; use a printable-ASCII extractor expression \
10034 like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
10035 `\"${{tenant}}\"`)"
10036 )]
10037 ShardKeyInvalid { shard_key: String, reason: String },
10038 #[error(
10039 ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
10040 Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
10041 convention); :estrategia Replicated runs every cluster active-active and \
10042 :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
10043 distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
10044 to :estrategia Sharded if hash-keyed routing is the intent"
10045 )]
10046 ShardKeyOnNonSharded {
10047 estrategia: PlacementStrategy,
10048 shard_key: String,
10049 },
10050 #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
10051 ContratoMissingTarget {
10052 de: String,
10053 para: String,
10054 wit: String,
10055 expected: &'static str,
10056 },
10057 #[error(
10058 "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
10059 expected `:{expected}` only"
10060 )]
10061 ContratoWrongTarget {
10062 de: String,
10063 para: String,
10064 wit: String,
10065 expected: &'static str,
10066 },
10067 #[error(
10068 "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
10069 like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
10070 that matches no traffic and silently drops every request)"
10071 )]
10072 ContratoEndpointEmpty { de: String, para: String },
10073 #[error(
10074 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
10075 (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
10076 :entrada :paths)"
10077 )]
10078 ContratoEndpointNotAbsolute {
10079 de: String,
10080 para: String,
10081 endpoint: String,
10082 },
10083 #[error(
10084 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
10085 Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
10086 emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
10087 caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
10088 shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
10089 like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
10090 and whitespace)"
10091 )]
10092 ContratoEndpointInvalid {
10093 de: String,
10094 para: String,
10095 endpoint: String,
10096 reason: String,
10097 },
10098 #[error(
10099 "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
10100 subject is a no-op subscribe; omit :subject only if the WIT world is not \
10101 pub-sub-shaped)"
10102 )]
10103 ContratoSubjectEmpty { de: String, para: String },
10104 #[error(
10105 "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
10106 NATS subject: {reason} (the NATS server's subject parser enforces the \
10107 same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
10108 single-token and `>` multi-token wildcards — at publish/subscribe time; \
10109 use a token-by-token form like `\"checkout.events.charge.failed\"` or \
10110 `\"orders.*.completed\"` — a malformed subject silently drops every \
10111 message at runtime far from the source caixa.lisp)"
10112 )]
10113 ContratoSubjectInvalid {
10114 de: String,
10115 para: String,
10116 subject: String,
10117 reason: String,
10118 },
10119 #[error(
10120 "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
10121 addresses the bucket root, defeating the per-key isolation the slot exists \
10122 for; omit :slot only if the WIT world is not store-shaped)"
10123 )]
10124 ContratoSlotEmpty { de: String, para: String },
10125 #[error(
10126 "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
10127 WASI keyvalue store slot template: {reason} (the substrate enforces \
10128 the printable-ASCII intersection-floor every kv backend admits — \
10129 use a single-token path / template expression like `\"checkout/$orderId\"`, \
10130 `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
10131 percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
10132 slot either gets rejected on write by strict backends or silently \
10133 corrupts the next read on permissive ones, far from the source caixa.lisp)"
10134 )]
10135 ContratoSlotInvalid {
10136 de: String,
10137 para: String,
10138 slot: String,
10139 reason: String,
10140 },
10141 #[error(
10142 "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
10143 or an event-sourced indirection (MESH-COMPOSITION §III.3)",
10144 cycle.join(" → ")
10145 )]
10146 ContratoCycle { cycle: Vec<String> },
10147 #[error(
10148 ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
10149 than once (the typed graph edges are a set, not a multiset; duplicate \
10150 contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
10151 values that K8s admission rejects far from the source caixa.lisp)"
10152 )]
10153 ContratoDuplicate {
10154 de: String,
10155 para: String,
10156 wit: String,
10157 target: String,
10158 },
10159 #[error(
10160 ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
10161 contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
10162 express `no per-call deadline on this axis`"
10163 )]
10164 PolicyTimeoutZero,
10165 #[error(
10166 ":politicas :retries must be > 0 when set; omit :retries to express \
10167 `no retries on transient failure`"
10168 )]
10169 PolicyRetriesZero,
10170 #[error(
10171 ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
10172 (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
10173 retry policy into a thundering-herd amplification vector on transient \
10174 failure (one caller request fans out to `(retries+1)^depth` server-side \
10175 calls across the synchronous-:contratos subgraph), exactly the failure \
10176 mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
10177 Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
10178 or omit :retries to disable retries entirely"
10179 )]
10180 PolicyRetriesExceedsCap { retries: u32 },
10181 #[error(
10182 ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
10183 breaker trips on the first call); omit :circuit-breaker to disable it"
10184 )]
10185 PolicyBreakerZeroFailures,
10186 #[error(
10187 ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
10188 mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
10189 above this cap turns the typed breaker policy into a no-op: the trip \
10190 threshold is structurally so high that no realistic failures-per-:window \
10191 traffic shape can reach it, so the breaker never trips and every typed-slot \
10192 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
10193 Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
10194 structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
10195 Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
10196 omit :circuit-breaker to disable the breaker entirely"
10197 )]
10198 PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
10199 #[error(
10200 ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
10201 tracks no failures); omit :circuit-breaker to disable it"
10202 )]
10203 PolicyBreakerZeroWindow,
10204 #[error(
10205 ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
10206 request); omit :rate-limit to disable rate limiting"
10207 )]
10208 PolicyRateLimitZero,
10209 #[error(
10210 ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
10211 (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
10212 rate-limit policy into a no-op limiter: the token-bucket capacity is \
10213 structurally so high that no realistic per-edge traffic shape can drain it, \
10214 so the limiter never trips and every typed-slot consumer (the future \
10215 CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
10216 local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
10217 that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
10218 Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
10219 Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
10220 Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
10221 to disable rate limiting entirely"
10222 )]
10223 PolicyRateLimitExceedsCap { rate: u32 },
10224 #[error(
10225 ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
10226 the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
10227 rate-limit codec round-trips losslessly; got {window:?} which renders to a \
10228 non-round-trippable form (omit :rate-limit to disable, or pick one of the \
10229 three canonical windows)"
10230 )]
10231 PolicyRateLimitWindowNotCanonical { window: Duration },
10232 #[error(
10233 ":politicas :timeout must be an integer number of milliseconds — the canonical \
10234 authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
10235 duration codec round-trips losslessly; got {timeout:?} which carries a \
10236 sub-millisecond residue that either truncates to a different `Duration` on \
10237 re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
10238 to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
10239 zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
10240 (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
10241 )]
10242 PolicyTimeoutNotCanonical { timeout: Duration },
10243 #[error(
10244 ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
10245 (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
10246 per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
10247 overlays carry a deadline so long no realistic synchronous-:contratos \
10248 traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
10249 CSE invariant degenerates to enforcement only at the per-Servico \
10250 `:limits :wall-clock` layer — far above the per-edge granularity the typed \
10251 `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
10252 (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
10253 ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
10254 maxes out at the same `3600s` ceiling) or omit :timeout to express \
10255 `no per-call deadline on this axis` (the synchronous-call deadline then \
10256 relies entirely on the per-Servico `:limits :wall-clock` axis)"
10257 )]
10258 PolicyTimeoutExceedsCap { timeout: Duration },
10259 #[error(
10260 ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
10261 the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
10262 the shared duration codec round-trips losslessly; got {window:?} which carries a \
10263 sub-millisecond residue that either truncates to a different `Duration` on \
10264 re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
10265 Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
10266 )]
10267 PolicyBreakerWindowNotCanonical { window: Duration },
10268 #[error(
10269 ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
10270 (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
10271 rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
10272 is structurally so long that transient failures are never forgotten, the breaker \
10273 trips once and stays tripped for the lifetime of the component, and every typed-slot \
10274 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
10275 outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
10276 Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
10277 default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
10278 the breaker entirely"
10279 )]
10280 PolicyBreakerWindowExceedsCap { window: Duration },
10281 #[error(
10282 ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
10283 :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
10284 a single timing-out call can be declared failed, so the dominant failure mode \
10285 the breaker exists to catch is structurally never counted: a call dispatched at \
10286 t=0 is only reported failed at t={timeout:?}, by which point the window that was \
10287 open at dispatch has already rolled, and every typed-slot consumer (the future \
10288 CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
10289 outlier_detection.interval paired against the per-route request timeout) emits a \
10290 breaker that cannot trip on timeouts however high the call volume. Pin :window \
10291 at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
10292 timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
10293 same shape), lower :timeout, or omit one of the two axes"
10294 )]
10295 PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
10296 #[error(
10297 ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
10298 :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
10299 :window ({cb_window:?}) — the token-bucket dispatches at most \
10300 `rate × cb_window / rl_window` calls per rolling breaker window, which is \
10301 structurally below the trip threshold, so the breaker cannot trip even under \
10302 100% failure and every typed-slot consumer (the future \
10303 CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
10304 outlier_detection.consecutive_5xx paired against \
10305 local_rate_limit.token_bucket.max_tokens) emits a protection that is \
10306 structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
10307 :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
10308 )]
10309 PolicyBreakerCannotTripUnderRateLimit {
10310 rate: u32,
10311 rl_window: Duration,
10312 max_failures: u32,
10313 cb_window: Duration,
10314 },
10315 #[error(
10316 ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
10317 :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
10318 attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
10319 at or before the last retry, so the breaker opens with declared retries still \
10320 unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
10321 per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
10322 outlier_detection.consecutive_5xx) emits a retry policy the substrate \
10323 structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
10324 Envoy / resilience4j production playbooks recommend the breaker's trip \
10325 threshold be observably larger than any single client's retry budget so the \
10326 breaker distinguishes one persistently-failing client from sustained \
10327 multi-client failure), lower :retries, or omit one of the two axes"
10328 )]
10329 PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
10330 #[error(
10331 ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
10332 ({retries}) plus the initial attempt — one client's declared retry sequence is \
10333 {retries}+1 attempts, each of which consumes one token from the local rate-limit \
10334 bucket, but the bucket admits at most {rate} tokens per refill window, so the \
10335 retry policy is silently truncated by the same rate limiter it feeds through and \
10336 every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
10337 overlay, Envoy's retry_policy.num_retries paired against \
10338 local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
10339 structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
10340 resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
10341 bucket capacity be observably larger than any single client's retry budget so the \
10342 limiter distinguishes one client's declared retries from sustained multi-client \
10343 load), lower :retries, or omit one of the two axes"
10344 )]
10345 PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
10346}
10347
10348// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
10349// ctor `entrada_host_invalid` is folded onto the sibling
10350// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
10351// `{ <field>: String, reason: String }` variants
10352// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
10353// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
10354// `ShardKeyInvalid`), so every variant on the uniform two-slot
10355// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
10356// reads through one substrate-primitive family rather than one macro
10357// closing six sites plus a hand-written seventh ctor closing the
10358// paired site alone. Prior separate-ctor rationale (17dd504) migrates
10359// verbatim to the macro's outer doc block.
10360
10361// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
10362// wit, expected }` wire-up sites at [`WitContract::target`] onto one
10363// substrate-primitive family per typed variant — the paired sibling on
10364// [`AplicacaoError`] of the four `LayoutError` constructor families
10365// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
10366// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
10367// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
10368// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
10369// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
10370// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
10371// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
10372// HTTP with subject/slot, PubSub with endpoint/slot, Store with
10373// endpoint/subject, Capability with any payload; three
10374// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
10375// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
10376// opened the identical six-line
10377// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
10378// WitTarget::<label> }` struct-literal against the local `edge()` closure
10379// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
10380// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
10381// on the same altitude the peer four `LayoutError` constructor families
10382// each closed on their sibling envelopes.
10383//
10384// The macro below generates one `#[must_use]` inherent constructor per
10385// variant of shape `fn <ctor>(edge: (String, String, String), expected:
10386// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
10387// dispatch per arm: `return
10388// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
10389// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
10390// the pre-lift struct-literal on the same edge fixture. The uniform four-
10391// field construction (`de, para, wit` triple-destructure onto same-named
10392// fields + `expected` verbatim) is spelled once — inside the macro —
10393// rather than at every wire-up site. `#[must_use]` fires a compile warning
10394// at any wire-up that mistakenly discards the constructed error.
10395//
10396// Every future consumer that wants to construct one of these two variants
10397// outside [`WitContract::target`] (a deferred
10398// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
10399// admission validator raising wrong-target / missing-target diagnostics
10400// on unrecognized shapes, a future `feira validate --contratos` per-caixa
10401// admission verb, a per-`WitContract` payload-axis pre-emitter probing
10402// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
10403// slots) reaches the variant through one call rather than re-inlining the
10404// six-line struct-literal block in lockstep with the seven in-crate
10405// wire-up sites.
10406macro_rules! contrato_target_ctors {
10407 ($($ctor:ident => $variant:ident),* $(,)?) => {
10408 impl AplicacaoError {
10409 $(
10410 #[doc = concat!(
10411 "Construct an [`AplicacaoError::",
10412 stringify!($variant),
10413 "`] naming the offending edge `(de, para, wit)` triple ",
10414 "under the given `expected` payload-field-name label. ",
10415 "Folds the uniform `{ de, para, wit, expected }` four-",
10416 "slot struct-literal onto one substrate primitive so ",
10417 "every [`WitContract::target`] wire-up on this variant ",
10418 "reads through one dispatch rather than the pre-lift ",
10419 "six-line open-coded block. The `edge` triple threads ",
10420 "verbatim from [`WitContract::edge_triple`] via the ",
10421 "local `edge()` closure at the call site."
10422 )]
10423 #[must_use]
10424 pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
10425 let (de, para, wit) = edge;
10426 Self::$variant { de, para, wit, expected }
10427 }
10428 )*
10429 }
10430 };
10431}
10432
10433contrato_target_ctors! {
10434 contrato_wrong_target => ContratoWrongTarget,
10435 contrato_missing_target => ContratoMissingTarget,
10436}
10437
10438// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
10439// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
10440// onto one substrate-primitive family per typed variant — the paired
10441// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
10442// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
10443// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
10444// `ContratoMissingTarget`) and of the two-slot
10445// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
10446// on the sibling per-`:entrada :host` envelope. Every one of the four
10447// wire-up sites — three under [`WitContract::target`] (the empty
10448// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
10449// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
10450// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
10451// value-shape gate fires ahead of) — opened the identical two-line
10452// `let (de, para) = <contract>.edge_pair(); return Err(
10453// AplicacaoError::<Variant> { de, para });` block against the local
10454// [`WitContract::edge_pair`] composite-projection accessor, the exact
10455// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
10456// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
10457// and [`AplicacaoError::entrada_host_invalid`] each closed on their
10458// sibling envelopes.
10459//
10460// The macro below generates one `#[must_use]` inherent constructor per
10461// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
10462// collapsing the four sites onto one dispatch per arm:
10463// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
10464// equal to the pre-lift struct-literal on the same edge pair. The
10465// uniform two-field construction (`de, para` pair-destructure onto
10466// same-named fields) is spelled once — inside the macro — rather than
10467// at every wire-up site. `#[must_use]` fires a compile warning at any
10468// wire-up that mistakenly discards the constructed error.
10469//
10470// Every future consumer that wants to construct one of these four
10471// variants outside the two in-crate wire-up sites (a deferred
10472// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
10473// admission validator raising empty-payload / empty-`:wit` diagnostics,
10474// a future `feira validate --contratos` per-caixa admission verb, an
10475// M4 typed WIT-registry-driven per-arm pre-emitter probing the
10476// [`WitContract`] payload slot against a canonical per-arm requirement
10477// table) reaches the variant through one call rather than re-inlining
10478// the two-line pair-destructure block in lockstep with the four
10479// in-crate wire-up sites.
10480macro_rules! contrato_empty_pair_ctors {
10481 ($($ctor:ident => $variant:ident),* $(,)?) => {
10482 impl AplicacaoError {
10483 $(
10484 #[doc = concat!(
10485 "Construct an [`AplicacaoError::",
10486 stringify!($variant),
10487 "`] naming the offending edge `(de, para)` pair. ",
10488 "Folds the uniform `{ de, para }` two-slot struct-",
10489 "literal onto one substrate primitive so every ",
10490 "wire-up on this variant reads through one dispatch ",
10491 "rather than the pre-lift two-line open-coded ",
10492 "`let (de, para) = <contract>.edge_pair(); return ",
10493 "Err(<Variant> { de, para });` block. The `edge` ",
10494 "pair threads verbatim from [`WitContract::edge_pair`] ",
10495 "at the call site."
10496 )]
10497 #[must_use]
10498 pub fn $ctor(edge: (String, String)) -> Self {
10499 let (de, para) = edge;
10500 Self::$variant { de, para }
10501 }
10502 )*
10503 }
10504 };
10505}
10506
10507contrato_empty_pair_ctors! {
10508 empty_wit => EmptyWit,
10509 contrato_endpoint_empty => ContratoEndpointEmpty,
10510 contrato_subject_empty => ContratoSubjectEmpty,
10511 contrato_slot_empty => ContratoSlotEmpty,
10512}
10513
10514// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
10515// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
10516// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
10517// onto one substrate primitive on [`AplicacaoError`] — sibling on the
10518// `{ de: String, para: String, <field>: String }` three-slot envelope of
10519// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
10520// variants on the paired `{ de, para }` two-slot envelope carrying the
10521// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
10522// { de, para });` pair-destructure prelude), the peer four-slot
10523// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
10524// the paired `{ de, para, <field>: String, reason: String }` envelope
10525// carrying the parser-shaped `reason` trailer), and the peer four-slot
10526// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
10527// `{ de, para, wit, expected: &'static str }` envelope carrying the
10528// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
10529// variant is the sole occupant of the three-slot `{ de, para, <field>:
10530// String }` shape on [`AplicacaoError`] (no sibling
10531// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
10532// and `:slot` axes carry no "must start with /" invariant, since the
10533// NATS subject grammar and the WASI keyvalue slot template grammar don't
10534// share the Gateway-API-HTTPPathMatch leading-slash prelude the
10535// `:endpoint` axis does), so a full macro isn't warranted; a single
10536// `#[must_use]` inherent ctor matching the ambient
10537// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
10538// peer per-`:contratos` ctor families each carry closes the last
10539// open-coded three-slot struct-literal on the envelope, matching the
10540// same standalone-ctor discipline the sibling
10541// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
10542// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
10543// [`crate::SupervisorError::child_caixa_invalid`] /
10544// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
10545// `{ caixa: String, [versao: String,] reason: String }` two- and three-
10546// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
10547// one variant on the `{ host: String, reason: String }` two-slot
10548// envelope) apply on their sibling one-off variants.
10549//
10550// The one wire-up site on this variant — [`WitContract::target`]'s
10551// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
10552// six per-`:contratos` value-shape gates inside the same method body,
10553// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
10554// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
10555// `ContratoWitInvalid`) each already reach through one of the three
10556// peer macro-generated ctor families above — opened the same five-line
10557// `let (de, para) = self.edge_pair(); return
10558// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
10559// ep.to_string() });` struct-literal against the local
10560// [`WitContract::edge_pair`] composite-projection accessor and the
10561// caller-side `&str` endpoint — the exact "same block re-inlined at
10562// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
10563// altitude the six peer `AplicacaoError` constructor families each
10564// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
10565// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
10566// becomes a caixa-build error, not a Cilium L7 policy-side path-match
10567// silent traffic drop far from the source caixa.lisp) now routes through
10568// one substrate primitive on the envelope.
10569//
10570// The ctor below folds the site onto one dispatch:
10571// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
10572// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
10573// on the same `(edge_pair, endpoint)` pair. The uniform three-field
10574// construction (`de, para` pair-destructure onto same-named fields +
10575// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
10576// body — rather than at the wire-up site. `#[must_use]` fires a compile
10577// warning at any future wire-up that mistakenly discards the constructed
10578// error.
10579//
10580// Every future consumer that wants to construct this variant outside
10581// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
10582// CR materializer's per-`:contratos` admission validator raising the
10583// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
10584// `feira validate --contratos` per-caixa admission verb re-running the
10585// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
10586// probing each declared `:endpoint` against the same shared
10587// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
10588// resolver rejecting a leading-slash-missing `:endpoint` against a
10589// cluster-local Cilium snapshot the M4 CR materializer projects) now
10590// reaches this variant through one call rather than re-inlining the
10591// five-line pair-destructure + struct-literal block in lockstep with
10592// the sole in-crate wire-up site.
10593impl AplicacaoError {
10594 /// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
10595 /// naming the offending edge `(de, para)` pair and the per-payload
10596 /// `endpoint` value. Folds the uniform `{ de, para, endpoint:
10597 /// endpoint.to_string() }` three-slot struct-literal onto one
10598 /// substrate primitive so every wire-up on this variant reads
10599 /// through one dispatch rather than the pre-lift five-line
10600 /// pair-destructure + struct-literal block. The `edge` pair threads
10601 /// verbatim from [`WitContract::edge_pair`] at the call site,
10602 /// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
10603 /// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
10604 /// paired two-slot and four-slot per-`:contratos :endpoint`
10605 /// envelopes on the same [`AplicacaoError`] type.
10606 #[must_use]
10607 pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
10608 let (de, para) = edge;
10609 Self::ContratoEndpointNotAbsolute {
10610 de,
10611 para,
10612 endpoint: endpoint.to_string(),
10613 }
10614 }
10615
10616 /// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
10617 /// offending self-edge's owning `caixa` and its `:wit` world
10618 /// reference, projecting both slots through the [`WitContract`]'s
10619 /// own [`WitContract::source`] and [`WitContract::world_ref`]
10620 /// scalar accessors on the substrate primitive.
10621 ///
10622 /// Folds the uniform `{ caixa: contract.source().to_string(), wit:
10623 /// contract.world_ref().to_string() }` two-slot struct-literal onto
10624 /// one substrate primitive so every wire-up on this variant reads
10625 /// through one dispatch rather than the pre-lift four-line
10626 /// twin-`.to_string()` struct-literal block. The `contract` borrow
10627 /// threads verbatim from the caller-side `for c in
10628 /// self.contratos()` iteration at the sole in-crate wire-up site
10629 /// [`AplicacaoSpec::validate_contratos`], matching the sibling
10630 /// per-`:contratos` `WitContract`-projection ctor discipline the
10631 /// peer [`AplicacaoError::empty_wit`] /
10632 /// [`AplicacaoError::contrato_endpoint_empty`] /
10633 /// [`AplicacaoError::contrato_subject_empty`] /
10634 /// [`AplicacaoError::contrato_slot_empty`] ctors carry through
10635 /// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
10636 /// envelope.
10637 ///
10638 /// The `caixa` slot is projected through [`WitContract::source`]
10639 /// rather than [`WitContract::destination`] to preserve byte-equal
10640 /// diagnostic ordering with the pre-lift open-coded body — a
10641 /// [`WitContract::is_self_loop`]-gated call site has
10642 /// `source() == destination()` by that predicate's own contract, so
10643 /// the two accessors are exchange-symmetric at this call site, but
10644 /// naming `source` at the ctor definition matches the pre-lift
10645 /// site's field selection and pins the discipline for any future
10646 /// consumer that constructs the variant against a not-yet-gated
10647 /// candidate contract (e.g. an M4
10648 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10649 /// webhook re-checking a per-`(:de, :para)` patched contract, a
10650 /// future `feira validate --contratos` per-caixa verb re-running
10651 /// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
10652 /// overlay resolver rejecting a self-edge introduced by a
10653 /// cluster-local `:contratos` override the M4 CR materializer
10654 /// projects).
10655 ///
10656 /// Peer of the sibling `WitContract`-projection ctors on the
10657 /// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
10658 /// same "one typed dispatch on the substrate primitive, projecting
10659 /// through the paired [`WitContract`] accessors, thin projections
10660 /// at each consumer" discipline extended here onto the last unlifted
10661 /// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
10662 /// inside [`AplicacaoSpec::validate_contratos`].
10663 #[must_use]
10664 pub fn contrato_self_loop(contract: &WitContract) -> Self {
10665 Self::ContratoSelfLoop {
10666 caixa: contract.source().to_string(),
10667 wit: contract.world_ref().to_string(),
10668 }
10669 }
10670
10671 /// Construct an [`AplicacaoError::ContratoDuplicate`] naming the
10672 /// offending duplicate edge's `(:de, :para, :wit)` triple and the
10673 /// per-payload `:target` byte-string, projecting the first three slots
10674 /// through the paired [`WitContract::edge_triple`] typed-accessor and
10675 /// the trailing `target:` slot through [`WitTarget::label`] on the
10676 /// substrate primitive.
10677 ///
10678 /// Folds the uniform `let (de, para, wit) = contract.edge_triple();
10679 /// Self::ContratoDuplicate { de, para, wit, target: target.label() }`
10680 /// six-line pair-destructure + struct-literal onto one substrate
10681 /// primitive so every wire-up on this variant reads through one
10682 /// dispatch rather than the pre-lift open-coded block inside the
10683 /// [`AplicacaoSpec::validate_contratos`] whole-edge dedup closure
10684 /// passed to [`crate::render::insert_first_seen`]. Peer of the sibling
10685 /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
10686 /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
10687 /// per-`:contratos` self-edge two-slot envelope) and the sibling
10688 /// [`AplicacaoError::empty_wit`] (projecting through
10689 /// [`WitContract::edge_pair`] on the sibling per-`:contratos` empty-
10690 /// `:wit` two-slot envelope) `WitContract`-projection ctors on the
10691 /// same [`AplicacaoError`] type — extended here onto the last unlifted
10692 /// four-slot `{ de: String, para: String, wit: String, target: String }`
10693 /// per-`:contratos` whole-edge-dedup envelope inside
10694 /// [`AplicacaoSpec::validate_contratos`], closing the paired
10695 /// duplicate-gate diagnostic constructor site the peer
10696 /// [`WitContract::edge_triple`] (5dbcfaf) lift's doc-block flagged as
10697 /// the last unlifted composite-projection wire-up.
10698 ///
10699 /// The `contract` borrow threads verbatim from the caller-side `for c
10700 /// in self.contratos()` iteration at the sole in-crate wire-up site
10701 /// [`AplicacaoSpec::validate_contratos`], and `target` threads
10702 /// verbatim from the paired `let target_view = c.target()?` local
10703 /// materialized upstream of the [`crate::render::insert_first_seen`]
10704 /// dedup dispatch — both project onto their respective substrate-
10705 /// primitive accessors ([`WitContract::edge_triple`] +
10706 /// [`WitTarget::label`]) inside the ctor body, matching the sibling
10707 /// [`AplicacaoError::contrato_self_loop`] `WitContract`-projection
10708 /// posture verbatim on the paired self-edge envelope.
10709 ///
10710 /// Every future consumer that wants to construct this variant outside
10711 /// [`AplicacaoSpec::validate_contratos`] — a deferred
10712 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10713 /// webhook re-checking a per-`(:de, :para, :wit, :target)`-patched
10714 /// candidate against a per-tenant `:contratos` overlay before the
10715 /// whole-edge dedup gate re-fires, a future `feira validate
10716 /// --contratos` per-caixa admission verb re-running the dedup check on
10717 /// demand, an M4 per-cluster contrato-cap resolver rejecting a
10718 /// cross-tenant duplicate-edge collision introduced by a fleet-local
10719 /// overlay the M4 CR materializer projects — now reaches this variant
10720 /// through one call rather than re-inlining the six-line pair-
10721 /// destructure + struct-literal block in lockstep with the existing
10722 /// wire-up.
10723 #[must_use]
10724 pub fn contrato_duplicate(contract: &WitContract, target: &WitTarget<'_>) -> Self {
10725 let (de, para, wit) = contract.edge_triple();
10726 Self::ContratoDuplicate {
10727 de,
10728 para,
10729 wit,
10730 target: target.label(),
10731 }
10732 }
10733
10734 /// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
10735 /// offending `:membros :caixa` and its `:versao` requirement under
10736 /// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
10737 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
10738 /// reason.into() }` three-slot struct-literal onto one substrate
10739 /// primitive so every wire-up on this variant reads through one
10740 /// dispatch, matching the peer
10741 /// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
10742 /// shape verbatim on the sibling `SupervisorError { caixa: String,
10743 /// versao: String, reason: String }` envelope's per-`:children :versao`
10744 /// axis. `reason` accepts both `&str` literals and `format!(…)`
10745 /// outputs through the `impl Into<String>` bound so the sole
10746 /// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
10747 /// requirement-cascade closure (routing the shared
10748 /// [`crate::render::require_valid_versao_requirement`]-delivered
10749 /// `reason` verbatim) picks the ctor up without a per-arm wrapper
10750 /// transformation on the caller-side `reason` axis. The
10751 /// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
10752 /// routing the sole wire-up already threads through remains verbatim
10753 /// — the ctor's two `&str` parameters accept the two accessors'
10754 /// returns as-is with no re-allocation at the call site.
10755 #[must_use]
10756 pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
10757 Self::MembroVersaoInvalid {
10758 caixa: caixa.to_string(),
10759 versao: versao.to_string(),
10760 reason: reason.into(),
10761 }
10762 }
10763
10764 /// Construct an [`AplicacaoError::PlacementClusterDuplicate`] naming
10765 /// the offending `:placement :clusters` entry.
10766 ///
10767 /// Folds the uniform `Self::PlacementClusterDuplicate { cluster:
10768 /// cluster.to_string() }` one-field struct-literal onto one substrate
10769 /// primitive so every wire-up on this variant reads through one
10770 /// dispatch rather than the pre-lift three-line open-coded
10771 /// struct-literal block. The `cluster` slot threads verbatim from the
10772 /// caller-side `for c in p.clusters()` iteration at the sole in-crate
10773 /// wire-up site [`AplicacaoSpec::validate_placement_shape`], via the
10774 /// per-entry dedup closure passed to
10775 /// [`crate::render::insert_first_seen`] whose `FnOnce`-shaped ctor
10776 /// bracket accepts the free function pointer as-is.
10777 ///
10778 /// Sibling of the per-`:membros :caixa` / per-`:entrada :paths` /
10779 /// per-`:politicas <scalar>` single-slot ctor families
10780 /// ([`aplicacao_caixa_only_ctors!`] on `{ caixa: String }` at the
10781 /// peer per-membership envelope, [`aplicacao_path_only_ctors!`] on
10782 /// `{ path: String }` at the peer per-gateway envelope,
10783 /// [`aplicacao_policy_scalar_ctors!`] on `{ <field>: Copy-scalar }`
10784 /// at the peer per-`:politicas` cap-scalar envelope) on the same
10785 /// [`AplicacaoError`] type — extends the "one typed dispatch per
10786 /// substrate primitive on every single-slot per-M3-slot envelope"
10787 /// discipline onto the last unlifted `{ cluster: String }` one-slot
10788 /// per-`:placement :clusters` dedup-envelope inside
10789 /// [`AplicacaoSpec::validate_placement_shape`].
10790 ///
10791 /// Every future consumer that wants to construct this variant outside
10792 /// [`AplicacaoSpec::validate_placement_shape`] — a deferred
10793 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10794 /// webhook re-checking a `:placement :clusters` overlay against a
10795 /// per-tenant cluster-topology snapshot, a future `feira validate
10796 /// --placement` per-caixa admission verb re-running the dedup check
10797 /// on demand, an M4 per-cluster placement resolver rejecting a
10798 /// duplicate cluster-name entry introduced by a fleet-local overlay
10799 /// the M4 CR materializer projects — now reaches this variant through
10800 /// one call rather than re-inlining the three-line struct-literal.
10801 #[must_use]
10802 pub fn placement_cluster_duplicate(cluster: &str) -> Self {
10803 Self::PlacementClusterDuplicate {
10804 cluster: cluster.to_string(),
10805 }
10806 }
10807
10808 /// Construct an [`AplicacaoError::PlacementWithoutClusters`] naming
10809 /// the offending `:placement :estrategia` scalar the empty `:clusters`
10810 /// list was declared against, projecting through the paired
10811 /// [`Placement::estrategia`] `Copy`-scalar accessor on the substrate
10812 /// primitive.
10813 ///
10814 /// Folds the uniform `Self::PlacementWithoutClusters { estrategia:
10815 /// placement.estrategia() }` one-field struct-literal onto one
10816 /// substrate primitive so every wire-up on this variant reads through
10817 /// one dispatch rather than the pre-lift three-line open-coded
10818 /// `AplicacaoError::PlacementWithoutClusters { estrategia:
10819 /// p.estrategia() }` block inside
10820 /// [`AplicacaoSpec::validate_placement`]. Same substrate-primitive-
10821 /// projection posture as the sibling
10822 /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
10823 /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
10824 /// per-`:contratos` self-edge envelope) and the peer
10825 /// [`crate::UpgradeError::duplicate_from`] (7e52aec, projecting through
10826 /// [`crate::UpgradeFromEntry::prior_versao`] on the sibling
10827 /// per-`:upgrade-from :from` envelope) ctors — extended here onto the
10828 /// last unlifted `{ estrategia: PlacementStrategy }` one-slot
10829 /// per-`:placement` empty-clusters envelope inside
10830 /// [`AplicacaoSpec::validate_placement`].
10831 ///
10832 /// `#[must_use]` and `const fn` alike: the ctor threads the paired
10833 /// [`Placement::estrategia`] `Copy`-scalar return through one
10834 /// zero-runtime-work construction — no allocation, no owned-string
10835 /// materialization — so the pre-lift `Copy`-pass-through property the
10836 /// open-coded `p.estrategia()` field expression carried survives
10837 /// verbatim through the substrate primitive. The sibling
10838 /// [`AplicacaoError::placement_cluster_duplicate`] (92b1c92) ctor
10839 /// carries the paired `.to_string()`-owned-String allocation on the
10840 /// `{ cluster: String }` envelope; this ctor's `Copy`-scalar envelope
10841 /// preserves the zero-alloc posture at the substrate-primitive
10842 /// dispatch, matching the peer
10843 /// [`aplicacao_policy_scalar_ctors!`] (7ef425e, eight variants on
10844 /// `{ <scalar>: Copy }`) family's `const fn` posture on the sibling
10845 /// per-`:politicas` cap-scalar envelopes.
10846 ///
10847 /// Every future consumer that wants to construct this variant outside
10848 /// [`AplicacaoSpec::validate_placement`] — a deferred
10849 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10850 /// webhook re-checking a `:placement :clusters` overlay against a
10851 /// per-tenant cluster-topology snapshot when the overlay resolves to
10852 /// an empty list, a future `feira validate --placement` per-caixa
10853 /// admission verb re-running the empty-clusters check on demand, an
10854 /// M4 per-cluster placement resolver rejecting an empty cluster pool
10855 /// after a fleet-local overlay strips every declared cluster — now
10856 /// reaches this variant through one call rather than re-inlining the
10857 /// three-line struct-literal in lockstep with the one in-crate
10858 /// wire-up site.
10859 #[must_use]
10860 pub const fn placement_without_clusters(placement: &Placement) -> Self {
10861 Self::PlacementWithoutClusters {
10862 estrategia: placement.estrategia(),
10863 }
10864 }
10865
10866 /// Construct an [`AplicacaoError::ShardKeyOnNonSharded`] naming the
10867 /// offending `:placement :estrategia` scalar and the declared-but-
10868 /// inert `:shard-key` value the non-`Sharded` arm refused, projecting
10869 /// the strategy through the paired [`Placement::estrategia`]
10870 /// `Copy`-scalar accessor on the substrate primitive.
10871 ///
10872 /// Folds the uniform `Self::ShardKeyOnNonSharded { estrategia:
10873 /// placement.estrategia(), shard_key: shard_key.to_string() }`
10874 /// two-slot struct-literal onto one substrate primitive so every
10875 /// wire-up on this variant reads through one dispatch rather than
10876 /// the pre-lift four-line open-coded struct-literal block inside
10877 /// [`AplicacaoSpec::validate_placement`]'s
10878 /// `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
10879 /// arm. Same substrate-primitive-projection posture as the sibling
10880 /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
10881 /// projecting through [`Placement::estrategia`] on the peer
10882 /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
10883 /// empty-clusters envelope) and the peer
10884 /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
10885 /// through [`WitContract::source`] / [`WitContract::world_ref`] on
10886 /// the paired per-`:contratos` self-edge envelope) ctors — extended
10887 /// here onto the last unlifted `{ estrategia: PlacementStrategy,
10888 /// shard_key: String }` two-slot per-`:placement :shard-key`
10889 /// declared-but-inert envelope on the sibling non-`Sharded`-arm
10890 /// partition.
10891 ///
10892 /// The `shard_key: &str` parameter accepts both the `Some(k)`-bound
10893 /// `&str` from the sole in-crate wire-up site (narrowed from
10894 /// `Option<&str>` via [`Placement::shard_key`]) and any future
10895 /// `&String` deref from a downstream consumer that reaches for the
10896 /// slot through the paired accessor, materializing the owned
10897 /// [`String`] via one `.to_string()` at the substrate primitive so
10898 /// no per-arm `.to_string()` allocation lives at the caller. The
10899 /// `estrategia` slot threads through [`Placement::estrategia`]'s
10900 /// `Copy`-scalar return rather than accepting a bare
10901 /// [`PlacementStrategy`] argument, matching the peer
10902 /// [`AplicacaoError::placement_without_clusters`] discipline —
10903 /// carrying the [`Placement`] borrow through one accessor call at
10904 /// the substrate primitive is strictly stronger than accepting the
10905 /// scalar as a separate argument (a future caller that constructs
10906 /// the error against a candidate [`Placement`] whose
10907 /// [`Placement::estrategia`] value the caller re-derives from
10908 /// another source can silently disagree with the storage the
10909 /// [`Placement`] carries; the accessor-projected primitive cannot).
10910 ///
10911 /// Peer of the sibling per-`:placement` single-slot / two-slot ctor
10912 /// families on the same [`AplicacaoError`] type — same "one typed
10913 /// dispatch on the substrate primitive, projecting through the
10914 /// paired [`Placement`] accessors, thin projections at each
10915 /// consumer" discipline extended here onto the last unlifted
10916 /// per-`:placement :shard-key` non-`Sharded`-arm envelope inside
10917 /// [`AplicacaoSpec::validate_placement`].
10918 ///
10919 /// Every future consumer that wants to construct this variant
10920 /// outside [`AplicacaoSpec::validate_placement`] — a deferred
10921 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10922 /// webhook re-checking a `:placement (:estrategia Replicated
10923 /// :shard-key …)` overlay against a per-tenant cluster-topology
10924 /// snapshot, a future `feira validate --placement` per-caixa
10925 /// admission verb re-running the non-`Sharded`-arm refusal on
10926 /// demand, an M4 per-cluster placement resolver rejecting a
10927 /// declared-but-inert `:shard-key` introduced by a fleet-local
10928 /// overlay the M4 CR materializer projects — now reaches this
10929 /// variant through one call rather than re-inlining the four-line
10930 /// struct-literal in lockstep with the one in-crate wire-up site.
10931 #[must_use]
10932 pub fn shard_key_on_non_sharded(placement: &Placement, shard_key: &str) -> Self {
10933 Self::ShardKeyOnNonSharded {
10934 estrategia: placement.estrategia(),
10935 shard_key: shard_key.to_string(),
10936 }
10937 }
10938
10939 /// Construct an [`AplicacaoError::EntradaMemberMissing`] naming the
10940 /// offending `:entrada :para` value the membership lookup against the
10941 /// [`AplicacaoSpec::membro_names`] oracle refused, projecting the
10942 /// slot through the paired [`Entrada::destination`] byte-string
10943 /// accessor on the substrate primitive.
10944 ///
10945 /// Folds the uniform `Self::EntradaMemberMissing { para:
10946 /// entrada.destination().to_string() }` one-field struct-literal onto
10947 /// one substrate primitive so every wire-up on this variant reads
10948 /// through one dispatch rather than the pre-lift three-line
10949 /// open-coded `AplicacaoError::EntradaMemberMissing { para:
10950 /// e.destination().to_string() }` block inside
10951 /// [`AplicacaoSpec::validate_entrada`]. Same substrate-primitive-
10952 /// projection posture as the sibling
10953 /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
10954 /// projecting through [`Placement::estrategia`] on the peer
10955 /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
10956 /// empty-clusters envelope) and the sibling
10957 /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
10958 /// through [`WitContract::source`] / [`WitContract::world_ref`] on
10959 /// the paired per-`:contratos` self-edge envelope) ctors — extended
10960 /// here onto the last unlifted `{ para: String }` one-slot
10961 /// per-`:entrada :para` phantom-reference envelope on the sibling
10962 /// per-`:entrada` slot.
10963 ///
10964 /// The `entrada: &Entrada` parameter threads verbatim from the
10965 /// caller-side `if let Some(e) = self.entrada() { … }` traversal at
10966 /// the sole in-crate wire-up site
10967 /// [`AplicacaoSpec::validate_entrada`], matching the sibling
10968 /// per-`:entrada` byte-string reads that already route through
10969 /// [`Entrada::destination`] one accessor call earlier in the same
10970 /// gate (`validate_entrada_para(e.destination())?;` +
10971 /// `if !names.contains(e.destination()) …`). Carrying the [`Entrada`]
10972 /// borrow through one accessor call at the substrate primitive is
10973 /// strictly stronger than accepting the bare `&str` as a separate
10974 /// argument — a future consumer that constructs the error against a
10975 /// candidate [`Entrada`] whose [`Entrada::destination`] value the
10976 /// caller re-derives from another source (a raw `e.para` field
10977 /// access that skipped the accessor, a stale snapshot of the
10978 /// pre-normalization storage) can silently disagree with the
10979 /// storage the [`Entrada`] carries; the accessor-projected primitive
10980 /// cannot. Matches the peer
10981 /// [`AplicacaoError::placement_without_clusters`] and
10982 /// [`AplicacaoError::shard_key_on_non_sharded`]
10983 /// [`Placement`]-borrow-projection discipline on the sibling
10984 /// per-`:placement` envelope, and matches the peer
10985 /// [`AplicacaoError::contrato_self_loop`] and
10986 /// [`AplicacaoError::contrato_endpoint_not_absolute`]
10987 /// [`WitContract`]-borrow-projection discipline on the sibling
10988 /// per-`:contratos` envelope.
10989 ///
10990 /// Every future consumer that wants to construct this variant
10991 /// outside [`AplicacaoSpec::validate_entrada`] — a deferred
10992 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10993 /// webhook re-checking a `:entrada :para` overlay against a
10994 /// per-tenant `:membros` snapshot after a fleet-local overlay
10995 /// renames a member, a future `feira validate --entrada` per-caixa
10996 /// admission verb re-running the phantom-reference lookup on
10997 /// demand, an M4 per-cluster Gateway API pre-emitter rejecting a
10998 /// `:entrada :para` whose target Servico was stripped from the
10999 /// cluster-local `:membros` overlay, a future authoring-surface
11000 /// widening the field into a `(String, Vec<Suggestion>)` pair
11001 /// carrying a "did-you-mean-<nearest-member>" hint — now reaches
11002 /// this variant through one call rather than re-inlining the
11003 /// three-line struct-literal in lockstep with the one in-crate
11004 /// wire-up site.
11005 #[must_use]
11006 pub fn entrada_member_missing(entrada: &Entrada) -> Self {
11007 Self::EntradaMemberMissing {
11008 para: entrada.destination().to_string(),
11009 }
11010 }
11011
11012 /// Construct an [`AplicacaoError::ContratoCycle`] naming the
11013 /// synchronous-`:contratos` cycle path the DFS-with-three-coloring
11014 /// sync-only-subgraph gate at
11015 /// [`AplicacaoSpec::detect_sync_cycles`] reconstructed from the
11016 /// gray-arm's back-edge target through the parent chain, folding the
11017 /// uniform `Self::ContratoCycle { cycle }` one-field struct-literal
11018 /// onto one substrate primitive so every wire-up on this variant
11019 /// reads through one dispatch rather than the pre-lift open-coded
11020 /// `AplicacaoError::ContratoCycle { cycle }` block at the sole
11021 /// in-crate wire-up site inside
11022 /// [`AplicacaoSpec::detect_sync_cycles`]'s gray-arm cycle-close
11023 /// return. Same substrate-primitive-projection posture as the
11024 /// sibling [`AplicacaoError::entrada_member_missing`] (deeae5c,
11025 /// projecting through [`Entrada::destination`] on the peer `{ para:
11026 /// String }` one-slot per-`:entrada :para` phantom-reference
11027 /// envelope) and [`AplicacaoError::placement_without_clusters`]
11028 /// (b0d24ba, projecting through [`Placement::estrategia`] on the
11029 /// sibling `{ estrategia: PlacementStrategy }` one-slot
11030 /// per-`:placement` empty-clusters envelope) ctors — extended here
11031 /// onto the last unlifted `{ cycle: Vec<String> }` one-slot
11032 /// per-`:contratos` cross-edge sync-cycle envelope on the same
11033 /// [`AplicacaoError`] type. Closes the last unlifted `AplicacaoError`
11034 /// struct-literal wire-up under
11035 /// [`AplicacaoSpec::detect_sync_cycles`].
11036 ///
11037 /// The `cycle: Vec<String>` parameter threads verbatim from the
11038 /// caller-side DFS traversal's reconstructed cycle path (built up by
11039 /// walking `parent` from the gray-back-edge's source node back to
11040 /// its target, reversing, then appending the target once more so the
11041 /// first and last elements coincide by construction and the
11042 /// `Display` rendering under the [`AplicacaoError::ContratoCycle`]
11043 /// `cycle.join(" → ")` formatter reads as a closed loop), matching
11044 /// the pre-lift open-coded body's field selection exactly. Taking
11045 /// the owned [`Vec<String>`] rather than a borrowed slice + collect
11046 /// on the ctor side keeps the pre-lift wire-up byte-identical (the
11047 /// caller already owns the reconstructed [`Vec<String>`] at the
11048 /// gray-arm return, so no per-arm re-allocation lands on the ctor
11049 /// path).
11050 ///
11051 /// Peer of the sibling per-`:contratos` single-slot / two-slot ctor
11052 /// families on the same [`AplicacaoError`] type — same "one typed
11053 /// dispatch on the substrate primitive, thin projections at each
11054 /// consumer" discipline extended here onto the last unlifted
11055 /// per-`:contratos` cross-edge cycle envelope inside
11056 /// [`AplicacaoSpec::detect_sync_cycles`].
11057 ///
11058 /// Every future consumer that wants to construct this variant
11059 /// outside [`AplicacaoSpec::detect_sync_cycles`] — a deferred
11060 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11061 /// webhook re-checking a per-tenant `:contratos` overlay's
11062 /// sync-cycle invariant after a fleet-local overlay adds or removes
11063 /// a synchronous edge, a future `feira validate --contratos`
11064 /// per-caixa admission verb re-running the cross-edge cycle detector
11065 /// on demand, the M4 per-edge policy resolver MESH-COMPOSITION §III.2
11066 /// #3 acknowledges (whose per-edge patch mutates one `:contratos`
11067 /// entry and needs to re-probe *just* the cycle invariant against
11068 /// the post-patch adjacency), a future authoring-surface widening
11069 /// the field into a `(Vec<String>, Vec<WitTarget>)` pair carrying
11070 /// the per-hop WIT shape for a richer "break here" hint — now
11071 /// reaches this variant through one call rather than re-inlining the
11072 /// open-coded struct-literal in lockstep with the one in-crate
11073 /// wire-up site.
11074 #[must_use]
11075 pub fn contrato_cycle(cycle: Vec<String>) -> Self {
11076 Self::ContratoCycle { cycle }
11077 }
11078
11079 /// Construct an [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
11080 /// naming the offending `:politicas :circuit-breaker :window` and
11081 /// the paired `:politicas :timeout` scalars under the first-firing
11082 /// cross-axis-violation gate at
11083 /// [`MeshPolicy::first_cross_axis_violation`], projecting the
11084 /// `window` slot through the [`CircuitBreaker::window`] scalar
11085 /// accessor on the substrate primitive.
11086 ///
11087 /// Folds the uniform `{ window: cb.window(), timeout: t }`
11088 /// two-slot `Copy`-`Duration` struct-literal onto one substrate
11089 /// primitive so every wire-up on this variant reads through one
11090 /// dispatch rather than the pre-lift four-line struct-literal
11091 /// block. The `cb` borrow threads verbatim from the caller-side
11092 /// `if let (Some(t), Some(cb)) = (self.timeout(),
11093 /// self.circuit_breaker())` pair-destructure at the sole in-crate
11094 /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
11095 /// window-below-timeout arm; `timeout` threads verbatim from the
11096 /// paired [`MeshPolicy::timeout`] accessor return already
11097 /// destructured out of the same `if let` pair. `const fn`
11098 /// preserves the pre-lift `Copy`-pass-through's zero-runtime-work
11099 /// property verbatim (both fields are [`Duration`], the
11100 /// [`CircuitBreaker::window`] accessor is itself `const fn`, and
11101 /// no `.to_string()` / `.into()` allocation lands on the ctor
11102 /// path).
11103 ///
11104 /// The `window` slot is projected through [`CircuitBreaker::window`]
11105 /// (not spelled out as a bare `Duration` parameter) so a future
11106 /// widening of the `:circuit-breaker :window` axis — a
11107 /// per-`:contratos`-edge `:circuit-breaker :window` override the
11108 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a promotion of
11109 /// the plain [`Duration`] window to a richer per-status-class
11110 /// window tuple once Envoy's `outlier_detection.interval` peers
11111 /// come into scope — reaches the diagnostic through one accessor
11112 /// swap rather than every wire-up in lockstep, matching the peer
11113 /// substrate-primitive-projection posture of
11114 /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
11115 /// through [`WitContract::source`] / [`WitContract::world_ref`] on
11116 /// the sibling `{ caixa: String, wit: String }` two-slot
11117 /// per-`:contratos` self-edge envelope),
11118 /// [`AplicacaoError::entrada_member_missing`] (deeae5c, projecting
11119 /// through [`Entrada::destination`] on the sibling `{ para: String }`
11120 /// one-slot per-`:entrada :para` phantom-reference envelope), and
11121 /// [`AplicacaoError::shard_key_on_non_sharded`] (14bafca, projecting
11122 /// through [`Placement::estrategia`] on the sibling `{ estrategia:
11123 /// PlacementStrategy, shard_key: String }` two-slot per-`:placement`
11124 /// envelope) ctors carry on the sibling `:contratos` / `:entrada`
11125 /// / `:placement` envelopes.
11126 ///
11127 /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
11128 /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
11129 /// `{ <field>: Copy-scalar }` envelopes on the per-axis
11130 /// [`MeshPolicy::validate`] gate — extended here onto the
11131 /// first-firing cross-axis compound variant, whose multi-slot
11132 /// `{ window: Duration, timeout: Duration }` shape does not fit
11133 /// that macro's one-`Copy`-scalar-per-variant arity. The three
11134 /// remaining cross-axis variants
11135 /// ([`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] on
11136 /// the four-slot `{ rate, rl_window, max_failures, cb_window }`
11137 /// envelope, [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
11138 /// on the two-slot `{ retries, max_failures }` envelope, and
11139 /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
11140 /// two-slot `{ retries, rate }` envelope) each carry a distinct
11141 /// substrate-primitive-projection shape and are folded on their
11142 /// own axis by their own per-variant ctors as those wire-ups are
11143 /// lifted.
11144 ///
11145 /// Every future consumer that wants to construct this variant
11146 /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
11147 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11148 /// webhook re-checking a per-tenant `:politicas` overlay's
11149 /// window-vs-timeout cross-axis invariant after a cluster-local
11150 /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
11151 /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
11152 /// future per-`:contratos`-edge `:politicas` override the M4 CR
11153 /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
11154 /// projecting a per-tenant per-axis ceiling into the same
11155 /// diagnostic shape — now reaches this variant through one call
11156 /// rather than re-inlining the open-coded struct-literal in
11157 /// lockstep with the one in-crate wire-up site.
11158 #[must_use]
11159 pub const fn policy_breaker_window_below_timeout(
11160 cb: &CircuitBreaker,
11161 timeout: Duration,
11162 ) -> Self {
11163 Self::PolicyBreakerWindowBelowTimeout {
11164 window: cb.window(),
11165 timeout,
11166 }
11167 }
11168
11169 /// Construct an [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
11170 /// naming the `(:politicas :rate-limit, :politicas :circuit-breaker)`
11171 /// cross-axis pair whose token-bucket window structurally starves the
11172 /// breaker so `:max-failures` cannot be reached inside `:circuit-breaker
11173 /// :window`.
11174 ///
11175 /// Folds the uniform `{ rate: rl.rate(), rl_window: rl.window(),
11176 /// max_failures: cb.max_failures(), cb_window: cb.window() }`
11177 /// four-slot `Copy`-`(u32 | Duration)` struct-literal onto one substrate
11178 /// primitive so every wire-up on this variant reads through one dispatch
11179 /// rather than the pre-lift six-line struct-literal block. Both `rl` and
11180 /// `cb` borrows thread verbatim from the caller-side `if let (Some(rl),
11181 /// Some(cb)) = (self.rate_limit(), self.circuit_breaker())`
11182 /// pair-destructure at the sole in-crate wire-up site inside
11183 /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-limit
11184 /// arm. `const fn` preserves the pre-lift `Copy`-pass-through's
11185 /// zero-runtime-work property verbatim (all four fields are `u32` /
11186 /// [`Duration`], every projected accessor is itself `const fn`, and no
11187 /// `.to_string()` / `.into()` allocation lands on the ctor path).
11188 ///
11189 /// Every slot is projected through its paired substrate-primitive
11190 /// accessor ([`RateLimit::rate`], [`RateLimit::window`],
11191 /// [`CircuitBreaker::max_failures`], [`CircuitBreaker::window`]) rather
11192 /// than spelled out as bare `u32` / [`Duration`] parameters so a future
11193 /// widening of either axis — a per-`:contratos`-edge `:rate-limit` or
11194 /// `:circuit-breaker` override the MESH-COMPOSITION §III.2 #3 roadmap
11195 /// acknowledges, a promotion of the plain scalar rate to a richer
11196 /// per-status-class token bucket once Envoy's per-descriptor
11197 /// `local_rate_limit` peers come into scope — reaches the diagnostic
11198 /// through one accessor swap rather than every wire-up in lockstep.
11199 /// Matches the peer substrate-primitive-projection posture of
11200 /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
11201 /// projecting through [`CircuitBreaker::window`] on the sibling
11202 /// two-slot `{ window, timeout }` cross-axis
11203 /// `(:timeout, :circuit-breaker)` envelope) on the sibling
11204 /// first-firing cross-axis compound variant.
11205 ///
11206 /// Second cross-axis Policy* variant folded onto its own per-variant
11207 /// substrate primitive — extending the peer
11208 /// [`AplicacaoError::policy_breaker_window_below_timeout`] discipline
11209 /// onto the second-firing cross-axis compound variant, whose four-slot
11210 /// `{ rate, rl_window, max_failures, cb_window }` shape does not fit
11211 /// the sibling two-slot ctor's arity. The two remaining cross-axis
11212 /// variants ([`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
11213 /// on the two-slot `{ retries, max_failures }` envelope and
11214 /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
11215 /// two-slot `{ retries, rate }` envelope) each carry a distinct
11216 /// substrate-primitive-projection shape and are folded on their own
11217 /// axis by their own per-variant ctors as those wire-ups are lifted.
11218 ///
11219 /// Every future consumer that wants to construct this variant outside
11220 /// [`MeshPolicy::first_cross_axis_violation`] — a deferred
11221 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11222 /// webhook re-checking a per-tenant `:politicas` overlay's
11223 /// starve-under-rate-limit cross-axis invariant after a cluster-local
11224 /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
11225 /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
11226 /// future per-`:contratos`-edge `:politicas` override the M4 CR
11227 /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
11228 /// projecting a per-tenant per-axis ceiling into the same diagnostic
11229 /// shape — now reaches this variant through one call rather than
11230 /// re-inlining the open-coded struct-literal in lockstep with the one
11231 /// in-crate wire-up site.
11232 #[must_use]
11233 pub const fn policy_breaker_cannot_trip_under_rate_limit(
11234 rl: &RateLimit,
11235 cb: &CircuitBreaker,
11236 ) -> Self {
11237 Self::PolicyBreakerCannotTripUnderRateLimit {
11238 rate: rl.rate(),
11239 rl_window: rl.window(),
11240 max_failures: cb.max_failures(),
11241 cb_window: cb.window(),
11242 }
11243 }
11244
11245 /// Construct an
11246 /// [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
11247 /// naming the offending `:politicas :retries` and the paired
11248 /// `:politicas :circuit-breaker :max-failures` scalars under the
11249 /// third-firing cross-axis-violation gate at
11250 /// [`MeshPolicy::first_cross_axis_violation`], projecting the
11251 /// `max_failures` slot through the [`CircuitBreaker::max_failures`]
11252 /// scalar accessor on the substrate primitive.
11253 ///
11254 /// Folds the uniform `{ retries, max_failures: cb.max_failures() }`
11255 /// two-slot `Copy`-`u32` struct-literal onto one substrate
11256 /// primitive so every wire-up on this variant reads through one
11257 /// dispatch rather than the pre-lift four-line struct-literal
11258 /// block. The `cb` borrow threads verbatim from the caller-side
11259 /// `if let (Some(retries), Some(cb)) = (self.retries(),
11260 /// self.circuit_breaker())` pair-destructure at the sole in-crate
11261 /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
11262 /// retries-saturate arm; `retries` threads verbatim from the paired
11263 /// [`MeshPolicy::retries`] accessor return already destructured out
11264 /// of the same `if let` pair. `const fn` preserves the pre-lift
11265 /// `Copy`-pass-through's zero-runtime-work property verbatim (both
11266 /// fields are `u32`, the [`CircuitBreaker::max_failures`] accessor
11267 /// is itself `const fn`, and no `.to_string()` / `.into()`
11268 /// allocation lands on the ctor path).
11269 ///
11270 /// The `max_failures` slot is projected through
11271 /// [`CircuitBreaker::max_failures`] (not spelled out as a bare
11272 /// `u32` parameter) so a future widening of the
11273 /// `:circuit-breaker :max-failures` axis — a
11274 /// per-`:contratos`-edge `:circuit-breaker :max-failures` override
11275 /// the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-tenant
11276 /// `:max-failures` ceiling the M4 per-cluster `:politicas`-cap
11277 /// resolver projects, a promotion of the plain `u32` count to a
11278 /// richer per-status-class trip counter once Envoy's
11279 /// `outlier_detection.consecutive_5xx` peers come into scope —
11280 /// reaches the diagnostic through one accessor swap rather than
11281 /// every wire-up in lockstep, matching the peer
11282 /// substrate-primitive-projection posture of
11283 /// [`AplicacaoError::policy_breaker_window_below_timeout`]
11284 /// (9b30c07, projecting through [`CircuitBreaker::window`] on the
11285 /// sibling two-slot `{ window, timeout }` first cross-axis
11286 /// envelope) and
11287 /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
11288 /// (6bb4e46, projecting through [`RateLimit::rate`] /
11289 /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
11290 /// [`CircuitBreaker::window`] on the sibling four-slot second
11291 /// cross-axis envelope). `retries` remains a bare `u32` parameter,
11292 /// matching the sibling first-arm ctor's bare `timeout: Duration`
11293 /// parameter discipline: [`MeshPolicy::retries`] returns
11294 /// `Option<u32>` and the caller-side `if let` already destructures
11295 /// the inner `u32` out, so the ctor takes the destructured scalar
11296 /// verbatim rather than re-wrapping it into an accessor call.
11297 ///
11298 /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
11299 /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
11300 /// `{ <field>: Copy-scalar }` envelopes on the per-axis
11301 /// [`MeshPolicy::validate`] gate — extended here onto the
11302 /// third-firing cross-axis compound variant, whose multi-slot
11303 /// `{ retries: u32, max_failures: u32 }` shape does not fit that
11304 /// macro's one-`Copy`-scalar-per-variant arity. The one remaining
11305 /// cross-axis variant
11306 /// ([`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
11307 /// two-slot `{ retries, rate }` envelope) carries a distinct
11308 /// substrate-primitive-projection shape (projecting through
11309 /// [`RateLimit::rate`] rather than
11310 /// [`CircuitBreaker::max_failures`]) and is folded on its own axis
11311 /// by its own per-variant ctor as that wire-up is lifted in a
11312 /// follow-up run.
11313 ///
11314 /// Every future consumer that wants to construct this variant
11315 /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
11316 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11317 /// webhook re-checking a per-tenant `:politicas` overlay's
11318 /// retries-vs-max-failures cross-axis invariant after a
11319 /// cluster-local `:politicas` override the MESH-COMPOSITION §III.2
11320 /// #3 roadmap acknowledges resolves an *effective* per-edge
11321 /// [`MeshPolicy`], a future per-`:contratos`-edge `:politicas`
11322 /// override the M4 CR resolver projects, an M4 per-cluster
11323 /// `:politicas`-cap resolver projecting a per-tenant per-axis
11324 /// ceiling into the same diagnostic shape — now reaches this
11325 /// variant through one call rather than re-inlining the open-coded
11326 /// struct-literal in lockstep with the one in-crate wire-up site.
11327 #[must_use]
11328 pub const fn policy_breaker_trips_before_retries_exhausted(
11329 retries: u32,
11330 cb: &CircuitBreaker,
11331 ) -> Self {
11332 Self::PolicyBreakerTripsBeforeRetriesExhausted {
11333 retries,
11334 max_failures: cb.max_failures(),
11335 }
11336 }
11337
11338 /// Construct an
11339 /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] naming
11340 /// the offending `:politicas :retries` and the paired `:politicas
11341 /// :rate-limit` `:rate` scalars under the fourth-firing (and last-
11342 /// remaining) cross-axis-violation gate at
11343 /// [`MeshPolicy::first_cross_axis_violation`], projecting the `rate`
11344 /// slot through the [`RateLimit::rate`] scalar accessor on the
11345 /// substrate primitive.
11346 ///
11347 /// Folds the uniform `{ retries, rate: rl.rate() }` two-slot
11348 /// `Copy`-`u32` struct-literal onto one substrate primitive so every
11349 /// wire-up on this variant reads through one dispatch rather than
11350 /// the pre-lift four-line struct-literal block. The `rl` borrow
11351 /// threads verbatim from the caller-side `if let (Some(retries),
11352 /// Some(rl)) = (self.retries(), self.rate_limit())` pair-destructure
11353 /// at the sole in-crate wire-up site inside
11354 /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
11355 /// limit arm; `retries` threads verbatim from the paired
11356 /// [`MeshPolicy::retries`] accessor return already destructured out
11357 /// of the same `if let` pair. `const fn` preserves the pre-lift
11358 /// `Copy`-pass-through's zero-runtime-work property verbatim (both
11359 /// fields are `u32`, the [`RateLimit::rate`] accessor is itself
11360 /// `const fn`, and no `.to_string()` / `.into()` allocation lands on
11361 /// the ctor path).
11362 ///
11363 /// The `rate` slot is projected through [`RateLimit::rate`] (not
11364 /// spelled out as a bare `u32` parameter) so a future widening of
11365 /// the `:rate-limit` `:rate` axis — a per-`:contratos`-edge
11366 /// `:rate-limit` `:rate` override the MESH-COMPOSITION §III.2 #3
11367 /// roadmap acknowledges, a per-tenant `:rate` ceiling the M4
11368 /// per-cluster `:politicas`-cap resolver projects, a promotion of
11369 /// the plain `u32` token capacity to a richer
11370 /// `{max_tokens, tokens_per_fill}` tuple once Envoy's
11371 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
11372 /// axis comes into scope — reaches the diagnostic through one
11373 /// accessor swap rather than every wire-up in lockstep, matching
11374 /// the peer substrate-primitive-projection posture of
11375 /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
11376 /// projecting through [`CircuitBreaker::window`] on the sibling
11377 /// two-slot `{ window, timeout }` first cross-axis envelope),
11378 /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
11379 /// (6bb4e46, projecting through [`RateLimit::rate`] /
11380 /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
11381 /// [`CircuitBreaker::window`] on the sibling four-slot second
11382 /// cross-axis envelope), and
11383 /// [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
11384 /// (f54c539, projecting through [`CircuitBreaker::max_failures`] on
11385 /// the sibling two-slot `{ retries, max_failures }` third cross-axis
11386 /// envelope). `retries` remains a bare `u32` parameter, matching
11387 /// the sibling third-arm ctor's bare `retries: u32` parameter
11388 /// discipline: [`MeshPolicy::retries`] returns `Option<u32>` and the
11389 /// caller-side `if let` already destructures the inner `u32` out, so
11390 /// the ctor takes the destructured scalar verbatim rather than
11391 /// re-wrapping it into an accessor call.
11392 ///
11393 /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
11394 /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
11395 /// `{ <field>: Copy-scalar }` envelopes on the per-axis
11396 /// [`MeshPolicy::validate`] gate — extended here onto the
11397 /// fourth-firing (and final) cross-axis compound variant, whose
11398 /// multi-slot `{ retries: u32, rate: u32 }` shape does not fit that
11399 /// macro's one-`Copy`-scalar-per-variant arity. After this lift all
11400 /// four cross-axis [`MeshPolicy::first_cross_axis_violation`] arms
11401 /// read through one substrate-primitive ctor dispatch each; the
11402 /// per-envelope compound cross-axis Policy* family closes on this
11403 /// variant.
11404 ///
11405 /// Every future consumer that wants to construct this variant
11406 /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
11407 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
11408 /// webhook re-checking a per-tenant `:politicas` overlay's
11409 /// retries-vs-rate cross-axis invariant after a cluster-local
11410 /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
11411 /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
11412 /// future per-`:contratos`-edge `:politicas` override the M4 CR
11413 /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
11414 /// projecting a per-tenant per-axis ceiling into the same diagnostic
11415 /// shape — now reaches this variant through one call rather than
11416 /// re-inlining the open-coded struct-literal in lockstep with the
11417 /// one in-crate wire-up site.
11418 #[must_use]
11419 pub const fn policy_rate_limit_cannot_admit_retry_burst(retries: u32, rl: &RateLimit) -> Self {
11420 Self::PolicyRateLimitCannotAdmitRetryBurst {
11421 retries,
11422 rate: rl.rate(),
11423 }
11424 }
11425
11426 /// Construct an [`AplicacaoError::ContratoCaixaInvalid`] naming the
11427 /// offending `:contratos <slot>` (`:de` / `:para`) and the value
11428 /// that broke the shared DNS-1123-label floor under the given
11429 /// `reason`. Folds the uniform `Self::ContratoCaixaInvalid { slot,
11430 /// caixa: caixa.to_string(), reason: reason.into() }` three-slot
11431 /// struct-literal onto one substrate primitive so every wire-up on
11432 /// this variant reads through one dispatch rather than the pre-lift
11433 /// six-line struct-literal block inside
11434 /// [`validate_contrato_caixa`]'s
11435 /// [`crate::render::require_valid_dns_1123_label`]
11436 /// `|reason| …` closure.
11437 ///
11438 /// Sibling of the per-axis [`aplicacao_field_reason_ctors!`]
11439 /// (981060b) macro-generated ctor family
11440 /// ([`AplicacaoError::membro_caixa_invalid`],
11441 /// [`AplicacaoError::entrada_para_invalid`],
11442 /// [`AplicacaoError::entrada_host_invalid`],
11443 /// [`AplicacaoError::entrada_path_invalid`],
11444 /// [`AplicacaoError::placement_cluster_invalid`],
11445 /// [`AplicacaoError::placement_affinity_invalid`],
11446 /// [`AplicacaoError::shard_key_invalid`]) — extends the "one typed
11447 /// dispatch per substrate primitive on every `{ <field>: String,
11448 /// reason: String }` per-axis parser-shaped envelope" discipline
11449 /// onto the sole unlifted three-slot `{ slot: &'static str, caixa:
11450 /// String, reason: String }` sibling whose extra `slot: &'static
11451 /// str` axis-tag distinguishes the two-arm `:de` / `:para` cascade
11452 /// on the per-`:contratos`-edge value axis and so does not fit the
11453 /// two-slot macro's arity.
11454 ///
11455 /// `slot` carries the kebab-case `:de` / `:para` tag verbatim
11456 /// (`&'static str` is `Copy`, no allocation), matching the caller-
11457 /// side [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
11458 /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
11459 /// sole in-crate wire-up threads through. `reason: impl
11460 /// Into<String>` accepts both `&str` literals and the shared
11461 /// [`crate::render::require_valid_dns_1123_label`]-delivered
11462 /// owned-`String` return verbatim so the closure picks the ctor up
11463 /// without a per-arm wrapper transformation, matching the peer
11464 /// [`aplicacao_field_reason_ctors!`] family's `reason: impl
11465 /// Into<String>` bound. `#[must_use]` fires a compile warning at
11466 /// any wire-up that mistakenly discards the constructed error
11467 /// rather than routing it through `return Err(…)` / `.map_err(…)`
11468 /// / a closure return.
11469 ///
11470 /// Every future consumer that wants to construct this variant
11471 /// outside the current in-crate wire-up (the deferred
11472 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
11473 /// per-`:contratos`-edge admission validator projecting the same
11474 /// diagnostic through the caller-facing `slot: &'static str` tag,
11475 /// a future `feira validate --contratos` per-caixa admission verb,
11476 /// an M4 per-`:contratos`-edge pre-emitter running the same
11477 /// DNS-1123-label floor against a caller-supplied `:de` / `:para`
11478 /// pair before hitting the apiserver-side selector, an M4
11479 /// per-cluster contrato-cap resolver rejecting a cross-tenant
11480 /// selector projection into the same diagnostic shape) — now
11481 /// reaches this variant through one call rather than re-inlining
11482 /// the six-line struct-literal block in lockstep with the one
11483 /// in-crate wire-up site.
11484 #[must_use]
11485 pub fn contrato_caixa_invalid(
11486 slot: &'static str,
11487 caixa: &str,
11488 reason: impl Into<String>,
11489 ) -> Self {
11490 Self::ContratoCaixaInvalid {
11491 slot,
11492 caixa: caixa.to_string(),
11493 reason: reason.into(),
11494 }
11495 }
11496
11497 /// Construct an [`AplicacaoError::ContratoCaixaEmpty`] naming the
11498 /// offending `:contratos <slot>` (`:de` / `:para`) at which the
11499 /// caixa-reference value is the empty string. Folds the uniform
11500 /// `Self::ContratoCaixaEmpty { slot }` one-slot struct-literal onto
11501 /// one substrate primitive so the sole in-crate closure passed to
11502 /// [`crate::render::require_valid_dns_1123_label`] at
11503 /// [`validate_contrato_caixa`] on this variant reads through one
11504 /// dispatch rather than the pre-lift open-coded block. The `slot`
11505 /// label threads verbatim from the caller-side
11506 /// [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
11507 /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
11508 /// wire-up feeds through [`validate_contrato_caixa`]'s
11509 /// `slot: &'static str` parameter.
11510 ///
11511 /// Sibling of the paired three-slot [`Self::contrato_caixa_invalid`]
11512 /// substrate primitive on the same
11513 /// [`crate::render::require_valid_dns_1123_label`] two-closure
11514 /// cascade — the empty-arm and invalid-arm now both reach the
11515 /// `AplicacaoError` envelope through one substrate primitive per
11516 /// typed variant, closing the pair. Same shape discipline as the
11517 /// peer [`crate::behavior::BehaviorError::empty_path`] one-slot
11518 /// `{ slot: &'static str }` sibling on the `BehaviorError`
11519 /// envelope's four-arm sandboxed-lisp-path cascade
11520 /// ([`crate::render::require_sandboxed_lisp_path`]) — extended here
11521 /// onto the sibling `AplicacaoError` envelope's two-arm
11522 /// DNS-1123-label cascade at the `:contratos <slot>` per-edge axis.
11523 ///
11524 /// `slot` stays `&'static str` (not `&str`) — every `:contratos
11525 /// <slot>` tag comes from the [`crate::render::CONTRATO_AUTHOR_KEY_*`]
11526 /// `const` roster carrying program-lifetime storage, matching the
11527 /// enum-field type and the [`validate_contrato_caixa`] wire-up's
11528 /// per-axis dispatch. A runtime-borrowed `&str` would silently
11529 /// downgrade the label lifetime and let a caller stash a
11530 /// non-`'static` borrow into the returned error. `#[must_use]` fires
11531 /// a compile warning at any wire-up that mistakenly discards the
11532 /// constructed error rather than routing it through `return Err(…)`
11533 /// / `.map_err(…)` / a closure return. `pub const fn` matches the
11534 /// peer per-envelope one-slot `Copy`-scalar ctor family discipline
11535 /// (`aplicacao_placement_scalar_ctors!`, `layout_nome_only_ctors!`,
11536 /// `dep_nome_only_ctors!`) so the ctor is usable in `const` position
11537 /// at every wire-up site.
11538 ///
11539 /// Every future consumer that wants to construct this variant
11540 /// outside the current in-crate wire-up (the deferred
11541 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
11542 /// per-`:contratos`-edge admission validator projecting the same
11543 /// diagnostic through the caller-facing `slot: &'static str` tag,
11544 /// a future `feira validate --contratos` per-caixa admission verb,
11545 /// an M4 per-`:contratos`-edge pre-emitter running the same
11546 /// DNS-1123-label floor's empty-arm against a caller-supplied
11547 /// `:de` / `:para` pair before hitting the apiserver-side selector,
11548 /// a per-`Caixa` overlay resolver rejecting an author-supplied
11549 /// `:contratos` overlay's empty `:de` / `:para` against a
11550 /// cluster-local snapshot) — now reaches this variant through one
11551 /// call rather than re-inlining the open-coded closure block in
11552 /// lockstep with the one in-crate wire-up site.
11553 #[must_use]
11554 pub const fn contrato_caixa_empty(slot: &'static str) -> Self {
11555 Self::ContratoCaixaEmpty { slot }
11556 }
11557}
11558
11559// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
11560// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
11561// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
11562// substrate-primitive family per typed variant — the paired
11563// `{ <field>: String, reason: String }` two-slot sibling on
11564// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
11565// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
11566// `ContratoMissingTarget`) and the peer two-slot
11567// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
11568// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
11569// on the sibling per-`:contratos` envelopes, plus the peer four-family
11570// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
11571// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
11572// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
11573// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
11574// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
11575// sibling layout-side envelope.
11576//
11577// Every one of the seven wire-up sites — six under the per-axis
11578// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
11579// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
11580// on `EntradaParaInvalid`, `validate_placement_cluster` on
11581// `PlacementClusterInvalid`, `validate_placement_affinity` on
11582// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
11583// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
11584// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
11585// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
11586// sites at [`validate_entrada_host`] (17dd504 already folded onto the
11587// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
11588// the macro-generated ctor of the same name), opened the identical
11589// four-line `AplicacaoError::<Variant>Invalid
11590// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
11591// the local `<field>: &str` argument — the exact "same block re-inlined
11592// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
11593// same altitude the peer three `AplicacaoError` constructor families
11594// and the four peer `LayoutError` constructor families each closed on
11595// their sibling envelopes.
11596//
11597// The macro below generates one `#[must_use]` inherent constructor per
11598// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
11599// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
11600// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
11601// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
11602// pre-lift struct-literal on the same `(<field>, reason)` pair. The
11603// uniform two-field construction (`<field>: <val>.to_string()`,
11604// `reason: reason.into()`) is spelled once — inside the macro — rather
11605// than at every wire-up site. The `reason: impl Into<String>` bound
11606// accepts both `&str` literals (with or without a trailing
11607// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
11608// wire-up site changes its per-arm diagnostic shape at the lift.
11609// `#[must_use]` fires a compile warning at any wire-up that mistakenly
11610// discards the constructed error rather than routing it through
11611// `return Err(…)` / `.map_err(…)` / a closure return.
11612//
11613// Every future consumer that wants to construct one of these seven
11614// variants outside the current in-crate wire-up sites (the deferred
11615// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
11616// admission validators, a future `feira validate --<axis>` per-caixa
11617// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
11618// on `:entrada :host`, an M4 typed placement-engine per-cluster /
11619// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
11620// per-path pre-emitter) reaches the variant through one call rather
11621// than re-inlining the four-line struct-literal block in lockstep with
11622// the current in-crate wire-up sites.
11623macro_rules! aplicacao_field_reason_ctors {
11624 ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
11625 impl AplicacaoError {
11626 $(
11627 #[doc = concat!(
11628 "Construct an [`AplicacaoError::",
11629 stringify!($variant),
11630 "`] naming the offending `",
11631 stringify!($field),
11632 "` under the given `reason`. Folds the uniform ",
11633 "`{ ",
11634 stringify!($field),
11635 ": ",
11636 stringify!($field),
11637 ".to_string(), reason: reason.into() }` two-slot ",
11638 "construction onto one substrate primitive so every ",
11639 "wire-up on this variant reads through one dispatch ",
11640 "rather than the pre-lift four-line struct-literal ",
11641 "block. `reason` accepts both `&str` literals and ",
11642 "`format!(…)` outputs through the `impl Into<String>` ",
11643 "bound."
11644 )]
11645 #[must_use]
11646 pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
11647 Self::$variant {
11648 $field: $field.to_string(),
11649 reason: reason.into(),
11650 }
11651 }
11652 )*
11653 }
11654 };
11655}
11656
11657aplicacao_field_reason_ctors! {
11658 membro_caixa_invalid => MembroCaixaInvalid { caixa },
11659 entrada_para_invalid => EntradaParaInvalid { para },
11660 entrada_host_invalid => EntradaHostInvalid { host },
11661 entrada_path_invalid => EntradaPathInvalid { path },
11662 placement_cluster_invalid => PlacementClusterInvalid { cluster },
11663 placement_affinity_invalid => PlacementAffinityInvalid { affinity },
11664 shard_key_invalid => ShardKeyInvalid { shard_key },
11665}
11666
11667// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
11668// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
11669// [`WitContract::target`] onto one substrate-primitive family per typed
11670// variant — the paired `{ de: String, para: String, <field>: String,
11671// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
11672// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
11673// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
11674// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
11675// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
11676// `ContratoSlotEmpty`), and the peer two-slot
11677// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
11678// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
11679// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
11680// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
11681// sibling `AplicacaoError` envelopes, plus the peer four-family
11682// `LayoutError` ctor set on the sibling layout-side envelope.
11683//
11684// Every one of the four wire-up sites — four per-`:contratos` value-
11685// shape gates inside [`WitContract::target`] (the world-ref prefix
11686// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
11687// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
11688// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
11689// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
11690// failure on `:slot`) — opened the identical five-line
11691// `let (de, para) = self.edge_pair();
11692// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
11693// <field>: <val>.to_string(), reason });` block against the local
11694// [`WitContract::edge_pair`] composite-projection accessor and the
11695// per-arm `<val>: &str` argument — the exact "same block re-inlined at
11696// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
11697// altitude the peer three `AplicacaoError` constructor families and the
11698// four peer `LayoutError` constructor families each closed on their
11699// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
11700// macro closes the last unlifted `{ de, para, <field>: String, reason:
11701// String }` four-slot envelope inside `impl WitContract`, so every
11702// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
11703// reads through this one substrate primitive.
11704//
11705// The macro below generates one `#[must_use]` inherent constructor per
11706// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
11707// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
11708// sites onto one dispatch per arm:
11709// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
11710// byte-equal to the pre-lift struct-literal on the same
11711// `(edge_pair, <val>, reason)` triple. The uniform four-field
11712// construction (`de, para` pair-destructure onto same-named fields +
11713// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
11714// once — inside the macro — rather than at every wire-up site. The
11715// `reason: impl Into<String>` bound accepts both `&str` literals and
11716// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
11717// diagnostic shape at the lift, matching the peer
11718// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
11719// envelope. `#[must_use]` fires a compile warning at any wire-up that
11720// mistakenly discards the constructed error.
11721//
11722// Every future consumer that wants to construct one of these four
11723// variants outside [`WitContract::target`] (a deferred
11724// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
11725// admission validator raising per-payload value-shape diagnostics on
11726// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
11727// future `feira validate --contratos` per-caixa admission verb, an M4
11728// typed WIT-registry-driven per-arm pre-emitter probing each declared
11729// `:endpoint` / `:subject` / `:slot` payload against a canonical
11730// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
11731// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
11732// pre-emitter probing each `:endpoint` against the same shared
11733// HTTPPathMatch grammar) reaches the variant through one call rather
11734// than re-inlining the five-line pair-destructure + struct-literal
11735// block in lockstep with the four in-crate wire-up sites.
11736macro_rules! contrato_pair_value_reason_ctors {
11737 ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
11738 impl AplicacaoError {
11739 $(
11740 #[doc = concat!(
11741 "Construct an [`AplicacaoError::",
11742 stringify!($variant),
11743 "`] naming the offending edge `(de, para)` pair, the ",
11744 "per-payload `",
11745 stringify!($field),
11746 "` value, and the parser-shaped `reason`. Folds the ",
11747 "uniform `{ de, para, ",
11748 stringify!($field),
11749 ": ",
11750 stringify!($field),
11751 ".to_string(), reason: reason.into() }` four-slot ",
11752 "construction onto one substrate primitive so every ",
11753 "wire-up on this variant reads through one dispatch ",
11754 "rather than the pre-lift five-line pair-destructure ",
11755 "+ struct-literal block. The `edge` pair threads ",
11756 "verbatim from [`WitContract::edge_pair`] at the ",
11757 "call site; `reason` accepts both `&str` literals ",
11758 "and `format!(…)` outputs through the `impl ",
11759 "Into<String>` bound."
11760 )]
11761 #[must_use]
11762 pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
11763 let (de, para) = edge;
11764 Self::$variant {
11765 de,
11766 para,
11767 $field: $field.to_string(),
11768 reason: reason.into(),
11769 }
11770 }
11771 )*
11772 }
11773 };
11774}
11775
11776contrato_pair_value_reason_ctors! {
11777 contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
11778 contrato_subject_invalid => ContratoSubjectInvalid { subject },
11779 contrato_slot_invalid => ContratoSlotInvalid { slot },
11780 contrato_wit_invalid => ContratoWitInvalid { wit },
11781}
11782
11783// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
11784// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
11785// caixa-only struct-variant wire-up sites at
11786// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
11787// `:contratos :para` arms of `ContratoMemberMissing`),
11788// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
11789// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
11790// and [`validate_no_self_membership`] (one site, the parent-`:nome`
11791// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
11792// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
11793// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
11794// three variants on `{ caixa: String }` at
11795// [`crate::SupervisorSpec::validate_children`] and
11796// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
11797// `SupervisorError` envelope, extending the same "one substrate primitive per
11798// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
11799// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
11800// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
11801// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
11802// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
11803// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
11804// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
11805// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
11806// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
11807// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
11808// variants on `{ nome, caminho }`), and
11809// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
11810// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
11811// peer three `AplicacaoError` sub-family folds already lifted here
11812// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
11813// [`aplicacao_field_reason_ctors!`] 981060b,
11814// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
11815// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
11816// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
11817// [`crate::LayoutError::missing_entry`] 1b09f9d,
11818// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
11819// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
11820//
11821// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
11822// at the per-`:contratos :de`/`:para` unknown-member arms, one on
11823// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
11824// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
11825// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
11826// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
11827// three-line struct-literal against a caller-side `&str` — the exact "same
11828// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
11829// bug, on the same altitude the peer `SupervisorError` /
11830// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
11831// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
11832// their sibling envelopes. The four variants share one `{ caixa: String }`
11833// shape, so the fold routes each wire-up site through one dispatch per typed
11834// variant.
11835//
11836// The macro below generates one `#[must_use]` inherent constructor per
11837// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
11838// wire-up site collapses onto one dispatch:
11839// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
11840// on the same `&str` fixture. The uniform one-field construction
11841// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
11842// than at every wire-up site. Every constructor is `#[must_use]` so a caller
11843// who mistakenly discards the constructed error trips a compile warning at
11844// the wire-up site.
11845//
11846// Every future consumer that wants to construct one of these four variants
11847// outside the current in-crate wire-up sites — a deferred
11848// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
11849// re-checking one added/renamed `:membros` entry against the sibling
11850// `:contratos` graph, a future `feira validate --membros` per-caixa admission
11851// verb re-checking each declared `:membros` entry's `:caixa` name against the
11852// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
11853// duplicate / self-referencing / unknown-membered `:contratos` entry against
11854// a cluster-local snapshot the M4 CR materializer projects — now reaches each
11855// variant through one call rather than re-inlining the three-line
11856// struct-literal in lockstep with the five in-crate wire-up sites.
11857macro_rules! aplicacao_caixa_only_ctors {
11858 ($($ctor:ident => $variant:ident),* $(,)?) => {
11859 impl AplicacaoError {
11860 $(
11861 #[doc = concat!(
11862 "Construct an [`AplicacaoError::",
11863 stringify!($variant),
11864 "`] naming the offending `:membros :caixa` (or ",
11865 "parent `:nome`, on the self-membership arm; or ",
11866 "`:contratos :de`/`:para`, on the unknown-member ",
11867 "arm). Folds the uniform `Self::",
11868 stringify!($variant),
11869 " { caixa: caixa.to_string() }` one-field ",
11870 "struct-literal onto one substrate primitive so ",
11871 "every wire-up on this variant reads through one ",
11872 "dispatch rather than the pre-lift three-line ",
11873 "open-coded struct-literal block."
11874 )]
11875 #[must_use]
11876 pub fn $ctor(caixa: &str) -> Self {
11877 Self::$variant { caixa: caixa.to_string() }
11878 }
11879 )*
11880 }
11881 };
11882}
11883
11884aplicacao_caixa_only_ctors! {
11885 contrato_member_missing => ContratoMemberMissing,
11886 membro_versao_empty => MembroVersaoEmpty,
11887 membro_duplicate => MembroDuplicate,
11888 membro_is_self_aplicacao => MembroIsSelfAplicacao,
11889}
11890
11891// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
11892// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
11893// sites onto one substrate-primitive family per typed variant — the direct
11894// per-`:entrada :paths` value-shape sibling of the peer
11895// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
11896// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
11897// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
11898// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
11899// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
11900// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
11901// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
11902// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
11903// `:deps` envelope — every single-`String`-slot error family in caixa-core
11904// now reaches through one substrate primitive per typed variant.
11905//
11906// The three wire-up sites — one under [`validate_entrada_path`]'s
11907// leading-slash grammar arm (`EntradaPathNotAbsolute` against
11908// `path: &str`), one under the per-`:entrada :paths` loop's identical
11909// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
11910// and one under the per-`:entrada :paths` loop's dedup arm
11911// (`EntradaPathDuplicate` against the same `&String` via
11912// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
11913// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
11914// three-line struct-literal against a caller-side `&str` / `&String`, the
11915// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
11916// names as a bug. Every one of the compile-time guarantees in
11917// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
11918// start with `/` becomes a caixa-build error, not a Gateway API webhook
11919// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
11920// becomes a caixa-build error, not a silent last-writer-wins render) now
11921// routes through one dispatch per typed variant at every emit site.
11922//
11923// The macro below generates one `#[must_use]` inherent constructor per
11924// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
11925// every wire-up site onto one dispatch:
11926// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
11927// on the same `&str` fixture) or the `&String` sites through
11928// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
11929// construction (`path: path.to_string()`) is spelled once — inside the
11930// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
11931// a caller who mistakenly discards the constructed error trips a compile
11932// warning at the wire-up site.
11933//
11934// Every future consumer that wants to construct one of these two variants
11935// outside the current in-crate wire-up sites — a deferred
11936// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
11937// per-`:entrada :paths` re-check against a cluster-local Gateway API
11938// snapshot, a future `feira validate --entrada` per-caixa admission verb
11939// re-checking each declared `:paths` entry against the same axes, a
11940// per-tenant per-`Aplicacao` overlay resolver rejecting a
11941// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
11942// snapshot the M4 CR materializer projects — now reaches each variant
11943// through one call rather than re-inlining the three-line struct-literal in
11944// lockstep with the three in-crate wire-up sites.
11945macro_rules! aplicacao_path_only_ctors {
11946 ($($ctor:ident => $variant:ident),* $(,)?) => {
11947 impl AplicacaoError {
11948 $(
11949 #[doc = concat!(
11950 "Construct an [`AplicacaoError::",
11951 stringify!($variant),
11952 "`] naming the offending `:entrada :paths` entry. ",
11953 "Folds the uniform `Self::",
11954 stringify!($variant),
11955 " { path: path.to_string() }` one-field ",
11956 "struct-literal onto one substrate primitive so ",
11957 "every wire-up on this variant reads through one ",
11958 "dispatch rather than the pre-lift three-line ",
11959 "open-coded struct-literal block."
11960 )]
11961 #[must_use]
11962 pub fn $ctor(path: &str) -> Self {
11963 Self::$variant { path: path.to_string() }
11964 }
11965 )*
11966 }
11967 };
11968}
11969
11970aplicacao_path_only_ctors! {
11971 entrada_path_not_absolute => EntradaPathNotAbsolute,
11972 entrada_path_duplicate => EntradaPathDuplicate,
11973}
11974
11975// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
11976// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
11977// substrate-primitive family per typed variant — the per-`:politicas` copy-
11978// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
11979// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
11980// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
11981// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
11982// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
11983// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
11984// the `String`-slot axis, and the peer per-`:politicas` cross-axis
11985// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
11986// carries at line 3064 on the same M3 mesh envelope.
11987//
11988// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
11989// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
11990// { <slot> }` one-line struct-literal closure against the caller-side
11991// `<slot>: <ty>` argument that the shared
11992// [`crate::render::require_positive_bounded_u32`] /
11993// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
11994// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
11995// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
11996// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
11997// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
11998// on line 3211) — the exact "same one-line struct-literal re-inlined at every
11999// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
12000// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
12001// been folded onto a substrate primitive.
12002//
12003// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
12004// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
12005// collapsing every wire-up onto either one direct dispatch
12006// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
12007// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
12008// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
12009// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
12010// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
12011// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
12012// constructor with matching arity and signature. The `const fn` qualifier
12013// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
12014// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
12015// per-variant `$field:ident` axis re-uses the enum's canonical field name so
12016// the generated ctor's parameter name matches every wire-up's local binding
12017// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
12018// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
12019// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
12020// warning at any wire-up that mistakenly discards the constructed error, on
12021// the same footing as every sibling `AplicacaoError` / `DepError` /
12022// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
12023// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
12024// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
12025// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
12026//
12027// Every future consumer that wants to construct one of these eight variants
12028// outside [`MeshPolicy::validate`] — a deferred
12029// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
12030// checking each `:politicas` axis against a cluster-local `:politicas` cap
12031// overlay, a future per-`:contratos`-edge `:politicas` override the
12032// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
12033// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
12034// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
12035// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
12036// a future `feira validate --politicas` per-caixa admission verb re-checking
12037// each declared per-axis value against the same bounds — now reaches each
12038// variant through one call rather than re-inlining the one-line struct-
12039// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
12040// which is exactly the invariant every prior ctor-macro lift already closed
12041// on its sibling envelope. Closes the last remaining per-`:politicas`
12042// per-axis `AplicacaoError` variant family that had not yet been folded onto
12043// a substrate primitive; the compound cross-axis variants
12044// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
12045// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
12046// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
12047macro_rules! aplicacao_policy_scalar_ctors {
12048 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
12049 impl AplicacaoError {
12050 $(
12051 #[doc = concat!(
12052 "Construct an [`AplicacaoError::",
12053 stringify!($variant),
12054 "`] naming the offending per-`:politicas` `",
12055 stringify!($field),
12056 "` scalar. Folds the uniform `Self::",
12057 stringify!($variant),
12058 " { ",
12059 stringify!($field),
12060 " }` one-field `Copy`-pass-through struct-literal onto ",
12061 "one substrate primitive so every per-axis wire-up on ",
12062 "this variant reads through one dispatch — as a direct ",
12063 "call (`AplicacaoError::",
12064 stringify!($ctor),
12065 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
12066 "the same `Copy`-`",
12067 stringify!($ty),
12068 "` fixture) or as a bare function pointer in the ",
12069 "`impl FnOnce(",
12070 stringify!($ty),
12071 ") -> AplicacaoError` bracket-closure slot every ",
12072 "`crate::render::require_positive_bounded_*` / ",
12073 "`crate::render::require_positive_canonical_bounded_*` ",
12074 "gate carries — rather than the pre-lift open-coded ",
12075 "one-line closure over the same one-field struct-",
12076 "literal. `const fn` preserves the `Copy`-pass-through's ",
12077 "zero-runtime-work property verbatim."
12078 )]
12079 #[must_use]
12080 pub const fn $ctor($field: $ty) -> Self {
12081 Self::$variant { $field }
12082 }
12083 )*
12084 }
12085 };
12086}
12087
12088aplicacao_policy_scalar_ctors! {
12089 policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
12090 policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
12091 policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
12092 policy_breaker_max_failures_exceeds_cap =>
12093 PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
12094 policy_breaker_window_not_canonical =>
12095 PolicyBreakerWindowNotCanonical { window: Duration },
12096 policy_breaker_window_exceeds_cap =>
12097 PolicyBreakerWindowExceedsCap { window: Duration },
12098 policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
12099 policy_rate_limit_window_not_canonical =>
12100 PolicyRateLimitWindowNotCanonical { window: Duration },
12101}
12102
12103#[cfg(test)]
12104mod tests {
12105 use super::*;
12106
12107 fn membro(name: &str, ver: &str) -> Membro {
12108 Membro {
12109 caixa: name.into(),
12110 versao: ver.into(),
12111 }
12112 }
12113
12114 fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
12115 WitContract {
12116 de: de.into(),
12117 para: para.into(),
12118 wit: "wasi:http/proxy".into(),
12119 endpoint: Some(ep.into()),
12120 subject: None,
12121 slot: None,
12122 }
12123 }
12124
12125 fn three_member_spec() -> AplicacaoSpec {
12126 AplicacaoSpec {
12127 membros: vec![
12128 membro("catalog", "^0.1"),
12129 membro("cart", "^0.1"),
12130 membro("payment", "^0.2"),
12131 ],
12132 contratos: vec![
12133 contract_http("cart", "catalog", "/products/:id"),
12134 contract_http("cart", "payment", "/charge"),
12135 ],
12136 politicas: MeshPolicy {
12137 timeout: Some(Duration::from_secs(30)),
12138 retries: Some(3),
12139 mtls_required: Some(true),
12140 ..Default::default()
12141 },
12142 placement: Placement {
12143 estrategia: PlacementStrategy::Replicated,
12144 clusters: vec!["rio".into(), "mar".into()],
12145 affinity: Some("data-locality".into()),
12146 shard_key: None,
12147 },
12148 entrada: Some(Entrada {
12149 host: "checkout.quero.cloud".into(),
12150 para: "cart".into(),
12151 paths: vec!["/api/cart".into(), "/api/products".into()],
12152 port: 8080,
12153 }),
12154 }
12155 }
12156
12157 #[test]
12158 fn happy_path_validates() {
12159 three_member_spec().validate().unwrap();
12160 }
12161
12162 #[test]
12163 fn rejects_empty_membros() {
12164 let mut s = three_member_spec();
12165 s.membros = vec![];
12166 assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
12167 }
12168
12169 #[test]
12170 fn rejects_empty_membro_caixa() {
12171 // A `:caixa ""` entry has no name to render into programs.yaml
12172 // and no caixa.lisp to resolve at lacre time.
12173 let mut s = three_member_spec();
12174 s.membros[1].caixa = String::new();
12175 assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
12176 }
12177
12178 #[test]
12179 fn rejects_empty_membro_versao() {
12180 // A `:versao ""` entry can't pin a semver constraint, so the
12181 // lacre pipeline fails far from the source.
12182 let mut s = three_member_spec();
12183 s.membros[2].versao = String::new();
12184 let err = s.validate().unwrap_err();
12185 assert!(
12186 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
12187 "got {err:?}"
12188 );
12189 }
12190
12191 #[test]
12192 fn rejects_duplicate_membro_caixa() {
12193 // Two `:membros` entries with the same `:caixa` collapse to one
12194 // node in the membership HashSet, which masks `:contratos`
12195 // membership errors and produces duplicate programs.yaml entries.
12196 let mut s = three_member_spec();
12197 s.membros.push(membro("cart", "^0.2"));
12198 let err = s.validate().unwrap_err();
12199 assert!(
12200 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
12201 "got {err:?}"
12202 );
12203 }
12204
12205 #[test]
12206 fn rejects_invalid_membro_versao_requirement() {
12207 // The fail-before-pass-after pin: a non-empty but malformed
12208 // semver requirement (`"^bad-version"`) silently passed
12209 // `validate()` on every pre-gate codebase because the prior
12210 // shape only refused the empty string. The parse failure
12211 // surfaced far downstream at lacre-resolve time with a
12212 // `semver::Error` that didn't name which `:membros` entry
12213 // carried the typo. The new gate moves the check to caixa-build
12214 // time at the source caixa.lisp.
12215 let mut s = three_member_spec();
12216 s.membros[2].versao = "^bad-version".into();
12217 let err = s.validate().unwrap_err();
12218 assert!(
12219 matches!(
12220 err,
12221 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
12222 if caixa == "payment" && versao == "^bad-version"
12223 ),
12224 "got {err:?}"
12225 );
12226 }
12227
12228 #[test]
12229 fn rejects_membro_versao_with_double_caret_typo() {
12230 // `"^^0.1"` is the canonical doubled-caret typo — looks like a
12231 // Cargo-shaped requirement on first glance but fails the parser
12232 // because semver doesn't accept stacked operators. Pin this
12233 // adjacent-shape footgun explicitly so a future relaxation that
12234 // accepts "looks-canonical-but-isn't" forms surfaces here.
12235 let mut s = three_member_spec();
12236 s.membros[0].versao = "^^0.1".into();
12237 let err = s.validate().unwrap_err();
12238 assert!(
12239 matches!(
12240 err,
12241 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
12242 if caixa == "catalog" && versao == "^^0.1"
12243 ),
12244 "got {err:?}"
12245 );
12246 }
12247
12248 #[test]
12249 fn rejects_membro_versao_with_v_prefixed_tag() {
12250 // `"v0.1"` is the canonical "git-tag-shape leaking into the
12251 // semver requirement slot" typo — an author copies the
12252 // publish-side git-tag string verbatim into `:versao`, but
12253 // Cargo's semver parser rejects the leading `v` (only digits +
12254 // canonical operators are valid in the major-version
12255 // position). The gate's diagnostic names which member entry
12256 // carried the v-prefix so the fix is one edit, not a grep
12257 // through every member's `:versao`. (Note: bare `x`-glob
12258 // shorthands like `^0.1.x` are *accepted* by the semver crate
12259 // as an `*` wildcard on the patch axis — they're a Cargo-side
12260 // valid shape, not a typo, so the gate intentionally lets them
12261 // through.)
12262 let mut s = three_member_spec();
12263 s.membros[1].versao = "v0.1".into();
12264 let err = s.validate().unwrap_err();
12265 assert!(
12266 matches!(
12267 err,
12268 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
12269 if caixa == "cart" && versao == "v0.1"
12270 ),
12271 "got {err:?}"
12272 );
12273 }
12274
12275 #[test]
12276 fn accepts_canonical_membro_versao_forms() {
12277 // The four Cargo-shaped requirement forms `:deps :versao`
12278 // already accepts via `crate::parse_requirement` must pass the
12279 // membros gate without re-validating at the resolver layer.
12280 // Pin every leg so a future tightening of the canonical set
12281 // surfaces here as a test failure.
12282 for form in [
12283 "^0.1", // caret — minor-range pin (the most common shape)
12284 "~0.1.2", // tilde — patch-range pin
12285 "0.1.0", // exact — single-version pin
12286 "*", // wildcard — explicitly any-version (semver::VersionReq::STAR)
12287 ">=0.1, <2", // multi-range — comma-separated comparators
12288 ] {
12289 let mut s = three_member_spec();
12290 for m in &mut s.membros {
12291 m.versao = form.into();
12292 }
12293 s.validate()
12294 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
12295 }
12296 }
12297
12298 #[test]
12299 fn membro_versao_empty_takes_precedence_over_invalid() {
12300 // Order pin: the existing `MembroVersaoEmpty` diagnostic
12301 // (which doesn't try to parse) fires before the new
12302 // `MembroVersaoInvalid` parse-side diagnostic, so an empty
12303 // `:versao` keeps its narrower error message — `parse_requirement`
12304 // would also reject `""`, but the empty-string arm is the more
12305 // self-locating diagnostic for the author.
12306 let mut s = three_member_spec();
12307 s.membros[1].versao = String::new();
12308 let err = s.validate().unwrap_err();
12309 assert!(
12310 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
12311 "got {err:?}"
12312 );
12313 }
12314
12315 #[test]
12316 fn membro_versao_invalid_fires_before_duplicate_check() {
12317 // Order pin: a malformed requirement on a non-duplicate entry
12318 // surfaces *its own* diagnostic (which names the offending
12319 // `:versao` string), even when a later entry would otherwise
12320 // collapse onto an earlier name. The per-entry shape gate runs
12321 // inline before the duplicate-key insert, parallel to
12322 // `membros_validation_runs_before_contratos_membership_check`
12323 // and `duplicate_contrato_gate_runs_after_target_shape_check`.
12324 let mut s = three_member_spec();
12325 s.membros[0].versao = "^bad".into();
12326 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
12327 let err = s.validate().unwrap_err();
12328 assert!(
12329 matches!(
12330 err,
12331 AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
12332 ),
12333 "got {err:?}"
12334 );
12335 }
12336
12337 #[test]
12338 fn membro_versao_invalid_diagnostic_carries_offending_versao() {
12339 // The diagnostic-shape pin: the error names the offending
12340 // `:versao` value verbatim so the author can grep their
12341 // caixa.lisp without re-running the build, and carries a
12342 // non-empty `reason` from `semver::VersionReq::parse` so the
12343 // parser's own wording flows through to the diagnostic.
12344 let mut s = three_member_spec();
12345 s.membros[2].versao = "not-a-req".into();
12346 let err = s.validate().unwrap_err();
12347 let AplicacaoError::MembroVersaoInvalid {
12348 caixa,
12349 versao,
12350 reason,
12351 } = err
12352 else {
12353 panic!("expected MembroVersaoInvalid, got other variant");
12354 };
12355 assert_eq!(caixa, "payment");
12356 assert_eq!(versao, "not-a-req");
12357 assert!(
12358 !reason.is_empty(),
12359 "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
12360 );
12361 }
12362
12363 #[test]
12364 fn membro_versao_invalid_runs_before_contratos_check() {
12365 // A malformed `:versao` on any member must surface its own
12366 // diagnostic (which names *which* member to fix) before any
12367 // `:contratos` membership lookup raises `ContratoMemberMissing`.
12368 // The `:contratos` gate runs after `validate_membros`, so this
12369 // is structurally guaranteed — pin it explicitly so a future
12370 // refactor that reorders the gates surfaces here.
12371 let mut s = three_member_spec();
12372 s.membros[1].versao = "^^0.1".into();
12373 // Add a contrato whose `:para` doesn't exist — would normally
12374 // raise ContratoMemberMissing at the membership lookup, but
12375 // the membros gate must fire first.
12376 s.contratos
12377 .push(contract_http("cart", "phantom", "/never-reached"));
12378 let err = s.validate().unwrap_err();
12379 assert!(
12380 matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
12381 "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
12382 );
12383 }
12384
12385 #[test]
12386 fn membros_validation_runs_before_contratos_membership_check() {
12387 // If `:membros` carries a duplicate, the membership-collapse
12388 // would silently accept a `:contratos :para "phantom"` so long
12389 // as some entry hashes to "phantom". Pinning order: the
12390 // duplicate-membros error fires first, regardless of whether
12391 // contratos reference real members.
12392 let mut s = three_member_spec();
12393 s.membros = vec![
12394 membro("cart", "^0.1"),
12395 membro("cart", "^0.2"),
12396 membro("catalog", "^0.1"),
12397 membro("payment", "^0.1"),
12398 ];
12399 let err = s.validate().unwrap_err();
12400 assert!(
12401 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
12402 "got {err:?}"
12403 );
12404 }
12405
12406 #[test]
12407 fn distinct_membros_validate() {
12408 // Pin the happy-path: every `:membros` entry has a non-empty
12409 // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
12410 // The fixture already satisfies this; this test makes the
12411 // invariant explicit so a future refactor of the fixture can't
12412 // silently break the guarantee.
12413 three_member_spec().validate().unwrap();
12414 }
12415
12416 // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
12417
12418 #[test]
12419 fn rejects_membro_caixa_with_uppercase() {
12420 // The canonical "I copied the Servico's display name verbatim"
12421 // typo — caixa names are lowercase per K8s DNS-1123 label rule,
12422 // but author tools often round-trip a TitleCase or CamelCase
12423 // identifier from an ADR or a sketch. Pin the diagnostic names
12424 // the offending name and suggests the lower-cased fix in one
12425 // edit, mirroring the `rejects_entrada_host_with_uppercase`
12426 // gate's shape (c7d05ec).
12427 let mut s = three_member_spec();
12428 s.membros[1].caixa = "Cart".into();
12429 let err = s.validate().unwrap_err();
12430 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
12431 panic!("expected MembroCaixaInvalid, got other variant");
12432 };
12433 assert_eq!(caixa, "Cart");
12434 assert!(
12435 reason.contains("uppercase"),
12436 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
12437 );
12438 assert!(
12439 reason.contains("\"cart\""),
12440 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
12441 );
12442 }
12443
12444 #[test]
12445 fn rejects_membro_caixa_with_underscore() {
12446 // The canonical "I'm thinking of a Python module / Postgres
12447 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
12448 // label schema. K8s rejects `metadata.name: my_cart` at admission
12449 // time with an opaque `field is invalid` (no source-citing
12450 // diagnostic). The gate moves it to caixa-build time.
12451 let mut s = three_member_spec();
12452 s.membros[0].caixa = "my_cart".into();
12453 let err = s.validate().unwrap_err();
12454 assert!(
12455 matches!(
12456 err,
12457 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
12458 if caixa == "my_cart" && reason.contains('_')
12459 ),
12460 "got {err:?}"
12461 );
12462 }
12463
12464 #[test]
12465 fn rejects_membro_caixa_with_dot() {
12466 // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
12467 // subdomain — even though K8s `metadata.name` itself accepts
12468 // dots (DNS-1123 subdomain rule), this string also lands as a
12469 // K8s Service name (DNS-1035 label — no dots) and as a label
12470 // value on identity-based Cilium selectors. The strictest floor
12471 // among the use sites wins. The "I want to namespace my member
12472 // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
12473 let mut s = three_member_spec();
12474 s.membros[2].caixa = "team.cart".into();
12475 let err = s.validate().unwrap_err();
12476 assert!(
12477 matches!(
12478 err,
12479 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
12480 if caixa == "team.cart" && reason.contains('.')
12481 ),
12482 "got {err:?}"
12483 );
12484 }
12485
12486 #[test]
12487 fn rejects_membro_caixa_with_leading_hyphen() {
12488 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
12489 // with an alphanumeric. The K8s apiserver rejects `-cart`
12490 // outright; the renderer would emit a `metadata.name: "-cart"`
12491 // that fails admission far from the source caixa.lisp.
12492 let mut s = three_member_spec();
12493 s.membros[0].caixa = "-cart".into();
12494 let err = s.validate().unwrap_err();
12495 assert!(
12496 matches!(
12497 err,
12498 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
12499 if caixa == "-cart" && reason.contains("start and end")
12500 ),
12501 "got {err:?}"
12502 );
12503 }
12504
12505 #[test]
12506 fn rejects_membro_caixa_with_trailing_hyphen() {
12507 // The symmetric arm of the boundary rule. Pin separately so
12508 // both ends of the label are covered against a future relaxation
12509 // that only checks one boundary.
12510 let mut s = three_member_spec();
12511 s.membros[1].caixa = "cart-".into();
12512 let err = s.validate().unwrap_err();
12513 assert!(
12514 matches!(
12515 err,
12516 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
12517 if caixa == "cart-"
12518 ),
12519 "got {err:?}"
12520 );
12521 }
12522
12523 #[test]
12524 fn rejects_membro_caixa_with_unicode() {
12525 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
12526 // (`xn--…`) by the author before it reaches K8s. The byte-by-
12527 // byte ASCII validity check rejects multi-byte UTF-8 sequences
12528 // by the first byte that fails the `[a-z0-9-]` predicate.
12529 let mut s = three_member_spec();
12530 s.membros[2].caixa = "café".into();
12531 let err = s.validate().unwrap_err();
12532 assert!(
12533 matches!(
12534 err,
12535 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
12536 if caixa == "café"
12537 ),
12538 "got {err:?}"
12539 );
12540 }
12541
12542 #[test]
12543 fn rejects_membro_caixa_with_whitespace() {
12544 // Whitespace is the canonical "I pasted from a sketch / doc"
12545 // footgun. The apiserver rejects every `metadata.name` value
12546 // carrying whitespace; pin the gate fires at the right boundary.
12547 let mut s = three_member_spec();
12548 s.membros[0].caixa = "my cart".into();
12549 let err = s.validate().unwrap_err();
12550 assert!(
12551 matches!(
12552 err,
12553 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
12554 if caixa == "my cart"
12555 ),
12556 "got {err:?}"
12557 );
12558 }
12559
12560 #[test]
12561 fn rejects_membro_caixa_too_long() {
12562 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
12563 // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
12564 // exactly. The gate's reason names both the cap and the actual
12565 // length so the author can shorten in one edit.
12566 let mut s = three_member_spec();
12567 let too_long = "a".repeat(64);
12568 s.membros[1].caixa = too_long.clone();
12569 let err = s.validate().unwrap_err();
12570 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
12571 panic!("expected MembroCaixaInvalid");
12572 };
12573 assert_eq!(caixa, too_long);
12574 assert!(
12575 reason.contains("63") && reason.contains("64"),
12576 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
12577 );
12578 }
12579
12580 #[test]
12581 fn membro_caixa_max_length_validates() {
12582 // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
12583 // so a future tightening (e.g. dropping to 62) surfaces here as
12584 // a regression, mirroring `entrada_host_max_length_validates`
12585 // (c7d05ec).
12586 let mut s = three_member_spec();
12587 s.membros[2].caixa = "a".repeat(63);
12588 s.entrada.as_mut().unwrap().para = "a".repeat(63);
12589 // remove contratos referencing the renamed member; they'd
12590 // raise ContratoMemberMissing otherwise
12591 s.contratos
12592 .retain(|c| c.de != "payment" && c.para != "payment");
12593 s.validate().unwrap();
12594 }
12595
12596 #[test]
12597 fn accepts_canonical_membro_caixa_forms() {
12598 // The DNS-1123 label shapes a caixa author is realistically
12599 // going to write: single-word lowercase, hyphen-joined, ending
12600 // in a digit-suffixed version (`cart-v2`), starting with a
12601 // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
12602 // DNS-1035 which requires a letter at position 0), single-
12603 // character (`a` — boundary). Pin every leg so a future
12604 // tightening that bans (e.g.) digit-start identifiers surfaces
12605 // here.
12606 for form in [
12607 "checkout",
12608 "cart",
12609 "cart-v2",
12610 "a",
12611 "c0",
12612 "3rd-party-shim",
12613 "x-1-2-3-4",
12614 ] {
12615 let mut s = three_member_spec();
12616 // Renaming a member also requires updating downstream refs;
12617 // drop everything else and rebuild a minimal spec around
12618 // just the one renamed member.
12619 s.membros = vec![membro(form, "^0.1")];
12620 s.contratos = vec![];
12621 s.entrada = None;
12622 s.validate()
12623 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
12624 }
12625 }
12626
12627 #[test]
12628 fn membro_caixa_empty_takes_precedence_over_invalid() {
12629 // Order pin: the existing `MembroCaixaEmpty` diagnostic
12630 // (which doesn't try to parse) fires before the new
12631 // `MembroCaixaInvalid` parse-side diagnostic, so an empty
12632 // `:caixa` keeps its narrower error message — the new gate
12633 // would also reject `""`, but the empty-string arm is the more
12634 // self-locating diagnostic for the author. Mirrors the
12635 // `entrada_host_empty_takes_precedence_over_invalid` pin
12636 // (c7d05ec).
12637 let mut s = three_member_spec();
12638 s.membros[1].caixa = String::new();
12639 let err = s.validate().unwrap_err();
12640 assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
12641 }
12642
12643 #[test]
12644 fn membro_caixa_invalid_fires_before_versao_check() {
12645 // Order pin: an invalid-shape `:caixa` surfaces *its own*
12646 // diagnostic (which names the offending caixa name), even when
12647 // the same entry's `:versao` is also empty/invalid. The shape
12648 // gate runs first because the diagnostic is more self-locating —
12649 // an empty/invalid `:versao` on an invalid-shape caixa name is
12650 // a downstream-fix-after-the-caixa-rename concern.
12651 let mut s = three_member_spec();
12652 s.membros[1].caixa = "Cart".into();
12653 s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
12654 let err = s.validate().unwrap_err();
12655 assert!(
12656 matches!(
12657 err,
12658 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
12659 ),
12660 "got {err:?}"
12661 );
12662 }
12663
12664 #[test]
12665 fn membro_caixa_invalid_fires_before_duplicate_check() {
12666 // Order pin: a malformed-shape `:caixa` on an earlier entry
12667 // surfaces *its own* diagnostic, even when a later entry would
12668 // otherwise collapse onto a duplicate name. The per-entry shape
12669 // gate runs inline before the duplicate-key insert, parallel
12670 // to `membro_versao_invalid_fires_before_duplicate_check`.
12671 let mut s = three_member_spec();
12672 s.membros[0].caixa = "Catalog".into();
12673 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
12674 let err = s.validate().unwrap_err();
12675 assert!(
12676 matches!(
12677 err,
12678 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
12679 ),
12680 "got {err:?}"
12681 );
12682 }
12683
12684 #[test]
12685 fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
12686 // The diagnostic-shape pin: the error names the offending
12687 // `:caixa` value verbatim so the author can grep their
12688 // caixa.lisp without re-running the build, and carries a
12689 // non-empty `reason` naming the specific violation. Same
12690 // shape every typed-shape gate enshrines (c7d05ec's
12691 // `entrada_host_diagnostic_carries_offending_host`,
12692 // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
12693 let mut s = three_member_spec();
12694 s.membros[2].caixa = "BAD_NAME".into();
12695 let err = s.validate().unwrap_err();
12696 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
12697 panic!("expected MembroCaixaInvalid");
12698 };
12699 assert_eq!(caixa, "BAD_NAME");
12700 assert!(
12701 !reason.is_empty(),
12702 "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
12703 );
12704 }
12705
12706 #[test]
12707 fn rejects_contrato_with_unknown_de() {
12708 let mut s = three_member_spec();
12709 s.contratos.push(contract_http("phantom", "catalog", "/x"));
12710 let err = s.validate().unwrap_err();
12711 assert!(
12712 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
12713 );
12714 }
12715
12716 #[test]
12717 fn rejects_contrato_with_unknown_para() {
12718 let mut s = three_member_spec();
12719 s.contratos.push(contract_http("cart", "phantom", "/x"));
12720 let err = s.validate().unwrap_err();
12721 assert!(
12722 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
12723 );
12724 }
12725
12726 #[test]
12727 fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
12728 // The read-path pin: the phantom-`:de` refusal arm's
12729 // `ContratoMemberMissing.caixa` carrier must be observed through
12730 // the lifted [`WitContract::source`] accessor, not the raw
12731 // `.de.clone()` field-access `String`-carry. Peer of the sibling
12732 // per-`:contratos` self-loop arm's `.source().to_string()` /
12733 // `.world_ref().to_string()` `String`-carry sites the earlier
12734 // convergence lifted onto the same accessor pair. A future
12735 // silent detour that reintroduced the raw `.de.clone()` at the
12736 // wrap envelope while the shape-gate and membership lookup
12737 // routed through the accessor would surface here as a byte-equal
12738 // miss between the fired diagnostic's `caixa:` field and the
12739 // offending edge's `.source()` — pinning the accessor as the
12740 // sole read path across the phantom-name refusal arm's arg +
12741 // wrap-envelope emit surface.
12742 let mut s = three_member_spec();
12743 let phantom = contract_http("phantom", "catalog", "/x");
12744 s.contratos.push(phantom.clone());
12745 let err = s.validate().unwrap_err();
12746 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
12747 panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
12748 };
12749 assert_eq!(
12750 caixa,
12751 phantom.source(),
12752 "ContratoMemberMissing.caixa on the phantom-:de arm must \
12753 byte-equal WitContract::source — the wrap envelope must \
12754 route through the lifted accessor rather than the raw \
12755 .de.clone() field-access String-carry"
12756 );
12757 }
12758
12759 #[test]
12760 fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
12761 // The symmetric read-path pin on the `:para` phantom-name
12762 // refusal arm — same shape as the sibling `:de` pin above but
12763 // on the callee-Servico axis. Pins the wrap envelope's
12764 // `caixa:` field is observed through the lifted
12765 // [`WitContract::destination`] accessor, not the raw
12766 // `.para.clone()` field-access `String`-carry.
12767 let mut s = three_member_spec();
12768 let phantom = contract_http("cart", "phantom", "/x");
12769 s.contratos.push(phantom.clone());
12770 let err = s.validate().unwrap_err();
12771 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
12772 panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
12773 };
12774 assert_eq!(
12775 caixa,
12776 phantom.destination(),
12777 "ContratoMemberMissing.caixa on the phantom-:para arm must \
12778 byte-equal WitContract::destination — the wrap envelope \
12779 must route through the lifted accessor rather than the raw \
12780 .para.clone() field-access String-carry"
12781 );
12782 }
12783
12784 #[test]
12785 fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
12786 // The read-path pin on the `:de` DNS-1123-malformed shape-gate
12787 // refusal arm — the `validate_contrato_caixa` arg must be
12788 // observed through the lifted [`WitContract::source`] accessor,
12789 // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
12790 // value routes through the shared
12791 // [`crate::render::require_valid_dns_1123_label`] floor with the
12792 // accessor-projected value; the fired
12793 // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
12794 // the offending edge's `.source()`, pinning that the arg + the
12795 // downstream `caixa: caixa.to_string()` wrap route through the
12796 // same accessor's read path.
12797 let mut s = three_member_spec();
12798 let malformed = contract_http("BAD_NAME", "catalog", "/x");
12799 s.contratos.push(malformed.clone());
12800 let err = s.validate().unwrap_err();
12801 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
12802 panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
12803 };
12804 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
12805 assert_eq!(
12806 caixa,
12807 malformed.source(),
12808 "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
12809 byte-equal WitContract::source — the shape-gate arg + wrap \
12810 envelope must route through the lifted accessor rather \
12811 than the raw &c.de &String-borrow"
12812 );
12813 }
12814
12815 #[test]
12816 fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
12817 // Symmetric arm to the sibling `:de` malformed-shape pin above,
12818 // on the `:para` axis. Pins the shape-gate arg + wrap envelope
12819 // route through the lifted [`WitContract::destination`]
12820 // accessor. `:para` runs after the `:de` shape gate in the
12821 // canonical edge-direction order, so the `:de` value must be
12822 // well-shaped for the `:para` gate to fire — the `cart` :de is
12823 // canonical.
12824 let mut s = three_member_spec();
12825 let malformed = contract_http("cart", "BAD_NAME", "/x");
12826 s.contratos.push(malformed.clone());
12827 let err = s.validate().unwrap_err();
12828 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
12829 panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
12830 };
12831 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
12832 assert_eq!(
12833 caixa,
12834 malformed.destination(),
12835 "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
12836 byte-equal WitContract::destination — the shape-gate arg + \
12837 wrap envelope must route through the lifted accessor \
12838 rather than the raw &c.para &String-borrow"
12839 );
12840 }
12841
12842 // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
12843
12844 #[test]
12845 fn rejects_contrato_de_empty() {
12846 // `:de ""` previously fell through to `ContratoMemberMissing`
12847 // (with `caixa: ""`) because the validated `:membros :caixa`
12848 // set never contains the empty string. The narrower
12849 // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
12850 // the offending slot.
12851 let mut s = three_member_spec();
12852 s.contratos.push(contract_http("", "catalog", "/x"));
12853 let err = s.validate().unwrap_err();
12854 assert_eq!(
12855 err,
12856 AplicacaoError::ContratoCaixaEmpty {
12857 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
12858 },
12859 "got {err:?}"
12860 );
12861 }
12862
12863 #[test]
12864 fn rejects_contrato_para_empty() {
12865 // Symmetric arm to `:de ""` — `:para ""` previously fell
12866 // through to `ContratoMemberMissing { caixa: "" }`.
12867 let mut s = three_member_spec();
12868 s.contratos.push(contract_http("cart", "", "/x"));
12869 let err = s.validate().unwrap_err();
12870 assert_eq!(
12871 err,
12872 AplicacaoError::ContratoCaixaEmpty {
12873 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
12874 },
12875 "got {err:?}"
12876 );
12877 }
12878
12879 #[test]
12880 fn rejects_contrato_de_with_uppercase() {
12881 // The canonical "I copied the Servico's TitleCase display
12882 // name from an ADR" typo. Until this gate landed `:de "Cart"`
12883 // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
12884 // as "this caixa isn't in `:membros`" when the root cause is
12885 // "this `:de` value's shape can never legitimately match a
12886 // validated member (DNS-1123 labels are lowercase)". The
12887 // narrower diagnostic names the offending slot, the value
12888 // verbatim, and the parser-shaped reason.
12889 let mut s = three_member_spec();
12890 s.contratos.push(contract_http("Cart", "catalog", "/x"));
12891 let err = s.validate().unwrap_err();
12892 let AplicacaoError::ContratoCaixaInvalid {
12893 slot,
12894 caixa,
12895 reason,
12896 } = err
12897 else {
12898 panic!("expected ContratoCaixaInvalid, got other variant");
12899 };
12900 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
12901 assert_eq!(caixa, "Cart");
12902 assert!(
12903 reason.contains("uppercase"),
12904 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
12905 );
12906 }
12907
12908 #[test]
12909 fn rejects_contrato_para_with_underscore() {
12910 // The canonical "I'm thinking of a Python module" leak —
12911 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
12912 // Pin the `:para` axis surfaces the same diagnostic shape as
12913 // the `:de` axis on the underscore violation.
12914 let mut s = three_member_spec();
12915 s.contratos.push(contract_http("cart", "my_catalog", "/x"));
12916 let err = s.validate().unwrap_err();
12917 assert!(
12918 matches!(
12919 err,
12920 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
12921 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
12922 ),
12923 "got {err:?}"
12924 );
12925 }
12926
12927 #[test]
12928 fn rejects_contrato_de_with_dot() {
12929 // A `:contratos :de` value is a single DNS-1123 *label*, not
12930 // a subdomain — mirroring the `:membros :caixa` floor. The
12931 // strictest floor among the use sites wins.
12932 let mut s = three_member_spec();
12933 s.contratos
12934 .push(contract_http("team.cart", "catalog", "/x"));
12935 let err = s.validate().unwrap_err();
12936 assert!(
12937 matches!(
12938 err,
12939 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
12940 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
12941 ),
12942 "got {err:?}"
12943 );
12944 }
12945
12946 #[test]
12947 fn rejects_contrato_para_with_unicode() {
12948 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
12949 // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
12950 // validity check rejects multi-byte UTF-8 by the first
12951 // non-`[a-z0-9-]` byte.
12952 let mut s = three_member_spec();
12953 s.contratos.push(contract_http("cart", "café", "/x"));
12954 let err = s.validate().unwrap_err();
12955 assert!(
12956 matches!(
12957 err,
12958 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
12959 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
12960 ),
12961 "got {err:?}"
12962 );
12963 }
12964
12965 #[test]
12966 fn rejects_contrato_de_with_leading_hyphen() {
12967 // DNS-1123 boundary rule: labels must start and end with an
12968 // alphanumeric. K8s rejects `-cart` outright; the narrower
12969 // shape diagnostic now names the violation at caixa-build
12970 // time rather than the misframed membership-lookup arm.
12971 let mut s = three_member_spec();
12972 s.contratos.push(contract_http("-cart", "catalog", "/x"));
12973 let err = s.validate().unwrap_err();
12974 assert!(
12975 matches!(
12976 err,
12977 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
12978 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
12979 ),
12980 "got {err:?}"
12981 );
12982 }
12983
12984 #[test]
12985 fn contrato_de_empty_takes_precedence_over_invalid() {
12986 // Order pin: the `ContratoCaixaEmpty` arm fires before the
12987 // `ContratoCaixaInvalid` parse-side arm — same empty-first
12988 // cascade `validate_membro_caixa` / `validate_placement_cluster`
12989 // / `validate_entrada_host` already establish on their peer
12990 // name axes. The empty string is a structurally distinct
12991 // authoring footgun (the author left the field blank, vs.
12992 // typed a malformed value), so it gets its own diagnostic.
12993 let mut s = three_member_spec();
12994 s.contratos.push(contract_http("", "catalog", "/x"));
12995 let err = s.validate().unwrap_err();
12996 assert_eq!(
12997 err,
12998 AplicacaoError::ContratoCaixaEmpty {
12999 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
13000 }
13001 );
13002 }
13003
13004 #[test]
13005 fn contrato_de_shape_fires_before_para_shape() {
13006 // Per-axis order pin: within one `:contratos` entry, the `:de`
13007 // shape gate fires before the `:para` shape gate — same
13008 // edge-direction order the existing `ContratoMemberMissing` /
13009 // `ContratoSelfLoop` / target-dispatch checks use, so the
13010 // diagnostic for a contract with both `:de` and `:para`
13011 // malformed is stable. Authors fixing the surfaced `:de`
13012 // first will see `:para`'s diagnostic on re-run.
13013 let mut s = three_member_spec();
13014 s.contratos.push(contract_http("Cart", "Catalog", "/x"));
13015 let err = s.validate().unwrap_err();
13016 assert!(
13017 matches!(
13018 err,
13019 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
13020 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
13021 ),
13022 "got {err:?}"
13023 );
13024 }
13025
13026 #[test]
13027 fn contrato_shape_fires_before_membership_lookup() {
13028 // The load-bearing pin: an invalid-shape `:de` surfaces its
13029 // *own* diagnostic, not the misframed `ContratoMemberMissing`.
13030 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
13031 // an invalid-shape `:de` could never legitimately match any
13032 // member — the prior `ContratoMemberMissing` diagnostic was
13033 // a structural impossibility framed as a graph-membership
13034 // failure. The shape gate now routes every such input through
13035 // the narrower self-locating diagnostic.
13036 let mut s = three_member_spec();
13037 s.contratos.push(contract_http("Cart", "catalog", "/x"));
13038 let err = s.validate().unwrap_err();
13039 assert!(
13040 matches!(
13041 err,
13042 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
13043 ),
13044 "got {err:?}"
13045 );
13046 // And the symmetric case: an invalid-shape `:para` surfaces
13047 // its own diagnostic too, even when `:de` is well-shaped.
13048 let mut s = three_member_spec();
13049 s.contratos.push(contract_http("cart", "Catalog", "/x"));
13050 let err = s.validate().unwrap_err();
13051 assert!(
13052 matches!(
13053 err,
13054 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
13055 ),
13056 "got {err:?}"
13057 );
13058 }
13059
13060 #[test]
13061 fn contrato_shape_fires_before_self_edge_check() {
13062 // A `:de "Cart" :para "Cart"` entry is two distinct authoring
13063 // bugs: the shape violation (uppercase) and the self-edge
13064 // violation. The narrower per-axis shape diagnostic surfaces
13065 // first because fixing the shape may reveal that the author
13066 // also meant to point `:para` at a different member — the
13067 // self-edge framing is only useful once both endpoints have
13068 // valid shape.
13069 let mut s = three_member_spec();
13070 s.contratos.push(contract_http("Cart", "Cart", "/x"));
13071 let err = s.validate().unwrap_err();
13072 assert!(
13073 matches!(
13074 err,
13075 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
13076 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
13077 ),
13078 "got {err:?}"
13079 );
13080 }
13081
13082 #[test]
13083 fn contrato_well_shaped_phantom_still_raises_member_missing() {
13084 // Strict-improvement pin: a well-shaped `:de` that simply
13085 // isn't in `:membros` (a phantom reference — author meant
13086 // to add the member but didn't, or renamed and missed an
13087 // update) still surfaces `ContratoMemberMissing`, unchanged.
13088 // The shape gate only intercepts inputs that could never
13089 // legitimately match a validated member; legitimately-shaped
13090 // phantom references remain on the graph-membership axis.
13091 let mut s = three_member_spec();
13092 s.contratos
13093 .push(contract_http("phantom-shim", "catalog", "/x"));
13094 let err = s.validate().unwrap_err();
13095 assert!(
13096 matches!(
13097 err,
13098 AplicacaoError::ContratoMemberMissing { ref caixa }
13099 if caixa == "phantom-shim"
13100 ),
13101 "got {err:?}"
13102 );
13103 }
13104
13105 #[test]
13106 fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
13107 // The diagnostic-shape pin: the error names the offending
13108 // slot (`:de` or `:para`) verbatim and the offending value
13109 // verbatim plus a non-empty parser-shaped reason, so the
13110 // author can grep their caixa.lisp for `:de "<name>"` /
13111 // `:para "<name>"` and fix it in one edit. Same diagnostic
13112 // shape as `MembroCaixaInvalid` (3f9d7a0) and
13113 // `PlacementClusterInvalid` (6c8c00b).
13114 let mut s = three_member_spec();
13115 s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
13116 let err = s.validate().unwrap_err();
13117 let AplicacaoError::ContratoCaixaInvalid {
13118 slot,
13119 caixa,
13120 reason,
13121 } = err
13122 else {
13123 panic!("expected ContratoCaixaInvalid, got {err:?}");
13124 };
13125 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
13126 assert_eq!(caixa, "BAD_NAME");
13127 assert!(
13128 !reason.is_empty(),
13129 "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
13130 );
13131 }
13132
13133 #[test]
13134 fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
13135 // Scalar-value pin: the two author-facing kebab-case labels the
13136 // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
13137 // admits on the `:contratos` per-entry endpoint-shape axis,
13138 // one arm per typed sub-slot. Mirrors the peer scalar-value
13139 // pin the sibling top-level M2 / M3 / Supervisor
13140 // author-facing-label consts carry
13141 // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
13142 // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
13143 // slot itself), so every altitude of the typed-slot algebra
13144 // shares the same "one canonical byte-string per arm"
13145 // discipline. A future rebrand (`:de` → `:from` matching the
13146 // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
13147 // sibling, `:para` → `:to` matching the same, or
13148 // `:de`/`:para` → `:source`/`:target` matching the WIT
13149 // world's `import`/`export` half-vocabulary) lands as an
13150 // edit to exactly one const, and every consumer that reaches
13151 // for the label picks it up at build time rather than at
13152 // runtime as a downstream `ContratoCaixaEmpty` /
13153 // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
13154 // diagnostic mismatch far from the rename's commit.
13155 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
13156 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
13157 }
13158
13159 #[test]
13160 fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
13161 // Production-through-const pin: the two per-axis labels the
13162 // per-`:contratos` entry endpoint-shape gate at
13163 // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
13164 // argument to [`validate_contrato_caixa`] route through the
13165 // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
13166 // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
13167 // future rebrand that reaches the const but not the gate (or
13168 // vice versa) surfaces here at build time rather than at
13169 // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
13170 // `slot: <stale-kebab-case>` diagnostic far from the rename's
13171 // commit. Mirror of the peer
13172 // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
13173 // pin (882f498) on the sibling M3 top-level slot axis.
13174 let mut s = three_member_spec();
13175 s.contratos.push(contract_http("", "catalog", "/x"));
13176 assert_eq!(
13177 s.validate().unwrap_err(),
13178 AplicacaoError::ContratoCaixaEmpty {
13179 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
13180 }
13181 );
13182 let mut s = three_member_spec();
13183 s.contratos.push(contract_http("cart", "", "/x"));
13184 assert_eq!(
13185 s.validate().unwrap_err(),
13186 AplicacaoError::ContratoCaixaEmpty {
13187 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
13188 }
13189 );
13190 }
13191
13192 #[test]
13193 fn accepts_canonical_contrato_caixa_forms() {
13194 // The DNS-1123 label shapes a caixa author is realistically
13195 // going to write on a `:contratos :de` / `:para`. Pin every
13196 // leg so a future tightening that bans (e.g.) digit-start
13197 // identifiers surfaces here, mirroring
13198 // `accepts_canonical_membro_caixa_forms` on the peer name
13199 // axis.
13200 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
13201 let mut s = three_member_spec();
13202 s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
13203 s.contratos = vec![contract_http("checkout", form, "/x")];
13204 s.entrada = None;
13205 s.validate().unwrap_or_else(|e| {
13206 panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
13207 });
13208
13209 let mut s = three_member_spec();
13210 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
13211 s.contratos = vec![contract_http(form, "catalog", "/x")];
13212 s.entrada = None;
13213 s.validate().unwrap_or_else(|e| {
13214 panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
13215 });
13216 }
13217 }
13218
13219 #[test]
13220 fn rejects_empty_wit() {
13221 let mut s = three_member_spec();
13222 s.contratos.push(WitContract {
13223 de: "cart".into(),
13224 para: "catalog".into(),
13225 wit: String::new(),
13226 endpoint: None,
13227 subject: None,
13228 slot: None,
13229 });
13230 let err = s.validate().unwrap_err();
13231 assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
13232 }
13233
13234 #[test]
13235 fn rejects_entrada_to_unknown_member() {
13236 let mut s = three_member_spec();
13237 s.entrada.as_mut().unwrap().para = "phantom".into();
13238 assert!(matches!(
13239 s.validate().unwrap_err(),
13240 AplicacaoError::EntradaMemberMissing { .. }
13241 ));
13242 }
13243
13244 // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
13245
13246 #[test]
13247 fn rejects_entrada_para_empty() {
13248 // `:para ""` previously fell through to
13249 // `EntradaMemberMissing { para: "" }` because the validated
13250 // `:membros :caixa` set never contains the empty string. The
13251 // narrower `EntradaParaEmpty` diagnostic now names the
13252 // offending slot directly — same empty-first cascade
13253 // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
13254 // `ContratoCaixaEmpty` establish on the peer name axes.
13255 let mut s = three_member_spec();
13256 s.entrada.as_mut().unwrap().para = String::new();
13257 let err = s.validate().unwrap_err();
13258 assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
13259 }
13260
13261 #[test]
13262 fn rejects_entrada_para_with_uppercase() {
13263 // The canonical "I copied the Servico's TitleCase display
13264 // name from an ADR" typo. Until this gate landed `:para "Cart"`
13265 // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
13266 // as "this caixa isn't in `:membros`" when the root cause is
13267 // "this `:para` value's shape can never legitimately match a
13268 // validated member (DNS-1123 labels are lowercase)". The
13269 // narrower diagnostic names the value verbatim plus the
13270 // parser-shaped reason.
13271 let mut s = three_member_spec();
13272 s.entrada.as_mut().unwrap().para = "Cart".into();
13273 let err = s.validate().unwrap_err();
13274 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
13275 panic!("expected EntradaParaInvalid, got other variant");
13276 };
13277 assert_eq!(para, "Cart");
13278 assert!(
13279 reason.contains("uppercase"),
13280 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
13281 );
13282 }
13283
13284 #[test]
13285 fn rejects_entrada_para_with_underscore() {
13286 // The canonical "I'm thinking of a Python module" leak —
13287 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
13288 let mut s = three_member_spec();
13289 s.entrada.as_mut().unwrap().para = "my_cart".into();
13290 let err = s.validate().unwrap_err();
13291 assert!(
13292 matches!(
13293 err,
13294 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
13295 if para == "my_cart" && reason.contains('_')
13296 ),
13297 "got {err:?}"
13298 );
13299 }
13300
13301 #[test]
13302 fn rejects_entrada_para_with_dot() {
13303 // An `:entrada :para` value is a single DNS-1123 *label*, not
13304 // a subdomain — mirroring the `:membros :caixa` floor. The
13305 // strictest floor among the use sites wins.
13306 let mut s = three_member_spec();
13307 s.entrada.as_mut().unwrap().para = "team.cart".into();
13308 let err = s.validate().unwrap_err();
13309 assert!(
13310 matches!(
13311 err,
13312 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
13313 if para == "team.cart" && reason.contains('.')
13314 ),
13315 "got {err:?}"
13316 );
13317 }
13318
13319 #[test]
13320 fn rejects_entrada_para_with_unicode() {
13321 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
13322 // (`xn--…`) before it reaches K8s.
13323 let mut s = three_member_spec();
13324 s.entrada.as_mut().unwrap().para = "café".into();
13325 let err = s.validate().unwrap_err();
13326 assert!(
13327 matches!(
13328 err,
13329 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
13330 ),
13331 "got {err:?}"
13332 );
13333 }
13334
13335 #[test]
13336 fn rejects_entrada_para_with_leading_hyphen() {
13337 // DNS-1123 boundary rule: labels must start and end with an
13338 // alphanumeric. K8s rejects `-cart` outright.
13339 let mut s = three_member_spec();
13340 s.entrada.as_mut().unwrap().para = "-cart".into();
13341 let err = s.validate().unwrap_err();
13342 assert!(
13343 matches!(
13344 err,
13345 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
13346 if para == "-cart" && reason.contains("start and end")
13347 ),
13348 "got {err:?}"
13349 );
13350 }
13351
13352 #[test]
13353 fn rejects_entrada_para_with_trailing_hyphen() {
13354 // Symmetric boundary arm.
13355 let mut s = three_member_spec();
13356 s.entrada.as_mut().unwrap().para = "cart-".into();
13357 let err = s.validate().unwrap_err();
13358 assert!(
13359 matches!(
13360 err,
13361 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
13362 if para == "cart-" && reason.contains("start and end")
13363 ),
13364 "got {err:?}"
13365 );
13366 }
13367
13368 #[test]
13369 fn rejects_entrada_para_too_long() {
13370 // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
13371 // bytes per label. K8s rejects longer names at admission on
13372 // every `metadata.name` axis.
13373 let mut s = three_member_spec();
13374 s.entrada.as_mut().unwrap().para = "a".repeat(64);
13375 let err = s.validate().unwrap_err();
13376 assert!(
13377 matches!(
13378 err,
13379 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
13380 if para.len() == 64 && reason.contains("max length")
13381 ),
13382 "got {err:?}"
13383 );
13384 }
13385
13386 #[test]
13387 fn entrada_para_empty_takes_precedence_over_invalid() {
13388 // Order pin: the `EntradaParaEmpty` arm fires before the
13389 // `EntradaParaInvalid` parse-side arm — same empty-first
13390 // cascade `validate_membro_caixa` / `validate_placement_cluster`
13391 // / `validate_contrato_caixa` already establish.
13392 let mut s = three_member_spec();
13393 s.entrada.as_mut().unwrap().para = String::new();
13394 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
13395 }
13396
13397 #[test]
13398 fn entrada_para_shape_fires_before_membership_lookup() {
13399 // The load-bearing pin: an invalid-shape `:para` surfaces its
13400 // *own* diagnostic, not the misframed `EntradaMemberMissing`.
13401 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
13402 // an invalid-shape `:para` could never legitimately match any
13403 // member — the prior `EntradaMemberMissing` diagnostic framed
13404 // a structural impossibility as a graph-membership failure.
13405 let mut s = three_member_spec();
13406 s.entrada.as_mut().unwrap().para = "Cart".into();
13407 let err = s.validate().unwrap_err();
13408 assert!(
13409 matches!(
13410 err,
13411 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
13412 ),
13413 "got {err:?}"
13414 );
13415 }
13416
13417 #[test]
13418 fn entrada_para_shape_fires_before_host_gate() {
13419 // Per-`:entrada` order pin: the `:para` shape gate fires
13420 // before the `:host` gate, mirroring the existing
13421 // `entrada_host_member_missing_takes_precedence_over_host_invalid`
13422 // ordering where the member-lookup arm preceded the host gate.
13423 // The shape gate slots ahead of that, so a malformed `:para`
13424 // surfaces its own diagnostic even when `:host` is also wrong.
13425 let mut s = three_member_spec();
13426 let e = s.entrada.as_mut().unwrap();
13427 e.para = "Cart".into();
13428 e.host = "BAD HOST".into();
13429 let err = s.validate().unwrap_err();
13430 assert!(
13431 matches!(
13432 err,
13433 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
13434 ),
13435 "got {err:?}"
13436 );
13437 }
13438
13439 #[test]
13440 fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
13441 // Strict-improvement pin: a well-shaped `:para` that simply
13442 // isn't in `:membros` (a phantom reference — author meant to
13443 // add the member but didn't, or renamed and missed an
13444 // update) still surfaces `EntradaMemberMissing`, unchanged.
13445 // The shape gate only intercepts inputs that could never
13446 // legitimately match a validated member.
13447 let mut s = three_member_spec();
13448 s.entrada.as_mut().unwrap().para = "phantom-shim".into();
13449 let err = s.validate().unwrap_err();
13450 assert!(
13451 matches!(
13452 err,
13453 AplicacaoError::EntradaMemberMissing { ref para }
13454 if para == "phantom-shim"
13455 ),
13456 "got {err:?}"
13457 );
13458 }
13459
13460 #[test]
13461 fn entrada_para_invalid_diagnostic_carries_offending_para() {
13462 // The diagnostic-shape pin: the error names the offending
13463 // `:para` value verbatim plus a non-empty parser-shaped
13464 // reason, so the author can grep their caixa.lisp for
13465 // `:para "<name>"` and fix it in one edit. Same diagnostic
13466 // shape as `MembroCaixaInvalid` (3f9d7a0),
13467 // `PlacementClusterInvalid` (6c8c00b), and
13468 // `ContratoCaixaInvalid` (8d5af6b).
13469 let mut s = three_member_spec();
13470 s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
13471 let err = s.validate().unwrap_err();
13472 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
13473 panic!("expected EntradaParaInvalid, got {err:?}");
13474 };
13475 assert_eq!(para, "BAD_NAME");
13476 assert!(
13477 !reason.is_empty(),
13478 "EntradaParaInvalid `reason` must carry a parser-shaped wording"
13479 );
13480 }
13481
13482 #[test]
13483 fn accepts_canonical_entrada_para_forms() {
13484 // Positive-control sweep covering the DNS-1123 label shapes a
13485 // caixa author is realistically going to write on `:entrada
13486 // :para`. Pin every leg so a future tightening that bans
13487 // (e.g.) digit-start identifiers surfaces here, mirroring
13488 // `accepts_canonical_membro_caixa_forms` and
13489 // `accepts_canonical_contrato_caixa_forms` on the peer name
13490 // axes.
13491 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
13492 let mut s = three_member_spec();
13493 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
13494 s.contratos = vec![contract_http(form, "catalog", "/x")];
13495 s.entrada = Some(Entrada {
13496 host: "checkout.quero.cloud".into(),
13497 para: form.into(),
13498 paths: vec!["/api".into()],
13499 port: 8080,
13500 });
13501 s.validate().unwrap_or_else(|e| {
13502 panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
13503 });
13504 }
13505 }
13506
13507 #[test]
13508 fn rejects_replicated_without_clusters() {
13509 let mut s = three_member_spec();
13510 s.placement.clusters = vec![];
13511 assert!(matches!(
13512 s.validate().unwrap_err(),
13513 AplicacaoError::PlacementWithoutClusters { .. }
13514 ));
13515 }
13516
13517 #[test]
13518 fn rejects_sharded_without_key() {
13519 let mut s = three_member_spec();
13520 s.placement.estrategia = PlacementStrategy::Sharded;
13521 s.placement.shard_key = None;
13522 s.placement.clusters = vec!["rio".into()];
13523 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
13524 }
13525
13526 #[test]
13527 fn sharded_with_key_validates() {
13528 let mut s = three_member_spec();
13529 s.placement.estrategia = PlacementStrategy::Sharded;
13530 s.placement.shard_key = Some("$tenantId".into());
13531 s.validate().unwrap();
13532 }
13533
13534 #[test]
13535 fn round_trip_via_json_preserves_shape() {
13536 let s = three_member_spec();
13537 let json = serde_json::to_string(&s.membros).unwrap();
13538 let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
13539 assert_eq!(back, s.membros);
13540
13541 let json = serde_json::to_string(&s.contratos).unwrap();
13542 let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
13543 assert_eq!(back, s.contratos);
13544
13545 let json = serde_json::to_string(&s.placement).unwrap();
13546 let back: Placement = serde_json::from_str(&json).unwrap();
13547 assert_eq!(back, s.placement);
13548
13549 let json = serde_json::to_string(&s.entrada).unwrap();
13550 let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
13551 assert_eq!(back, s.entrada);
13552 }
13553
13554 #[test]
13555 fn rate_limit_round_trip_seconds() {
13556 let policy = MeshPolicy {
13557 rate_limit: Some(RateLimit {
13558 rate: 100,
13559 window: Duration::from_secs(1),
13560 }),
13561 ..Default::default()
13562 };
13563 let json = serde_json::to_string(&policy).unwrap();
13564 assert!(json.contains("\"100/s\""));
13565 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13566 assert_eq!(back.rate_limit.unwrap().rate, 100);
13567 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
13568 }
13569
13570 #[test]
13571 fn rate_limit_round_trip_minutes() {
13572 let policy = MeshPolicy {
13573 rate_limit: Some(RateLimit {
13574 rate: 5000,
13575 window: Duration::from_secs(60),
13576 }),
13577 ..Default::default()
13578 };
13579 let json = serde_json::to_string(&policy).unwrap();
13580 assert!(json.contains("\"5000/m\""));
13581 }
13582
13583 #[test]
13584 fn circuit_breaker_round_trip() {
13585 let policy = MeshPolicy {
13586 circuit_breaker: Some(CircuitBreaker {
13587 max_failures: 5,
13588 window: Duration::from_secs(60),
13589 }),
13590 ..Default::default()
13591 };
13592 let json = serde_json::to_string(&policy).unwrap();
13593 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13594 assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
13595 assert_eq!(
13596 back.circuit_breaker.unwrap().window,
13597 Duration::from_secs(60)
13598 );
13599 }
13600
13601 #[test]
13602 fn rejects_http_contrato_without_endpoint() {
13603 let mut s = three_member_spec();
13604 s.contratos.push(WitContract {
13605 de: "cart".into(),
13606 para: "catalog".into(),
13607 wit: "wasi:http/proxy".into(),
13608 endpoint: None,
13609 subject: None,
13610 slot: None,
13611 });
13612 let err = s.validate().unwrap_err();
13613 assert!(matches!(
13614 err,
13615 AplicacaoError::ContratoMissingTarget {
13616 expected: WitTarget::HTTP_FIELD_NAME,
13617 ..
13618 }
13619 ));
13620 }
13621
13622 #[test]
13623 fn rejects_http_contrato_with_subject() {
13624 let mut s = three_member_spec();
13625 s.contratos.push(WitContract {
13626 de: "cart".into(),
13627 para: "catalog".into(),
13628 wit: "wasi:http/proxy".into(),
13629 endpoint: Some("/x".into()),
13630 subject: Some("not.allowed.here".into()),
13631 slot: None,
13632 });
13633 let err = s.validate().unwrap_err();
13634 assert!(matches!(
13635 err,
13636 AplicacaoError::ContratoWrongTarget {
13637 expected: WitTarget::HTTP_FIELD_NAME,
13638 ..
13639 }
13640 ));
13641 }
13642
13643 #[test]
13644 fn rejects_pubsub_contrato_without_subject() {
13645 let mut s = three_member_spec();
13646 s.contratos.push(WitContract {
13647 de: "cart".into(),
13648 para: "catalog".into(),
13649 wit: "nats:pub-sub".into(),
13650 endpoint: None,
13651 subject: None,
13652 slot: None,
13653 });
13654 let err = s.validate().unwrap_err();
13655 assert!(matches!(
13656 err,
13657 AplicacaoError::ContratoMissingTarget {
13658 expected: WitTarget::PUBSUB_FIELD_NAME,
13659 ..
13660 }
13661 ));
13662 }
13663
13664 #[test]
13665 fn rejects_pubsub_contrato_with_endpoint() {
13666 let mut s = three_member_spec();
13667 s.contratos.push(WitContract {
13668 de: "cart".into(),
13669 para: "catalog".into(),
13670 wit: "kafka:topic".into(),
13671 endpoint: Some("/wrong".into()),
13672 subject: Some("topic.x".into()),
13673 slot: None,
13674 });
13675 let err = s.validate().unwrap_err();
13676 assert!(matches!(
13677 err,
13678 AplicacaoError::ContratoWrongTarget {
13679 expected: WitTarget::PUBSUB_FIELD_NAME,
13680 ..
13681 }
13682 ));
13683 }
13684
13685 #[test]
13686 fn rejects_store_contrato_without_slot() {
13687 let mut s = three_member_spec();
13688 s.contratos.push(WitContract {
13689 de: "cart".into(),
13690 para: "catalog".into(),
13691 wit: "wasi:keyvalue/store".into(),
13692 endpoint: None,
13693 subject: None,
13694 slot: None,
13695 });
13696 let err = s.validate().unwrap_err();
13697 assert!(matches!(
13698 err,
13699 AplicacaoError::ContratoMissingTarget {
13700 expected: WitTarget::STORE_FIELD_NAME,
13701 ..
13702 }
13703 ));
13704 }
13705
13706 // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
13707
13708 #[test]
13709 fn rejects_http_contrato_with_empty_endpoint() {
13710 // `Some("")` for an HTTP endpoint passes the presence check
13711 // (target() previously returned WitTarget::Http { endpoint: "" })
13712 // but renders as a `path: ""` Cilium L7 rule that matches no
13713 // traffic. Same value-shape footgun closed for :entrada :paths
13714 // entries (eb3456d).
13715 let mut s = three_member_spec();
13716 s.contratos.push(WitContract {
13717 de: "cart".into(),
13718 para: "catalog".into(),
13719 wit: "wasi:http/proxy".into(),
13720 endpoint: Some(String::new()),
13721 subject: None,
13722 slot: None,
13723 });
13724 let err = s.validate().unwrap_err();
13725 assert!(
13726 matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
13727 if de == "cart" && para == "catalog"),
13728 "got {err:?}"
13729 );
13730 }
13731
13732 #[test]
13733 fn rejects_http_contrato_with_relative_endpoint() {
13734 // Cilium L7 :path + Gateway API PathPrefix both require a
13735 // leading `/`. Same shape required of :entrada :paths
13736 // (eb3456d). Lifted into target() so every consumer of the
13737 // typed WitTarget view inherits the guarantee.
13738 let mut s = three_member_spec();
13739 s.contratos.push(WitContract {
13740 de: "cart".into(),
13741 para: "catalog".into(),
13742 wit: "wasi:http/proxy".into(),
13743 endpoint: Some("products/:id".into()),
13744 subject: None,
13745 slot: None,
13746 });
13747 let err = s.validate().unwrap_err();
13748 assert!(
13749 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
13750 if endpoint == "products/:id"),
13751 "got {err:?}"
13752 );
13753 }
13754
13755 #[test]
13756 fn rejects_pubsub_contrato_with_empty_subject() {
13757 // NATS / Kafka publish without a subject is a no-op subscribe;
13758 // never the author's intent. Same empty-string rejection as
13759 // :membros :caixa, :placement :clusters entries, :entrada
13760 // :paths entries — every value carried by every typed slot is
13761 // value-shape-checked at validate().
13762 let mut s = three_member_spec();
13763 s.contratos.push(WitContract {
13764 de: "cart".into(),
13765 para: "catalog".into(),
13766 wit: "nats:pub-sub".into(),
13767 endpoint: None,
13768 subject: Some(String::new()),
13769 slot: None,
13770 });
13771 let err = s.validate().unwrap_err();
13772 assert!(
13773 matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
13774 if de == "cart" && para == "catalog"),
13775 "got {err:?}"
13776 );
13777 }
13778
13779 #[test]
13780 fn rejects_store_contrato_with_empty_slot() {
13781 // An empty slot template addresses the bucket root, defeating
13782 // the per-key isolation the slot exists for — a footgun on
13783 // `wasi:keyvalue/store` whose closest analog is the empty
13784 // shard-key rejected on :placement Sharded (c7c7799).
13785 let mut s = three_member_spec();
13786 s.contratos.push(WitContract {
13787 de: "cart".into(),
13788 para: "catalog".into(),
13789 wit: "wasi:keyvalue/store".into(),
13790 endpoint: None,
13791 subject: None,
13792 slot: Some(String::new()),
13793 });
13794 let err = s.validate().unwrap_err();
13795 assert!(
13796 matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
13797 if de == "cart" && para == "catalog"),
13798 "got {err:?}"
13799 );
13800 }
13801
13802 #[test]
13803 fn http_contrato_root_endpoint_validates() {
13804 // Pin the boundary case: a single-`/` endpoint is the catch-all
13805 // form the Gateway HTTPRoute renderer falls back to when
13806 // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
13807 // must remain a valid contrato endpoint too.
13808 let mut s = three_member_spec();
13809 s.contratos.push(contract_http("cart", "catalog", "/"));
13810 s.validate().unwrap();
13811 }
13812
13813 // ── :contratos :endpoint value-shape gate ────────────────────────────
13814 //
13815 // Mirrors the `:entrada :paths` value-shape suite on the peer
13816 // HTTP-path axis. Until this gate landed `WitContract::target()`
13817 // only refused the empty string + the missing-leading-`/` form
13818 // (c4213a4); a structurally invalid endpoint passed validate and
13819 // landed verbatim as a Cilium L7 `path:` rule
13820 // (caixa-mesh/src/lib.rs:311) that either silently dropped all
13821 // traffic or was rejected at apply time by Cilium policy admission.
13822 // Every authoring footgun the K8s Gateway API webhook / Cilium
13823 // policy validator would catch on admission now becomes a caixa-
13824 // build-time `ContratoEndpointInvalid` with the offending
13825 // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
13826 // shape as `EntradaPathInvalid` on the sibling axis; same shared
13827 // predicate (`crate::render::is_gateway_api_http_path`) ensures
13828 // drift between the two axes' rule enforcement is a build error
13829 // at the predicate.
13830
13831 fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
13832 // Fresh spec per call so the would-be-duplicate edge
13833 // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
13834 // `three_member_spec`'s pre-existing
13835 // `(cart, catalog, …, /products/:id)` entry — only the
13836 // endpoint payload differs.
13837 let mut s = three_member_spec();
13838 s.contratos.push(contract_http("cart", "catalog", ep));
13839 s.validate().unwrap_err()
13840 }
13841
13842 #[test]
13843 fn rejects_http_contrato_endpoint_with_query() {
13844 // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
13845 // silently rendered as a Cilium L7 `path: "/charge?token=X"`
13846 // rule the L7 matcher would never satisfy.
13847 let err = contrato_endpoint_err("/charge?token=X");
13848 assert!(
13849 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13850 if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
13851 "got {err:?}"
13852 );
13853 }
13854
13855 #[test]
13856 fn rejects_http_contrato_endpoint_with_fragment() {
13857 let err = contrato_endpoint_err("/charge#frag");
13858 assert!(
13859 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13860 if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
13861 "got {err:?}"
13862 );
13863 }
13864
13865 #[test]
13866 fn rejects_http_contrato_endpoint_with_whitespace() {
13867 let err = contrato_endpoint_err("/foo bar");
13868 assert!(
13869 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13870 if endpoint == "/foo bar" && reason.contains("whitespace")),
13871 "got {err:?}"
13872 );
13873 }
13874
13875 #[test]
13876 fn rejects_http_contrato_endpoint_with_control_char() {
13877 let err = contrato_endpoint_err("/api/\x01bar");
13878 assert!(
13879 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13880 if endpoint == "/api/\x01bar" && reason.contains("control character")),
13881 "got {err:?}"
13882 );
13883 }
13884
13885 #[test]
13886 fn rejects_http_contrato_endpoint_with_non_ascii() {
13887 let err = contrato_endpoint_err("/api/café");
13888 assert!(
13889 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13890 if endpoint == "/api/café" && reason.contains("non-ASCII")),
13891 "got {err:?}"
13892 );
13893 }
13894
13895 #[test]
13896 fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
13897 let err = contrato_endpoint_err("/api//cart");
13898 assert!(
13899 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13900 if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
13901 "got {err:?}"
13902 );
13903 }
13904
13905 #[test]
13906 fn rejects_http_contrato_endpoint_with_dot_segment() {
13907 let err = contrato_endpoint_err("/api/./cart");
13908 assert!(
13909 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13910 if endpoint == "/api/./cart" && reason.contains("`.` segment")),
13911 "got {err:?}"
13912 );
13913 }
13914
13915 #[test]
13916 fn rejects_http_contrato_endpoint_with_parent_segment() {
13917 // Path-traversal in a contrato endpoint is the canonical
13918 // "L7 rule that the workload's HTTP server's path-resolution
13919 // logic interprets differently than the policy enforcer"
13920 // footgun. Rejected outright at validate time.
13921 let err = contrato_endpoint_err("/api/../etc");
13922 assert!(
13923 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13924 if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
13925 "got {err:?}"
13926 );
13927 }
13928
13929 #[test]
13930 fn rejects_http_contrato_endpoint_too_long() {
13931 // 1025-byte endpoint — one over the Gateway API
13932 // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
13933 // path matcher has no inherent length limit but the policy
13934 // CR itself rides through the K8s apiserver, which enforces
13935 // ConfigMap-shaped limits; sharing the Gateway API cap is the
13936 // conservative floor.
13937 let big = format!("/api/{}", "a".repeat(1020));
13938 assert_eq!(big.len(), 1025);
13939 let err = contrato_endpoint_err(&big);
13940 assert!(
13941 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13942 if endpoint == &big && reason.contains("max length of 1024")),
13943 "got {err:?}"
13944 );
13945 }
13946
13947 #[test]
13948 fn http_contrato_endpoint_max_length_validates() {
13949 // 1024-byte endpoint — exactly the cap. Boundary pin: drift
13950 // in the cap surfaces here and at
13951 // `rejects_http_contrato_endpoint_too_long` simultaneously,
13952 // mirroring `entrada_path_max_length_validates` on the peer
13953 // axis.
13954 let big = format!("/api/{}", "a".repeat(1019));
13955 assert_eq!(big.len(), 1024);
13956 let mut s = three_member_spec();
13957 s.contratos.push(contract_http("cart", "catalog", &big));
13958 s.validate().unwrap();
13959 }
13960
13961 #[test]
13962 fn http_contrato_endpoint_accepts_canonical_forms() {
13963 // Positive-set sweep: every canonical HTTP-path shape the
13964 // sibling `:entrada :paths` axis accepts (the bare-root `/`,
13965 // plain paths, hidden-file-style `.config` segments distinct
13966 // from the `.` segment, digit-bearing segments, the canonical
13967 // route-template `:param` form, trailing-slash form,
13968 // percent-encoded segments, the `/foo..bar` interior-`..`-
13969 // substring forms that are NOT `..` segments) must remain a
13970 // valid contrato endpoint too. Drift between this list and
13971 // the entrada path positive sweep surfaces at the shared
13972 // `is_gateway_api_http_path` substrate-side suite — one
13973 // source of truth. Uses a fresh `(payment, catalog)` edge so
13974 // none of the swept endpoints collide with the pre-existing
13975 // `(cart, catalog, /products/:id)` / `(cart, payment,
13976 // /charge)` entries in `three_member_spec`.
13977 for ep in [
13978 "/",
13979 "/charge",
13980 "/v1/charge",
13981 "/api/.config",
13982 "/products/:id",
13983 "/api/cart/",
13984 "/api/caf%C3%A9",
13985 "/foo..bar",
13986 "/...",
13987 ] {
13988 let mut s = three_member_spec();
13989 s.contratos.push(contract_http("payment", "catalog", ep));
13990 s.validate()
13991 .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
13992 }
13993 }
13994
13995 #[test]
13996 fn contrato_endpoint_empty_takes_precedence_over_invalid() {
13997 // Ordering pin: `ContratoEndpointEmpty` is the more self-
13998 // locating diagnostic on `""` and must lead — the value-
13999 // shape gate is only reached after the empty-check fires.
14000 // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
14001 // on the peer axis.
14002 let mut s = three_member_spec();
14003 s.contratos.push(WitContract {
14004 de: "cart".into(),
14005 para: "catalog".into(),
14006 wit: "wasi:http/proxy".into(),
14007 endpoint: Some(String::new()),
14008 subject: None,
14009 slot: None,
14010 });
14011 let err = s.validate().unwrap_err();
14012 assert!(
14013 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
14014 "got {err:?}"
14015 );
14016 }
14017
14018 #[test]
14019 fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
14020 // Ordering pin: an endpoint without a leading `/` surfaces the
14021 // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
14022 // value-shape gate is only consulted on endpoints that already
14023 // satisfy the absolute-prefix invariant. Mirrors
14024 // `entrada_path_not_absolute_takes_precedence_over_invalid`.
14025 let err = contrato_endpoint_err("bad path");
14026 assert!(
14027 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
14028 if endpoint == "bad path"),
14029 "got {err:?}"
14030 );
14031 }
14032
14033 #[test]
14034 fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
14035 // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
14036 // `:para` + a non-empty reason flow through verbatim so the
14037 // author can grep their caixa.lisp for the offending contrato
14038 // block and fix it in one edit. Same shape as
14039 // `entrada_path_diagnostic_carries_offending_path`.
14040 let err = contrato_endpoint_err("/api?q=1");
14041 match err {
14042 AplicacaoError::ContratoEndpointInvalid {
14043 de,
14044 para,
14045 endpoint,
14046 reason,
14047 } => {
14048 assert_eq!(de, "cart");
14049 assert_eq!(para, "catalog");
14050 assert_eq!(endpoint, "/api?q=1");
14051 assert!(!reason.is_empty(), "reason field must be non-empty");
14052 }
14053 other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
14054 }
14055 }
14056
14057 #[test]
14058 fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
14059 // The compounding theorem: every &str inside a WitTarget
14060 // returned by target() is non-empty (and absolute, for Http).
14061 // Renderers downstream of typed_view() can rely on this
14062 // without re-checking — the type system carries the proof.
14063 let http = contract_http("cart", "catalog", "/x");
14064 match http.target().unwrap() {
14065 WitTarget::Http { endpoint } => {
14066 assert!(!endpoint.is_empty());
14067 assert!(endpoint.starts_with('/'));
14068 }
14069 other => panic!("expected Http, got {other:?}"),
14070 }
14071 let nats = WitContract {
14072 de: "a".into(),
14073 para: "b".into(),
14074 wit: "nats:pub-sub".into(),
14075 endpoint: None,
14076 subject: Some("topic.x".into()),
14077 slot: None,
14078 };
14079 match nats.target().unwrap() {
14080 WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
14081 other => panic!("expected PubSub, got {other:?}"),
14082 }
14083 let kv = WitContract {
14084 de: "a".into(),
14085 para: "b".into(),
14086 wit: "wasi:keyvalue/store".into(),
14087 endpoint: None,
14088 subject: None,
14089 slot: Some("checkout/$orderId".into()),
14090 };
14091 match kv.target().unwrap() {
14092 WitTarget::Store { slot } => assert!(!slot.is_empty()),
14093 other => panic!("expected Store, got {other:?}"),
14094 }
14095 }
14096
14097 #[test]
14098 fn target_diagnostic_names_offending_endpoint_value() {
14099 // When the malformed endpoint string is non-trivial, the
14100 // diagnostic carries the actual value back to the author —
14101 // not a generic "endpoint malformed" error.
14102 let bad = WitContract {
14103 de: "src".into(),
14104 para: "dst".into(),
14105 wit: "wasi:http/proxy".into(),
14106 endpoint: Some("api/v1/charge".into()),
14107 subject: None,
14108 slot: None,
14109 };
14110 match bad.target().unwrap_err() {
14111 AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
14112 assert_eq!(de, "src");
14113 assert_eq!(para, "dst");
14114 assert_eq!(endpoint, "api/v1/charge");
14115 }
14116 other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
14117 }
14118 }
14119
14120 #[test]
14121 fn rejects_unknown_wit_with_target_set() {
14122 let mut s = three_member_spec();
14123 s.contratos.push(WitContract {
14124 de: "cart".into(),
14125 para: "catalog".into(),
14126 wit: "custom:exchange".into(),
14127 endpoint: Some("/leaked".into()),
14128 subject: None,
14129 slot: None,
14130 });
14131 let err = s.validate().unwrap_err();
14132 assert!(matches!(
14133 err,
14134 AplicacaoError::ContratoWrongTarget {
14135 expected: WitTarget::CAPABILITY_EXPECTED,
14136 ..
14137 }
14138 ));
14139 }
14140
14141 #[test]
14142 fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
14143 // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
14144 // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
14145 // fourth arm of the same "which payload field name goes in the
14146 // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
14147 // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14148 // consts cover on the peer HTTP / PubSub / Store arms
14149 // (`wit_target_field_name_pins_per_variant`). Until this lift
14150 // landed the byte-string sat twice — once inline in the
14151 // [`WitContract::target`] Capability-arm rejection at the
14152 // production dispatch, once in `rejects_unknown_wit_with_target_set`
14153 // pinning against the same literal — with no compile-time link
14154 // between them. Same "one canonical declaration, next to the
14155 // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
14156 // lift established for the payload-less arm's human-readable
14157 // label axis; this test is the shape peer of
14158 // `wit_target_label_pins_per_variant`'s Capability-arm assertion
14159 // pair (routes-through-const + scalar-value pin) on the
14160 // wrong-target diagnostic-scalar axis.
14161 //
14162 // Fail-before-pass-after was verified locally by mutating the
14163 // const declaration to `"capability"` — the scalar-value pin
14164 // below fires (`"capability" != "none"`) and the routes-through
14165 // assertion below still holds (production and const walk in
14166 // lockstep), which is the correct behavior: a rename on the
14167 // const drifts here first, not at a downstream consumer.
14168 assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
14169
14170 let mut s = three_member_spec();
14171 s.contratos.push(WitContract {
14172 de: "cart".into(),
14173 para: "catalog".into(),
14174 wit: "custom:exchange".into(),
14175 endpoint: Some("/leaked".into()),
14176 subject: None,
14177 slot: None,
14178 });
14179 match s.validate().unwrap_err() {
14180 AplicacaoError::ContratoWrongTarget { expected, .. } => {
14181 assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
14182 }
14183 other => panic!("expected ContratoWrongTarget, got {other:?}"),
14184 }
14185 }
14186
14187 #[test]
14188 fn unknown_wit_capability_only_validates() {
14189 let mut s = three_member_spec();
14190 s.contratos.push(WitContract {
14191 de: "cart".into(),
14192 para: "catalog".into(),
14193 // A WIT world we haven't yet shaped — accept it as a typed
14194 // capability edge so authors aren't blocked while the WIT
14195 // registry catches up. No payload field may be carried.
14196 wit: "custom:exchange".into(),
14197 endpoint: None,
14198 subject: None,
14199 slot: None,
14200 });
14201 s.validate().unwrap();
14202 let added = s.contratos.last().unwrap();
14203 assert_eq!(added.target().unwrap(), WitTarget::Capability);
14204 }
14205
14206 #[test]
14207 fn target_typed_view_round_trips_each_shape() {
14208 let http = contract_http("cart", "catalog", "/products/:id");
14209 assert_eq!(
14210 http.target().unwrap(),
14211 WitTarget::Http {
14212 endpoint: "/products/:id"
14213 }
14214 );
14215 let nats = WitContract {
14216 de: "a".into(),
14217 para: "b".into(),
14218 wit: "nats:pub-sub".into(),
14219 endpoint: None,
14220 subject: Some("topic.x".into()),
14221 slot: None,
14222 };
14223 assert_eq!(
14224 nats.target().unwrap(),
14225 WitTarget::PubSub { subject: "topic.x" }
14226 );
14227 let kv = WitContract {
14228 de: "a".into(),
14229 para: "b".into(),
14230 wit: "wasi:keyvalue/store".into(),
14231 endpoint: None,
14232 subject: None,
14233 slot: Some("checkout/$orderId".into()),
14234 };
14235 assert_eq!(
14236 kv.target().unwrap(),
14237 WitTarget::Store {
14238 slot: "checkout/$orderId"
14239 }
14240 );
14241 }
14242
14243 #[test]
14244 fn wit_contract_kind_predicates() {
14245 let http = contract_http("a", "b", "/x");
14246 assert!(http.is_http());
14247 assert!(!http.is_pubsub());
14248 assert!(!http.is_store());
14249 assert!(!http.is_capability());
14250
14251 let nats = WitContract {
14252 de: "a".into(),
14253 para: "b".into(),
14254 wit: "nats:pub-sub".into(),
14255 endpoint: None,
14256 subject: Some("topic.x".into()),
14257 slot: None,
14258 };
14259 assert!(nats.is_pubsub());
14260 assert!(!nats.is_http());
14261 assert!(!nats.is_capability());
14262
14263 let kv = WitContract {
14264 de: "a".into(),
14265 para: "b".into(),
14266 wit: "wasi:keyvalue/store".into(),
14267 endpoint: None,
14268 subject: None,
14269 slot: Some("checkout/$orderId".into()),
14270 };
14271 assert!(kv.is_store());
14272 assert!(!kv.is_http());
14273 assert!(!kv.is_capability());
14274
14275 // Fourth arm on the paired closed-set predicate family: the
14276 // payload-less capability edge that projects to the payload-
14277 // less [`WitTarget::Capability`] arm under [`WitContract::target`].
14278 // Extends the 3-arm predicate sweep this test opened to cover
14279 // the closed 4-way partition [`WitContract::is_capability`]
14280 // closes on the pre-projection WIT-shape axis, matched with the
14281 // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
14282 // 4-arm predicate set.
14283 let cap = WitContract {
14284 de: "a".into(),
14285 para: "b".into(),
14286 wit: "custom:capability-only".into(),
14287 endpoint: None,
14288 subject: None,
14289 slot: None,
14290 };
14291 assert!(cap.is_capability());
14292 assert!(!cap.is_http());
14293 assert!(!cap.is_pubsub());
14294 assert!(!cap.is_store());
14295 }
14296
14297 // ── :contratos :wit value-shape gate ─────────────────────────────────
14298 //
14299 // Mirrors the `:contratos :endpoint` value-shape suite on the peer
14300 // dispatch-discriminator axis. Until this gate landed
14301 // `WitContract::target()` accepted any non-empty string and
14302 // silently demoted unrecognized shapes to a capability-only L4
14303 // edge — the canonical "I thought I had L7 HTTP routing, got
14304 // L4-only" footgun. Every authoring footgun the WIT registry's
14305 // own grammar rejects (uppercase, hyphen-for-colon typo,
14306 // whitespace, empty package, doubled `@`, …) now becomes a
14307 // caixa-build-time `ContratoWitInvalid` with the offending
14308 // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
14309 // as `ContratoEndpointInvalid` on the sibling axis; same shared
14310 // predicate (`crate::render::is_wit_world_ref`) ensures drift
14311 // between any two axes' rule enforcement is a build error at the
14312 // predicate, not piecemeal across renderers.
14313
14314 fn contrato_wit_err(wit: &str) -> AplicacaoError {
14315 // Fresh spec per call so the new contract doesn't collide on
14316 // identity with `three_member_spec`'s pre-existing entries.
14317 // The new edge uses `(payment, catalog)` — a pair the fixture
14318 // doesn't already declare — with no payload field set, so the
14319 // wit-shape gate fires before any payload-shape arm.
14320 let mut s = three_member_spec();
14321 s.contratos.push(WitContract {
14322 de: "payment".into(),
14323 para: "catalog".into(),
14324 wit: wit.into(),
14325 endpoint: None,
14326 subject: None,
14327 slot: None,
14328 });
14329 s.validate().unwrap_err()
14330 }
14331
14332 #[test]
14333 fn rejects_wit_with_uppercase_namespace() {
14334 // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
14335 // didn't match the lowercase `wasi:http/` prefix is_http() keys
14336 // off, so the dispatch fell through to the capability arm and
14337 // the contract silently rendered as an L4-only Cilium edge.
14338 // The new gate surfaces the uppercase typo at validate time
14339 // with the offending `:wit` named.
14340 let err = contrato_wit_err("WASI:http/proxy");
14341 assert!(
14342 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14343 if wit == "WASI:http/proxy" && reason.contains("lowercase")),
14344 "got {err:?}"
14345 );
14346 }
14347
14348 #[test]
14349 fn rejects_wit_with_hyphen_for_colon_typo() {
14350 // The canonical "I forgot the `:` separator" typo — pre-gate
14351 // this passed as Capability silently, so the renderer emitted
14352 // an L4-only policy where the author expected L7 HTTP rules.
14353 let err = contrato_wit_err("wasi-http/proxy");
14354 assert!(
14355 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14356 if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
14357 "got {err:?}"
14358 );
14359 }
14360
14361 #[test]
14362 fn rejects_wit_with_multiple_colons() {
14363 // Doubled `:` — the namespace/package split has nowhere to
14364 // anchor, so the dispatch silently demotes to Capability.
14365 let err = contrato_wit_err("wasi:http:proxy");
14366 assert!(
14367 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14368 if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
14369 "got {err:?}"
14370 );
14371 }
14372
14373 #[test]
14374 fn rejects_wit_with_empty_package() {
14375 // `wasi:` — namespace alone with no package. Pre-gate this
14376 // failed neither the is_http nor is_pubsub nor is_store
14377 // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
14378 // a bare `wasi:`), so it silently demoted to Capability.
14379 let err = contrato_wit_err("wasi:");
14380 assert!(
14381 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14382 if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
14383 "got {err:?}"
14384 );
14385 }
14386
14387 #[test]
14388 fn rejects_wit_with_underscore() {
14389 // Underscore — WIT identifiers are kebab-case, same rule
14390 // DNS-1123 enforces on its peer axes. The diagnostic carries
14391 // the explicit "use `-` instead" remediation.
14392 let err = contrato_wit_err("wasi:http_proxy");
14393 assert!(
14394 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14395 if wit == "wasi:http_proxy" && reason.contains('_')),
14396 "got {err:?}"
14397 );
14398 }
14399
14400 #[test]
14401 fn rejects_wit_with_whitespace() {
14402 // Whitespace mid-token — the prefix check matches but the
14403 // package-and-onward parse silently demoted to Capability.
14404 let err = contrato_wit_err("wasi:http proxy");
14405 assert!(
14406 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14407 if wit == "wasi:http proxy" && reason.contains("whitespace")),
14408 "got {err:?}"
14409 );
14410 }
14411
14412 #[test]
14413 fn rejects_wit_with_non_ascii() {
14414 // Un-percent-encoded non-ASCII byte — the canonical "I copied
14415 // the package name from a doc with smart quotes / accented
14416 // characters" footgun.
14417 let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
14418 assert!(
14419 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14420 if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
14421 "got {err:?}"
14422 );
14423 }
14424
14425 #[test]
14426 fn rejects_wit_with_consecutive_hyphens() {
14427 // `pub--sub` — WIT identifiers join words with single hyphens.
14428 let err = contrato_wit_err("nats:pub--sub");
14429 assert!(
14430 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14431 if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
14432 "got {err:?}"
14433 );
14434 }
14435
14436 #[test]
14437 fn rejects_wit_with_trailing_at_no_version() {
14438 // `wasi:http/proxy@` — the version-suffix author started to
14439 // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
14440 // parser would reject this; surface it at validate time.
14441 let err = contrato_wit_err("wasi:http/proxy@");
14442 assert!(
14443 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14444 if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
14445 "got {err:?}"
14446 );
14447 }
14448
14449 #[test]
14450 fn rejects_wit_too_long() {
14451 // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
14452 // The legitimate-shape arms all pass (lowercase, single `:`,
14453 // kebab-case identifiers); only the cap arm fires. Surfaces
14454 // the paste-from-binary / accidental-multi-line-blob landing
14455 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
14456 // on the peer axis.
14457 let big = format!("wasi:{}", "a".repeat(124));
14458 assert_eq!(big.len(), 129);
14459 let err = contrato_wit_err(&big);
14460 assert!(
14461 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
14462 if wit == &big && reason.contains("max length of 128")),
14463 "got {err:?}"
14464 );
14465 }
14466
14467 #[test]
14468 fn wit_max_length_validates() {
14469 // 128-byte WIT reference — exactly the cap. Boundary pin:
14470 // drift in the cap surfaces here and at `rejects_wit_too_long`
14471 // simultaneously, mirroring
14472 // `http_contrato_endpoint_max_length_validates` on the peer
14473 // axis.
14474 let big = format!("wasi:{}", "a".repeat(123));
14475 assert_eq!(big.len(), 128);
14476 let mut s = three_member_spec();
14477 s.contratos.push(WitContract {
14478 de: "payment".into(),
14479 para: "catalog".into(),
14480 wit: big,
14481 endpoint: None,
14482 subject: None,
14483 slot: None,
14484 });
14485 s.validate().unwrap();
14486 }
14487
14488 #[test]
14489 fn wit_accepts_canonical_forms_at_aplicacao_layer() {
14490 // Positive-set sweep through the AplicacaoSpec::validate
14491 // surface (rather than the substrate-side predicate directly)
14492 // — pins every shape the existing test fixtures + the
14493 // checkout-aplicacao example carry, so the gate's accept-set
14494 // matches the substrate's emit-set. Drift between this list
14495 // and `render::tests::wit_world_ref_accepts_canonical_forms`
14496 // surfaces at the substrate layer's positive sweep — one
14497 // source of truth for the rule.
14498 for wit in [
14499 "wasi:http/proxy",
14500 "wasi:keyvalue/store",
14501 "nats:pub-sub",
14502 "kafka:topic",
14503 "custom:exchange",
14504 "pleme:cap/audit",
14505 "wasi:http/proxy@0.2.0",
14506 ] {
14507 // Payload field paired to the dispatched WIT shape so the
14508 // shape-↔-target arm doesn't fire instead of the wit-shape
14509 // arm we're exercising. Routes off the same
14510 // `wit_shape_is_http` / `wit_shape_is_pubsub` /
14511 // `wit_shape_is_store` free functions the production
14512 // `WitContract::is_http` / `is_pubsub` / `is_store`
14513 // methods delegate to (both consult the lifted
14514 // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
14515 // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
14516 // future prefix addition to the routing accept-set
14517 // reaches this test's payload-dispatch arm by
14518 // construction — no per-test-site drift can hide a
14519 // shape-→-target-slot mismatch that would silently
14520 // demote a canonical `:wit` value to the
14521 // `(None, None, None)` capability-only arm and let the
14522 // `AplicacaoSpec::validate` positive sweep pass on a
14523 // shape it should exercise as HTTP / pub-sub / store.
14524 let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
14525 (Some("/x".into()), None, None)
14526 } else if wit_shape_is_pubsub(wit) {
14527 (None, Some("topic.x".into()), None)
14528 } else if wit_shape_is_store(wit) {
14529 (None, None, Some("bucket/$key".into()))
14530 } else {
14531 (None, None, None)
14532 };
14533 let mut s = three_member_spec();
14534 s.contratos.push(WitContract {
14535 de: "payment".into(),
14536 para: "catalog".into(),
14537 wit: wit.into(),
14538 endpoint,
14539 subject,
14540 slot,
14541 });
14542 s.validate()
14543 .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
14544 }
14545 }
14546
14547 #[test]
14548 fn wit_shape_predicates_accept_canonical_prefix_set() {
14549 // Positive-set sweep pinning every prefix in
14550 // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
14551 // WIT_STORE_SHAPE_PREFIXES against the three free-function
14552 // dispatch predicates. The six prefixes are the load-bearing
14553 // routing keys the substrate's WIT-shape dispatch consults
14554 // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
14555 // key/value-store-slot admission); any drift between the
14556 // free-function accept-set and this list surfaces here
14557 // rather than at apply time as a silent
14558 // shape-→-capability-only demotion.
14559 assert!(wit_shape_is_http("wasi:http/proxy"));
14560 assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
14561 assert!(wit_shape_is_http("http:incoming"));
14562
14563 assert!(wit_shape_is_pubsub("nats:pub-sub"));
14564 assert!(wit_shape_is_pubsub("kafka:topic"));
14565
14566 assert!(wit_shape_is_store("wasi:keyvalue/store"));
14567 assert!(wit_shape_is_store("kv:cache/session"));
14568 }
14569
14570 #[test]
14571 fn wit_shape_predicates_reject_uncanonical_forms() {
14572 // Negative-set pin: the six canonical prefixes are
14573 // lowercase-only (mirrors the `is_wit_world_ref` substrate
14574 // predicate's lowercase invariant — see its docstring on the
14575 // "I thought I had L7 HTTP routing, got L4-only" footgun).
14576 // The empty string, an uppercase-prefixed form, a hyphen-
14577 // instead-of-colon typo, and a bare kebab identifier all miss
14578 // every shape arm — reachable-by-construction only via the
14579 // `is_wit_world_ref` gate that admission-checks the `:wit`
14580 // value first, but pinned here so any future
14581 // free-function change (e.g. a case-insensitive
14582 // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
14583 // this unit level.
14584 for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
14585 assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
14586 assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
14587 assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
14588 }
14589 }
14590
14591 #[test]
14592 fn wit_shape_predicates_partition_canonical_set() {
14593 // Every canonical prefix routes to exactly one shape arm —
14594 // the three prefix sets are pairwise disjoint. Pins the
14595 // routing property [`WitContract::target`] relies on: an
14596 // `is_http()` return of `true` guarantees `is_pubsub()` and
14597 // `is_store()` return `false`, so the shape-→-target-slot
14598 // dispatch (endpoint vs subject vs slot) is unambiguous.
14599 // Drift (e.g. a future `"kv:"` moved into the HTTP set
14600 // without removal from the store set) would silently route
14601 // one prefix to two arms and the first-matching-arm order
14602 // becomes load-bearing — this pin surfaces it as a build
14603 // error instead.
14604 for prefix in WIT_HTTP_SHAPE_PREFIXES {
14605 let sample = format!("{prefix}x");
14606 assert!(wit_shape_is_http(&sample));
14607 assert!(!wit_shape_is_pubsub(&sample));
14608 assert!(!wit_shape_is_store(&sample));
14609 }
14610 for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
14611 let sample = format!("{prefix}x");
14612 assert!(!wit_shape_is_http(&sample));
14613 assert!(wit_shape_is_pubsub(&sample));
14614 assert!(!wit_shape_is_store(&sample));
14615 }
14616 for prefix in WIT_STORE_SHAPE_PREFIXES {
14617 let sample = format!("{prefix}x");
14618 assert!(!wit_shape_is_http(&sample));
14619 assert!(!wit_shape_is_pubsub(&sample));
14620 assert!(wit_shape_is_store(&sample));
14621 }
14622 }
14623
14624 #[test]
14625 fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
14626 // Positive pin: [`wit_shape_matches`] is exactly the
14627 // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
14628 // parameterized on the accept-set. Two-prefix accept-set,
14629 // one-prefix accept-set, and empty accept-set (which must
14630 // reject everything, including the empty string — an empty
14631 // `any()` fold returns `false`) all pinned so a future
14632 // reimplementation that swaps `starts_with` for `contains`,
14633 // `==`, or a case-folded comparator surfaces at unit-test
14634 // time.
14635 let two = &["wasi:http/", "http:"];
14636 assert!(wit_shape_matches("wasi:http/proxy", two));
14637 assert!(wit_shape_matches("http:incoming", two));
14638 assert!(!wit_shape_matches("wasi:keyvalue/store", two));
14639
14640 let one = &["nats:"];
14641 assert!(wit_shape_matches("nats:pub-sub", one));
14642 assert!(!wit_shape_matches("kafka:topic", one));
14643
14644 // Empty accept-set matches nothing — the identity element
14645 // for the disjunctive `any()` fold across the prefix set.
14646 // Reachable via a future `wit_shape_is_<name>` const paired
14647 // to a still-empty prefix table on a nascent shape-arm draft.
14648 let empty: &[&str] = &[];
14649 assert!(!wit_shape_matches("wasi:http/proxy", empty));
14650 assert!(!wit_shape_matches("", empty));
14651
14652 // starts_with, not contains: a prefix embedded mid-string
14653 // never matches. Pins the routing invariant [`WitContract::target`]
14654 // relies on (an authored `:wit "custom:wasi:http/"` string
14655 // does not silently route through the HTTP arm just because
14656 // it happens to contain the canonical HTTP prefix).
14657 assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
14658 }
14659
14660 #[test]
14661 fn wit_shape_predicates_delegate_to_wit_shape_matches() {
14662 // Equivalence pin: each per-shape predicate is exactly
14663 // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
14664 // every canonical prefix + the empty string + one negative
14665 // sample against every peer so a future predicate that grew
14666 // its own inline `iter().any(starts_with)` (rather than
14667 // delegating through the lifted combinator) drifts loudly here
14668 // — the peer-const table's contents must agree with the
14669 // predicate's accept-set by construction.
14670 let samples = [
14671 String::new(),
14672 "wasi:http/proxy".to_string(),
14673 "http:incoming".to_string(),
14674 "nats:pub-sub".to_string(),
14675 "kafka:topic".to_string(),
14676 "wasi:keyvalue/store".to_string(),
14677 "kv:cache/session".to_string(),
14678 "custom-shape".to_string(),
14679 "WASI:HTTP/proxy".to_string(),
14680 ];
14681 for wit in &samples {
14682 assert_eq!(
14683 wit_shape_is_http(wit),
14684 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
14685 "wit_shape_is_http drifted from combinator on {wit:?}",
14686 );
14687 assert_eq!(
14688 wit_shape_is_pubsub(wit),
14689 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
14690 "wit_shape_is_pubsub drifted from combinator on {wit:?}",
14691 );
14692 assert_eq!(
14693 wit_shape_is_store(wit),
14694 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
14695 "wit_shape_is_store drifted from combinator on {wit:?}",
14696 );
14697 }
14698 }
14699
14700 #[test]
14701 fn wit_contract_shape_methods_delegate_to_free_functions() {
14702 // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
14703 // `is_store` are `&self` conveniences on top of the free
14704 // functions — for every canonical prefix the method's return
14705 // matches its free-function peer. Sweeps the union of the
14706 // three prefix sets so a future method that grew its own
14707 // inline prefix logic (rather than delegating) drifts loudly
14708 // here on the first prefix the free function accepts and the
14709 // method doesn't.
14710 for shape_set in [
14711 WIT_HTTP_SHAPE_PREFIXES,
14712 WIT_PUBSUB_SHAPE_PREFIXES,
14713 WIT_STORE_SHAPE_PREFIXES,
14714 ] {
14715 for prefix in shape_set {
14716 let c = WitContract {
14717 de: "cart".into(),
14718 para: "catalog".into(),
14719 wit: format!("{prefix}x"),
14720 endpoint: None,
14721 subject: None,
14722 slot: None,
14723 };
14724 assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
14725 assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
14726 assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
14727 assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
14728 }
14729 }
14730 // Capability-arm delegation sweep: two representative
14731 // Capability-shaped `:wit` values (a bare non-prefix-matching
14732 // WIT world, the deliberately-shaped empty string
14733 // [`WitContract::is_capability`]'s docstring calls out as
14734 // syntactically Capability). Extends the free-function
14735 // delegation pin onto the fourth arm so a future
14736 // [`WitContract::is_capability`] rewrite that grew an inline
14737 // prefix-set scan (rather than delegating through
14738 // [`wit_shape_is_capability`]) drifts loudly here on the first
14739 // Capability-shaped sample.
14740 for wit in ["custom:capability-only", ""] {
14741 let c = WitContract {
14742 de: "cart".into(),
14743 para: "catalog".into(),
14744 wit: wit.into(),
14745 endpoint: None,
14746 subject: None,
14747 slot: None,
14748 };
14749 assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
14750 }
14751 }
14752
14753 #[test]
14754 fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
14755 // 4-way partition-witness pin on the raw `&str` axis: for every
14756 // canonical prefix in the three payload-arm accept-sets,
14757 // exactly one of the four [`wit_shape_is_http`] /
14758 // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
14759 // [`wit_shape_is_capability`] free functions returns `true` and
14760 // the other three return `false` — the four-arm partition
14761 // witness that locks the free-function WIT-shape-classifier
14762 // family into a partition of the `:contratos :wit` axis
14763 // load-bearing. Peer of the sibling [`WitContract`]-surface
14764 // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
14765 // partition pin — extends the discipline onto the raw `&str`
14766 // axis so any future arm addition (a hypothetical
14767 // `wasi:sockets/*` transport-layer shape, an `oci:*`
14768 // capability-import carrier per the sibling
14769 // [`wit_shape_matches`] docstring's trajectory bullet) that
14770 // landed on one of the payload-arm free functions without
14771 // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
14772 // here as two arms returning `true` simultaneously at
14773 // caixa-core build time rather than a silent per-consumer
14774 // misclassification at renderer emit time.
14775 for shape_set in [
14776 WIT_HTTP_SHAPE_PREFIXES,
14777 WIT_PUBSUB_SHAPE_PREFIXES,
14778 WIT_STORE_SHAPE_PREFIXES,
14779 ] {
14780 for prefix in shape_set {
14781 let wit = format!("{prefix}x");
14782 let hits = [
14783 wit_shape_is_http(&wit),
14784 wit_shape_is_pubsub(&wit),
14785 wit_shape_is_store(&wit),
14786 wit_shape_is_capability(&wit),
14787 ]
14788 .iter()
14789 .filter(|&&b| b)
14790 .count();
14791 assert_eq!(
14792 hits,
14793 1,
14794 "raw-&str WIT-shape 4-way predicate partition must \
14795 admit exactly one arm per canonical prefix; got {hits} \
14796 hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
14797 is_capability={})",
14798 wit_shape_is_http(&wit),
14799 wit_shape_is_pubsub(&wit),
14800 wit_shape_is_store(&wit),
14801 wit_shape_is_capability(&wit),
14802 );
14803 }
14804 }
14805 // Capability-arm sweep on the raw `&str` axis: two
14806 // representative Capability-shaped `:wit` values (a bare non-
14807 // prefix-matching WIT world, the deliberately-shaped empty
14808 // string the pure classifier still admits per
14809 // [`wit_shape_is_capability`]'s docstring). Both must land on
14810 // the fourth arm exclusively so the partition witness holds
14811 // across the full 4-arm closure on the raw `&str` axis.
14812 for wit in ["custom:capability-only", ""] {
14813 let hits = [
14814 wit_shape_is_http(wit),
14815 wit_shape_is_pubsub(wit),
14816 wit_shape_is_store(wit),
14817 wit_shape_is_capability(wit),
14818 ]
14819 .iter()
14820 .filter(|&&b| b)
14821 .count();
14822 assert_eq!(
14823 hits, 1,
14824 "raw-&str WIT-shape 4-way predicate partition must \
14825 admit exactly one arm on Capability-shaped wit={wit:?}"
14826 );
14827 assert!(
14828 wit_shape_is_capability(wit),
14829 "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
14830 );
14831 }
14832 }
14833
14834 #[test]
14835 fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
14836 // Composition-witness pin: [`wit_shape_is_capability`] is the
14837 // exact-inverse disjunction of the sibling payload-arm free-
14838 // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
14839 // / [`wit_shape_is_store`]. A future reimplementation that
14840 // grew its own prefix-set scan (e.g. inlining a fourth
14841 // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
14842 // not own today) rather than delegating to the sibling trio
14843 // would drift loudly here — the composition contract binds the
14844 // fourth-arm free-function predicate to the exact-inverse of
14845 // the three payload-arm free-function predicates, so any
14846 // rebrand of any prefix-set const flows through
14847 // [`wit_shape_is_capability`] by construction without a
14848 // coordinated per-consumer rewrite. Peer of the sibling
14849 // [`WitContract`]-surface
14850 // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
14851 // composition pin — extends the discipline onto the raw
14852 // `&str` axis.
14853 let mut cases: Vec<String> = Vec::new();
14854 for shape_set in [
14855 WIT_HTTP_SHAPE_PREFIXES,
14856 WIT_PUBSUB_SHAPE_PREFIXES,
14857 WIT_STORE_SHAPE_PREFIXES,
14858 ] {
14859 for prefix in shape_set {
14860 cases.push(format!("{prefix}x"));
14861 }
14862 }
14863 cases.push("custom:capability-only".to_string());
14864 cases.push(String::new());
14865 for wit in cases {
14866 assert_eq!(
14867 wit_shape_is_capability(&wit),
14868 !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
14869 "wit_shape_is_capability must equal \
14870 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
14871 at wit={wit:?}"
14872 );
14873 }
14874 }
14875
14876 #[test]
14877 fn wit_shape_classifier_family_is_const_fn() {
14878 // Fail-before-pass-after pin on the 4-arm free-function WIT-
14879 // shape classifier family's `const`-eval posture. Each of the
14880 // four peer classifiers ([`wit_shape_is_http`] /
14881 // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
14882 // [`wit_shape_is_capability`]) and the underlying combinator
14883 // [`wit_shape_matches`] must be `pub const fn` — any future
14884 // accidental downgrade to non-`const` fails the `const fn`
14885 // wrappers below at caixa-core build time with E0015
14886 // (`cannot call non-const function`), strictly stronger than
14887 // a runtime `assert!` and strictly stronger than the module-
14888 // scope `const _: () = assert!(…)` pins immediately after the
14889 // classifier declarations (those anchor specific accept-set
14890 // truth-table entries; this pin anchors the `const` posture
14891 // itself via `const fn` wrappers that are only well-formed
14892 // when the callee is itself `const fn`).
14893 //
14894 // Verified fail-before-pass-after by locally reverting
14895 // `pub const fn` → `pub fn` on each classifier and observing
14896 // E0015 at every corresponding wrapper call site (build
14897 // error, no test-time surface), then restoring `pub const fn`
14898 // and observing the pin pass at test time. Peer of the
14899 // sibling M3
14900 // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
14901 // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
14902 // M2
14903 // [`child_spec_restart_accessor_is_const_fn`] /
14904 // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
14905 // and M3
14906 // [`placement_estrategia_accessor_is_const_fn`] /
14907 // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
14908 // sibling `const`-eval-surface-pass axes.
14909 const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
14910 wit_shape_matches(wit, prefixes)
14911 }
14912 const fn http_via_const_fn(wit: &str) -> bool {
14913 wit_shape_is_http(wit)
14914 }
14915 const fn pubsub_via_const_fn(wit: &str) -> bool {
14916 wit_shape_is_pubsub(wit)
14917 }
14918 const fn store_via_const_fn(wit: &str) -> bool {
14919 wit_shape_is_store(wit)
14920 }
14921 const fn capability_via_const_fn(wit: &str) -> bool {
14922 wit_shape_is_capability(wit)
14923 }
14924 // Sweep one canonical accept-set sample per arm plus the
14925 // payload-less/empty capability samples, asserting the
14926 // wrapper and direct dispatches agree byte-for-byte across
14927 // the closed 4-arm partition.
14928 let cases: [(&str, bool, bool, bool, bool); 6] = [
14929 ("wasi:http/proxy", true, false, false, false),
14930 ("http:incoming", true, false, false, false),
14931 ("nats:events", false, true, false, false),
14932 ("kafka:topic", false, true, false, false),
14933 ("wasi:keyvalue/store", false, false, true, false),
14934 ("kv:cache", false, false, true, false),
14935 ];
14936 for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
14937 assert_eq!(
14938 matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
14939 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
14940 "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
14941 );
14942 assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
14943 assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
14944 assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
14945 assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
14946 assert_eq!(wit_shape_is_http(wit), is_http);
14947 assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
14948 assert_eq!(wit_shape_is_store(wit), is_store);
14949 }
14950 // Payload-less capability arm (the 4th partition arm).
14951 let capability_samples: [&str; 3] =
14952 ["wasi:filesystem/preopens", "custom:capability-only", ""];
14953 for wit in capability_samples {
14954 assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
14955 assert!(wit_shape_is_capability(wit));
14956 assert!(!wit_shape_is_http(wit));
14957 assert!(!wit_shape_is_pubsub(wit));
14958 assert!(!wit_shape_is_store(wit));
14959 }
14960 }
14961
14962 // Canonical `(wit, expected)` sweep the four [`WitShape`] pins below
14963 // key off — one accept-set sample per prefix in each of the three
14964 // payload-arm prefix sets [`WIT_HTTP_SHAPE_PREFIXES`] /
14965 // [`WIT_PUBSUB_SHAPE_PREFIXES`] / [`WIT_STORE_SHAPE_PREFIXES`], plus
14966 // three canonical Capability-arm samples (a non-prefix-matching WIT
14967 // world, an empty string, a partial-match probe that lands after
14968 // the accepted prefix boundary). Declared once so a future arm
14969 // addition or prefix-set edit grows the truth table at one
14970 // authored site and every downstream pin picks up the new row by
14971 // construction.
14972 const WIT_SHAPE_CLASSIFY_TRUTH_TABLE: &[(&str, WitShape)] = &[
14973 ("wasi:http/proxy", WitShape::Http),
14974 ("http:incoming", WitShape::Http),
14975 ("nats:events", WitShape::PubSub),
14976 ("kafka:topic", WitShape::PubSub),
14977 ("wasi:keyvalue/store", WitShape::Store),
14978 ("kv:cache", WitShape::Store),
14979 ("wasi:filesystem/preopens", WitShape::Capability),
14980 ("custom:capability-only", WitShape::Capability),
14981 ("", WitShape::Capability),
14982 ];
14983
14984 #[test]
14985 fn wit_shape_all_matches_declaration_order_and_covers_every_arm() {
14986 // Fail-before-pass-after pin on [`WitShape::ALL`]: the slice
14987 // must enumerate every arm exactly once in declaration order
14988 // (`Http` → `PubSub` → `Store` → `Capability`), so downstream
14989 // consumers that walk the shape space through the const slice
14990 // reach every arm and see them in the canonical order the
14991 // paired [`WitShape::classify`] arm-preference dispatches on.
14992 // A future variant addition that forgets to grow the slice
14993 // trips here (the length no longer matches the number of arms
14994 // touched by the `match self` below); a rearrangement of the
14995 // declaration order without updating the slice trips too.
14996 let expected: [WitShape; 4] = [
14997 WitShape::Http,
14998 WitShape::PubSub,
14999 WitShape::Store,
15000 WitShape::Capability,
15001 ];
15002 assert_eq!(WitShape::ALL.len(), expected.len());
15003 assert_eq!(WitShape::ALL, &expected[..]);
15004 // Exhaustive-match witness: touch every arm so a future
15005 // variant addition without a matching `WitShape::ALL` extension
15006 // trips at compile time here on the missing arm.
15007 for arm in WitShape::ALL {
15008 match arm {
15009 WitShape::Http | WitShape::PubSub | WitShape::Store | WitShape::Capability => {}
15010 }
15011 }
15012 }
15013
15014 #[test]
15015 fn wit_shape_classify_pins_the_canonical_truth_table() {
15016 // Pin the [`WitShape::classify`] arm-dispatch against the
15017 // shared truth table [`WIT_SHAPE_CLASSIFY_TRUTH_TABLE`]. A
15018 // future prefix-set edit that reroutes any canonical sample
15019 // onto the wrong arm trips at exactly the offending row.
15020 for (wit, expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
15021 assert_eq!(
15022 WitShape::classify(wit),
15023 *expected,
15024 "WitShape::classify({wit:?}) drifted from truth table",
15025 );
15026 }
15027 }
15028
15029 #[test]
15030 fn wit_shape_classify_partitions_via_is_variant_predicates() {
15031 // Fail-before-pass-after pin: for every canonical truth-table
15032 // row, the classified arm satisfies exactly one of the four
15033 // [`gen_platform::IsVariant`]-derived arm-discriminator
15034 // predicates ([`WitShape::is_http`] / [`is_pubsub`] /
15035 // [`is_store`] / [`is_capability`]) — the observed 4-slot
15036 // predicate row must equal a one-hot row with the `true` at
15037 // exactly the same index as the declared arm's slot in
15038 // [`WitShape::ALL`]. A future rebind (an `#[is_variant(name =
15039 // "…")]` drift, a manual `impl` shadowing the derive, an arm
15040 // rename that reroutes one arm through the wrong predicate
15041 // lane) trips here at exactly the offending row rather than
15042 // surfacing far from the derive commit.
15043 for (wit, expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
15044 let arm = WitShape::classify(wit);
15045 let observed = [
15046 arm.is_http(),
15047 arm.is_pubsub(),
15048 arm.is_store(),
15049 arm.is_capability(),
15050 ];
15051 let mut expected_row = [false; 4];
15052 let idx = WitShape::ALL
15053 .iter()
15054 .position(|a| a == expected)
15055 .expect("truth-table arm appears in WitShape::ALL");
15056 expected_row[idx] = true;
15057 assert_eq!(
15058 observed, expected_row,
15059 "WitShape::classify({wit:?}).is_* row must be one-hot at slot {idx}",
15060 );
15061 }
15062 }
15063
15064 #[test]
15065 fn wit_shape_classify_agrees_with_free_predicates() {
15066 // Equivalence pin against the four free classifier predicates
15067 // ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
15068 // [`wit_shape_is_store`] / [`wit_shape_is_capability`]) — after
15069 // this lift the free predicates route through
15070 // `matches!(WitShape::classify(wit), WitShape::<arm>)`, so this
15071 // pin proves the delegation preserves each predicate's
15072 // accept-set on the canonical truth table. A future accidental
15073 // reintroduction of an open-coded free-predicate body (or a
15074 // classify-side arm reorder that shifts arm preference in a
15075 // way that breaks disjointness) trips here at the offending
15076 // row rather than at a downstream consumer.
15077 for (wit, _expected) in WIT_SHAPE_CLASSIFY_TRUTH_TABLE {
15078 let arm = WitShape::classify(wit);
15079 assert_eq!(arm.is_http(), wit_shape_is_http(wit));
15080 assert_eq!(arm.is_pubsub(), wit_shape_is_pubsub(wit));
15081 assert_eq!(arm.is_store(), wit_shape_is_store(wit));
15082 assert_eq!(arm.is_capability(), wit_shape_is_capability(wit));
15083 }
15084 }
15085
15086 #[test]
15087 fn wit_shape_as_str_display_and_asref_route_through_one_source() {
15088 // Fail-before-pass-after pin on the canonical-projection triple
15089 // [`WitShape::as_str`] / [`std::fmt::Display for WitShape`] /
15090 // [`AsRef<str> for WitShape`]: every arm's `Display`-formatted
15091 // and `AsRef<str>`-borrowed output must byte-equal its
15092 // `as_str` output. Same discipline the sibling
15093 // [`crate::CaixaKind`] / [`crate::dialeto::CaixaDialeto`] /
15094 // [`PlacementStrategy`] / [`RateLimitUnit`] canonical-projection
15095 // triples carry — a future accidental hand-rolled `Display`
15096 // body that diverges from `as_str` trips here.
15097 let expected: &[(WitShape, &str)] = &[
15098 (WitShape::Http, "http"),
15099 (WitShape::PubSub, "pubsub"),
15100 (WitShape::Store, "store"),
15101 (WitShape::Capability, "capability"),
15102 ];
15103 for (arm, want) in expected {
15104 assert_eq!(arm.as_str(), *want, "WitShape::as_str({arm:?}) drifted");
15105 assert_eq!(
15106 format!("{arm}"),
15107 *want,
15108 "Display for WitShape drifted from as_str at {arm:?}",
15109 );
15110 assert_eq!(
15111 AsRef::<str>::as_ref(arm),
15112 *want,
15113 "AsRef<str> for WitShape drifted from as_str at {arm:?}",
15114 );
15115 }
15116 }
15117
15118 #[test]
15119 fn wit_shape_classify_is_const_fn() {
15120 // Fail-before-pass-after pin on [`WitShape::classify`]'s
15121 // `const`-eval posture. The classifier must be `pub const fn`
15122 // — any future accidental downgrade to non-`const` fails the
15123 // wrapper below with E0015 at caixa-core build time, strictly
15124 // stronger than a runtime `assert!`. Peer of the sibling
15125 // [`wit_shape_classifier_family_is_const_fn`] pin on the
15126 // free-function classifier family.
15127 const fn classify_via_const_fn(wit: &str) -> WitShape {
15128 WitShape::classify(wit)
15129 }
15130 // Compile-time truth-table pin: every canonical row's
15131 // classification is reachable at const-eval time, so any
15132 // downstream `const`-context consumer (a module-scope
15133 // `const _: () = assert!(matches!(WitShape::classify(<lit>),
15134 // WitShape::<arm>))` invariant pin on a typed fixture, a
15135 // future `const fn` per-`:contratos :wit` arm-resolver over a
15136 // static wit literal) reaches the classifier through one
15137 // dispatch on the substrate primitive without an intermediate
15138 // non-`const` step.
15139 const _: () = assert!(matches!(
15140 classify_via_const_fn("wasi:http/proxy"),
15141 WitShape::Http
15142 ));
15143 const _: () = assert!(matches!(
15144 classify_via_const_fn("nats:events"),
15145 WitShape::PubSub
15146 ));
15147 const _: () = assert!(matches!(
15148 classify_via_const_fn("wasi:keyvalue/store"),
15149 WitShape::Store
15150 ));
15151 const _: () = assert!(matches!(classify_via_const_fn(""), WitShape::Capability));
15152 // Also assert const `as_str` routes through the const `classify`
15153 // on the same const path.
15154 const _: () = assert!(matches!(
15155 classify_via_const_fn("wasi:http/proxy").as_str().as_bytes(),
15156 b"http"
15157 ));
15158 }
15159
15160 #[test]
15161 fn wit_shape_from_wire_accepts_every_as_str_output() {
15162 // Fail-before-pass-after per-arm accept pin on the newly lifted
15163 // [`WitShape::from_wire`] reverse projection: every arm in
15164 // [`WitShape::ALL`] must parse back through `from_wire` when fed
15165 // its own [`WitShape::as_str`] output, landing on
15166 // `Some(same_variant)`. A regression that hand-rolled either
15167 // side's per-arm match without threading through the shared
15168 // four-string closed set would silently disagree on any future
15169 // arm rename (or a new arm the WIT-shape space grows — a
15170 // hypothetical `wasi:sockets/*` transport-layer shape, an
15171 // `oci:*` capability-import carrier per the sibling
15172 // [`wit_shape_matches`] docstring's trajectory bullet) and this
15173 // pin flags it at caixa-core build time rather than at a
15174 // downstream `feira app graph --by-wit-shape` consumer's silent
15175 // tag misclassification.
15176 //
15177 // Peer of the sibling
15178 // `caixa_provedor::ferrite::tests::ferrite_runtime_from_wire_accepts_every_variant_slug_output`
15179 // (1e4cc81) /
15180 // `caixa_theme::style::tests::semantic_from_wire_accepts_every_as_str_output`
15181 // (e7bca7b) /
15182 // `caixa_lint::diagnostic::tests::fix_safety_from_wire_accepts_every_as_str_output`
15183 // (bd505a1) /
15184 // `caixa_lint::diagnostic::tests::severity_from_wire_accepts_every_as_str_output`
15185 // (5afff0e) /
15186 // `caixa_arch::report::tests::arch_verdict_from_wire_accepts_every_as_str_output`
15187 // (6afe564) /
15188 // `caixa_arch::invariants::tests::invariant_kind_from_wire_accepts_every_as_str_output`
15189 // (b9e4e61) round-trip pins on the peer caixa-provedor /
15190 // caixa-theme / caixa-lint / caixa-arch closed-set-enum
15191 // reverse-projection axes, and of the sibling
15192 // `crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`
15193 // (2aa6d23) /
15194 // `crate::dialeto::tests::caixa_dialeto_from_wire_accepts_every_as_str_output`
15195 // (d0e65ea) /
15196 // `placement_strategy_from_wire_accepts_every_lifted_constant`
15197 // (18c7342) /
15198 // `crate::dep::tests::dep_list_round_trips_through_as_str_and_from_wire`
15199 // (45ee563) /
15200 // `crate::render::tests::path_shape_violation_from_wire_accepts_every_as_str_output`
15201 // (aebd9c6) round-trip pins on the sibling caixa-core closed-
15202 // set typed-enum reverse-projection axes.
15203 for &variant in WitShape::ALL {
15204 let wire = variant.as_str();
15205 let parsed = WitShape::from_wire(wire).unwrap_or_else(|| {
15206 panic!(
15207 "WitShape::from_wire({wire:?}) must accept every \
15208 WitShape::as_str output — got None for the wire \
15209 byte-string of {variant:?}"
15210 )
15211 });
15212 assert_eq!(
15213 parsed, variant,
15214 "WitShape::from_wire(WitShape::{variant:?}.as_str()) must \
15215 return WitShape::{variant:?} — the (as_str, from_wire) \
15216 pair must form a total round-trip on the closed four-arm \
15217 WitShape arm-set",
15218 );
15219 }
15220 // Pin the exact per-arm accept-set so a future rebrand of the
15221 // census-label byte-strings ("http" / "pubsub" / "store" /
15222 // "capability") surfaces at this pin rather than at a downstream
15223 // consumer's silent tag drift.
15224 assert_eq!(WitShape::from_wire("http"), Some(WitShape::Http));
15225 assert_eq!(WitShape::from_wire("pubsub"), Some(WitShape::PubSub));
15226 assert_eq!(WitShape::from_wire("store"), Some(WitShape::Store));
15227 assert_eq!(
15228 WitShape::from_wire("capability"),
15229 Some(WitShape::Capability),
15230 );
15231 }
15232
15233 #[test]
15234 fn wit_shape_from_wire_rejects_unknown_byte_strings() {
15235 // Rejection pin on the [`WitShape::from_wire`] parser's
15236 // accept-set: any string outside the four-arm
15237 // [`WitShape::as_str`] output set must return [`None`]. A future
15238 // accidental widening of the accept-set (a case-insensitive
15239 // match that accepts `"HTTP"` / `"Http"`, a silent acceptance of
15240 // the PascalCase Debug-derived shapes `"Http"` / `"PubSub"` /
15241 // `"Store"` / `"Capability"` on the wire axis, a Levenshtein-
15242 // forgiving arm-lookup that admits typos, a silent absorption of
15243 // the sibling raw `:contratos :wit` identifiers [`Self::classify`]
15244 // consumes on the peer classifier axis — `"wasi:http/proxy"`,
15245 // `"nats:events"`, `"wasi:keyvalue/store"`, `"kafka:topic"`,
15246 // `"kv:cache"`, `"http:incoming"` — a silent absorption of the
15247 // paired [`WitTarget::label`] short-form tags every downstream
15248 // renderer already handles on the post-validation axis) would
15249 // silently drift the parser's accept-set from the emitter's — a
15250 // downstream re-loader that bound a prior emission's
15251 // [`Self::as_str`] output back to the typed enum through this
15252 // parser would then bind a malformed byte-string to a
15253 // plausibly-wrong typed arm the caller does not route through
15254 // any fallback, silently misclassifying the reloaded row.
15255 //
15256 // The raw `:contratos :wit` identifier vectors are load-bearing:
15257 // [`WitShape::classify`] is a *total* function on every `&str`
15258 // (falling through to [`WitShape::Capability`] on unknown
15259 // prefixes), so a caller who confuses the two axes and routes a
15260 // raw WIT identifier through [`from_wire`] instead of
15261 // [`classify`] must observe [`None`] here rather than a plausibly-
15262 // wrong `Some(WitShape::Capability)` silently — the peer axes
15263 // carry different accept-sets by design.
15264 //
15265 // Peer of the sibling
15266 // `caixa_provedor::ferrite::tests::ferrite_runtime_from_wire_rejects_unknown_byte_strings`
15267 // (1e4cc81) /
15268 // `caixa_theme::style::tests::semantic_from_wire_rejects_unknown_byte_strings`
15269 // (e7bca7b) /
15270 // `caixa_lint::diagnostic::tests::fix_safety_from_wire_rejects_unknown_byte_strings`
15271 // (bd505a1) /
15272 // `caixa_lint::diagnostic::tests::severity_from_wire_rejects_unknown_byte_strings`
15273 // (5afff0e) /
15274 // `caixa_arch::report::tests::arch_verdict_from_wire_rejects_unknown_byte_strings`
15275 // (6afe564) /
15276 // `caixa_arch::invariants::tests::invariant_kind_from_wire_rejects_unknown_byte_strings`
15277 // (b9e4e61) rejection pins on the peer caixa-provedor /
15278 // caixa-theme / caixa-lint / caixa-arch axes, and of the sibling
15279 // `caixa_kind_from_wire_rejects_unknown_byte_strings` (2aa6d23),
15280 // `caixa_dialeto_from_wire_rejects_unknown_byte_strings`
15281 // (d0e65ea),
15282 // `placement_strategy_from_wire_rejects_unknown_byte_strings`
15283 // (18c7342),
15284 // `dep_list_from_wire_returns_none_on_unknown_wire_scalar`
15285 // (45ee563), and
15286 // `path_shape_violation_from_wire_rejects_unknown_byte_strings`
15287 // (aebd9c6) rejection pins on the sibling caixa-core axes.
15288 for bad in [
15289 "",
15290 " ",
15291 "http ",
15292 " http",
15293 "HTTP",
15294 "Http",
15295 "PUBSUB",
15296 "PubSub",
15297 "pub_sub",
15298 "pub-sub",
15299 "STORE",
15300 "Store",
15301 "CAPABILITY",
15302 "Capability",
15303 "kv",
15304 "nats",
15305 "kafka",
15306 "wasi:http/proxy",
15307 "wasi:http/",
15308 "http:",
15309 "http:incoming",
15310 "nats:events",
15311 "kafka:topic",
15312 "wasi:keyvalue/store",
15313 "wasi:keyvalue/",
15314 "kv:cache",
15315 "kv:",
15316 "oci:capability",
15317 "wasi:sockets/tcp",
15318 "\u{200b}http",
15319 "http\u{200b}",
15320 ] {
15321 assert!(
15322 WitShape::from_wire(bad).is_none(),
15323 "WitShape::from_wire({bad:?}) must reject byte-strings \
15324 outside the four-arm WitShape::as_str output set — got \
15325 {:?}",
15326 WitShape::from_wire(bad),
15327 );
15328 }
15329 }
15330
15331 #[test]
15332 fn wit_shape_from_wire_and_classify_partition_the_axis() {
15333 // Cross-axis discipline pin: [`WitShape::classify`] is a total
15334 // function on the raw `:contratos :wit` identifier axis (every
15335 // `&str` classifies), while [`WitShape::from_wire`] is a partial
15336 // function on the census-label axis (the four
15337 // [`WitShape::as_str`] outputs and nothing else). The two axes
15338 // meet on exactly zero strings by construction — the four
15339 // census labels (`"http"` / `"pubsub"` / `"store"` /
15340 // `"capability"`) are not prefix-matched by any of
15341 // [`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
15342 // [`WIT_STORE_SHAPE_PREFIXES`], so on the shared four-string
15343 // census-label set:
15344 //
15345 // * [`WitShape::from_wire`] returns `Some(<matching arm>)`
15346 // per [`WitShape::as_str`]'s output;
15347 // * [`WitShape::classify`] falls through to the
15348 // [`WitShape::Capability`] catch-all fallback (since none of
15349 // the payload-arm prefix sets begin with `"http"` /
15350 // `"pubsub"` / `"store"` / `"capability"`).
15351 //
15352 // A future WIT-prefix set edit that accidentally started with
15353 // one of the four census labels (a hypothetical
15354 // `"http"` prefix directly, a `"pubsub://"` scheme addition, a
15355 // `"store:"` capability-carrier extension) would silently
15356 // collide the two axes on the same string — [`from_wire`] would
15357 // still yield the census-label arm while [`classify`] would
15358 // route the payload-arm dispatch through the accidental overlap.
15359 // Locking the partition here means such a prefix-set edit
15360 // trips this pin at caixa-core build time before the collision
15361 // becomes observable at any downstream consumer.
15362 for &variant in WitShape::ALL {
15363 let label = variant.as_str();
15364 // The census-label axis half — [`from_wire`] resolves to
15365 // the emitter's arm identity.
15366 assert_eq!(
15367 WitShape::from_wire(label),
15368 Some(variant),
15369 "WitShape::from_wire({label:?}) must resolve to the \
15370 emitter's arm identity on the census-label axis",
15371 );
15372 // The raw-classifier axis half — [`classify`] falls through
15373 // to [`WitShape::Capability`] on every census label under
15374 // the current prefix set. Any future overlap trips here.
15375 assert_eq!(
15376 WitShape::classify(label),
15377 WitShape::Capability,
15378 "WitShape::classify({label:?}) must fall through to \
15379 WitShape::Capability on every census label — a match \
15380 to any payload arm here means a payload-prefix set \
15381 has silently collided the census-label axis with the \
15382 raw-classifier axis",
15383 );
15384 }
15385 }
15386
15387 #[test]
15388 fn wit_shape_try_from_str_routes_through_from_wire_accessor() {
15389 // Fail-before-pass-after byte-parity pin on the newly lifted
15390 // `impl TryFrom<&str> for WitShape` — asserts the standard-
15391 // library trait impl and the substrate-primitive
15392 // [`WitShape::from_wire`] `Option<Self>` accessor resolve to the
15393 // same four-arm census-label accept-set across every arm the
15394 // exhaustive [`WitShape::ALL`] slice enumerates. Any future
15395 // silent detour that routes the trait impl through a divergent
15396 // projection (a per-arm inline `match s { "http" =>
15397 // Ok(Self::Http), … }` re-inlining that opens a compile-time
15398 // link to the un-lifted arm-literal, a stray attribute drift
15399 // that silently splits the wire byte-string from every consumer
15400 // that reaches for this typed dispatch) trips at caixa-core test
15401 // time under `assert_eq!` rather than at a downstream
15402 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
15403 // every one of the four arms [`WitShape::ALL`] carries so no
15404 // arm's projection is covered only by the sibling method-named
15405 // `from_wire` path.
15406 //
15407 // Peer of the sibling
15408 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
15409 // (3c83606),
15410 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
15411 // (bf33136),
15412 // [`tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
15413 // (6fd00cd),
15414 // [`crate::supervisor::tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
15415 // (5b828ed), and
15416 // [`crate::supervisor::tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
15417 // (6fdd0d9) round-trip pins on the sibling caixa-core closed-
15418 // set typed-enum trait-idiomatic reverse-projection axes.
15419 for &variant in WitShape::ALL {
15420 let wire = variant.as_str();
15421 assert_eq!(
15422 <WitShape as TryFrom<&str>>::try_from(wire),
15423 Ok(variant),
15424 "TryFrom<&str> impl on WitShape must round-trip \
15425 WitShape::{variant:?}.as_str() = {wire:?} back to \
15426 Ok(WitShape::{variant:?}) — divergence from \
15427 WitShape::from_wire signals a silent detour off the \
15428 substrate-primitive accessor"
15429 );
15430 assert_eq!(
15431 <WitShape as TryFrom<&str>>::try_from(wire).ok(),
15432 WitShape::from_wire(wire),
15433 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
15434 WitShape::from_wire on the same input"
15435 );
15436 }
15437 }
15438
15439 #[test]
15440 fn wit_shape_try_from_str_rejects_unknown_byte_strings() {
15441 // Rejection witness on the `impl TryFrom<&str> for WitShape` —
15442 // sweeps a candidate set of byte-strings outside the four-arm
15443 // census-label wire accept-set the sibling [`WitShape::as_str`]
15444 // emits and asserts every one lands on `Err(())`, so a future
15445 // accidental widening of the trait impl's accept-set (a stray
15446 // additional `_ if s.eq_ignore_ascii_case("http") => Ok(…)`
15447 // case-fold path, a silent inclusion of a PascalCase rebrand of
15448 // the wire byte-string that would collide the two-axis split the
15449 // sibling `wit_shape_from_wire_rejects_unknown_byte_strings` pin
15450 // makes load-bearing, a silent overlap with the raw WIT
15451 // identifier accept-set the paired [`WitShape::classify`] total
15452 // function consumes on the sibling axis that the
15453 // `wit_shape_from_wire_and_classify_partition_the_axis` cross-
15454 // axis discipline pin locks the accept-sets against) trips at
15455 // caixa-core test time. The candidate set includes the empty
15456 // string, whitespace-only padding, PascalCase rebrand candidates
15457 // (`"Http"`, `"PubSub"`), snake_case rebrand candidates
15458 // (`"pub_sub"`), uppercase rebrand candidates (`"HTTP"`,
15459 // `"CAPABILITY"`), kebab-case rebrand candidates (`"pub-sub"`),
15460 // trailing/leading-whitespace-padded canonical scalars, the
15461 // trailing-newline shape, English-rebrand candidates
15462 // (`"messaging"`, `"cache"`), raw `:contratos :wit` identifiers
15463 // the sibling [`WitShape::classify`] axis consumes
15464 // (`"wasi:http/proxy"`, `"nats:events"`,
15465 // `"wasi:keyvalue/store"`) that must not silently leak across
15466 // the two-axis partition, the residual `"?"` and JSON-quoted
15467 // `"\"http\""` shape.
15468 //
15469 // Peer of the sibling
15470 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
15471 // (3c83606),
15472 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_rejects_unknown_byte_strings`]
15473 // (bf33136),
15474 // [`tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
15475 // (6fd00cd),
15476 // [`crate::supervisor::tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
15477 // (5b828ed), and
15478 // [`crate::supervisor::tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
15479 // (6fdd0d9) rejection witnesses.
15480 let rejected: &[&str] = &[
15481 "",
15482 " ",
15483 "\n",
15484 "\t",
15485 "Http",
15486 "HTTP",
15487 "PubSub",
15488 "PUBSUB",
15489 "Store",
15490 "STORE",
15491 "Capability",
15492 "CAPABILITY",
15493 "pub-sub",
15494 "pub_sub",
15495 "pubSub",
15496 "http ",
15497 " http",
15498 " store ",
15499 "capability\n",
15500 "http/",
15501 "messaging",
15502 "cache",
15503 "wasi:http/proxy",
15504 "wasi:keyvalue/store",
15505 "nats:events",
15506 "?",
15507 "\"http\"",
15508 ];
15509 for &input in rejected {
15510 assert_eq!(
15511 <WitShape as TryFrom<&str>>::try_from(input),
15512 Err(()),
15513 "TryFrom<&str> impl on WitShape must reject the \
15514 non-wire byte-string {input:?} — silent acceptance \
15515 signals an accept-set widening off the paired \
15516 WitShape::from_wire resolver, or a cross-axis leak \
15517 from the raw-identifier axis WitShape::classify consumes"
15518 );
15519 }
15520 }
15521
15522 #[test]
15523 fn wit_shape_try_from_str_and_from_wire_partition_the_accept_set() {
15524 // Cross-axis partition pin locking the newly lifted
15525 // `impl TryFrom<&str> for WitShape` and the substrate-primitive
15526 // [`WitShape::from_wire`] accessor to the same `Option<Self>`
15527 // output on every input — the two axes converge on the same
15528 // partition of `&str` by construction, and this pin asserts
15529 // that convergence directly rather than only through
15530 // [`WitShape::ALL`]'s per-arm sweep. Any future divergence (a
15531 // stray case-fold path on the trait axis that widens acceptance
15532 // past what `from_wire` admits, a silent per-arm short-circuit
15533 // that returns `Err(())` on an input `from_wire` accepts) trips
15534 // here under `assert_eq!` on every input in the sweep.
15535 //
15536 // Sweeps the four accepted census labels plus a representative
15537 // rejection set covering the same categories the sibling
15538 // `wit_shape_try_from_str_rejects_unknown_byte_strings` pin
15539 // enumerates, so a regression on either axis surfaces at the
15540 // partition pin rather than at a downstream consumer's silent
15541 // observation split.
15542 //
15543 // Peer of the sibling
15544 // [`crate::supervisor::tests::restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
15545 // (5b828ed) and
15546 // [`crate::supervisor::tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
15547 // (6fdd0d9) cross-axis partition pins.
15548 let inputs: &[&str] = &[
15549 "http",
15550 "pubsub",
15551 "store",
15552 "capability",
15553 "",
15554 " ",
15555 "Http",
15556 "PubSub",
15557 "HTTP",
15558 "pub-sub",
15559 "http ",
15560 "wasi:http/proxy",
15561 "wasi:keyvalue/store",
15562 "nats:events",
15563 "messaging",
15564 "?",
15565 ];
15566 for &input in inputs {
15567 assert_eq!(
15568 <WitShape as TryFrom<&str>>::try_from(input).ok(),
15569 WitShape::from_wire(input),
15570 "TryFrom<&str> and from_wire must agree on WitShape \
15571 for {input:?} — the trait-idiomatic and method-named \
15572 axes must partition the accept-set identically"
15573 );
15574 }
15575 }
15576
15577 #[test]
15578 fn wit_shape_from_into_static_str_routes_through_as_str_accessor() {
15579 // Fail-before-pass-after byte-parity pin on the newly lifted
15580 // `impl From<WitShape> for &'static str` — asserts the standard-
15581 // library trait impl and the substrate-primitive
15582 // [`WitShape::as_str`] `pub const fn` accessor resolve to the
15583 // same four-arm census-label emit-set across every arm the
15584 // exhaustive [`WitShape::ALL`] slice enumerates. Any future
15585 // silent detour that routes the trait impl through a divergent
15586 // projection (a per-arm inline `match shape { Http => "http", …
15587 // }` re-inlining that opens a compile-time link to the un-lifted
15588 // arm-literal outside the paired [`WitShape::as_str`] dispatch,
15589 // an accidental swap onto the sibling raw-identifier axis
15590 // [`WitShape::classify`] consumes that would collide the two-axis
15591 // wire/classifier split the sibling
15592 // `wit_shape_from_wire_and_classify_partition_the_axis` pin makes
15593 // load-bearing) trips at caixa-core test time under `assert_eq!`
15594 // rather than at a downstream `impl Into<&'static str>`-bound
15595 // consumer's silent split. Sweeps every one of the four arms
15596 // [`WitShape::ALL`] carries so no arm's projection is covered
15597 // only by the sibling method-named `as_str` /
15598 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
15599 // `<&'static str as From<WitShape>>::from` output in four
15600 // `const`-shape bindings against the paired [`WitShape::as_str`]
15601 // `pub const fn` accessor to make the `'static` lifetime promise
15602 // a build-time invariant — a future accidental downgrade of any
15603 // of the four arms' inline census-label byte-strings to a non-
15604 // `&'static str` (a `String::leak()`-produced return, a
15605 // `Box::leak`-cast, an intermediate lifetime-erasing helper)
15606 // trips at caixa-core build time rather than at a downstream
15607 // `'static`-bound consumer.
15608 //
15609 // Peer of the sibling
15610 // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
15611 // (523157d),
15612 // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
15613 // (9fb37d0),
15614 // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
15615 // (edb827b),
15616 // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
15617 // (c189a6f), and
15618 // [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
15619 // (afa3562) pins on the sibling closed-set typed-enum forward-
15620 // projection axes — extends the trait-idiomatic forward-
15621 // projection axis onto the sixth closed-set fieldless typed
15622 // enum on the caixa surface (the second M3-mesh-primitive-
15623 // defining slot enum, the `:contratos :wit` census-label axis
15624 // the caixa-mesh renderer keys off end-to-end).
15625 const HTTP: &str = WitShape::Http.as_str();
15626 const PUBSUB: &str = WitShape::PubSub.as_str();
15627 const STORE: &str = WitShape::Store.as_str();
15628 const CAPABILITY: &str = WitShape::Capability.as_str();
15629 for &variant in WitShape::ALL {
15630 let via_trait: &'static str = <&'static str as From<WitShape>>::from(variant);
15631 let via_method: &'static str = variant.as_str();
15632 assert_eq!(
15633 via_trait, via_method,
15634 "From<WitShape> for &'static str impl must round-trip \
15635 WitShape::{variant:?} to the same census-label \
15636 byte-string WitShape::as_str returns — divergence \
15637 signals a silent detour off the substrate-primitive \
15638 accessor"
15639 );
15640 let via_into: &'static str = variant.into();
15641 assert_eq!(
15642 via_into, via_method,
15643 "Into<&'static str>::into on WitShape::{variant:?} must \
15644 byte-equal WitShape::as_str on the same input — the \
15645 blanket-derived Into shape must resolve to the same \
15646 as_str dispatch as the explicit From impl"
15647 );
15648 }
15649 assert_eq!(
15650 [HTTP, PUBSUB, STORE, CAPABILITY],
15651 ["http", "pubsub", "store", "capability"],
15652 "const-context WitShape::as_str must resolve to the four \
15653 canonical census-label byte-strings — a future accidental \
15654 downgrade of any arm to a non-const or non-static byte-\
15655 string breaks the `&'static str`-lifetime promise the \
15656 paired From<WitShape> for &'static str impl carries by \
15657 construction"
15658 );
15659 }
15660
15661 #[test]
15662 fn wit_shape_from_into_static_str_and_as_str_partition_the_emit_set() {
15663 // Cross-axis partition pin: the paired trait-idiomatic
15664 // `From<WitShape> for &'static str` forward projection and the
15665 // method-named [`WitShape::as_str`] forward projection must
15666 // resolve identically on *every* arm, not just the ones named
15667 // in the primary byte-parity pin above. Sweeps every
15668 // [`WitShape::ALL`] arm and asserts the trait's `From::from`
15669 // output byte-equals the method-named accessor's return-value
15670 // on each, locking the two forward-projection paths together by
15671 // construction so any future detour (a stray `From` special-case
15672 // that lands on a divergent per-arm literal outside the paired
15673 // `as_str` dispatch, a hypothetical rebrand touching one axis
15674 // without the other) trips at caixa-core test time.
15675 //
15676 // Peer of the sibling forward-projection partition pins
15677 // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
15678 // (523157d),
15679 // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
15680 // (9fb37d0),
15681 // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
15682 // (edb827b),
15683 // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
15684 // (c189a6f), and
15685 // [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
15686 // (afa3562) — extends the round-trip discipline onto the sixth
15687 // closed-set typed enum on the caixa surface, closing the two-
15688 // way `Self ↔ &'static str` round-trip on the trait-idiomatic
15689 // pair (`From<Self> for &'static str` + `TryFrom<&str> for
15690 // Self`) as well as the pre-existing method-named pair
15691 // (`as_str` + `from_wire`).
15692 for &variant in WitShape::ALL {
15693 let via_trait: &'static str = <&'static str as From<WitShape>>::from(variant);
15694 let via_method: &'static str = variant.as_str();
15695 assert_eq!(
15696 via_trait, via_method,
15697 "From<WitShape> for &'static str and WitShape::as_str \
15698 must resolve identically on WitShape::{variant:?} — \
15699 divergence signals the two forward-projection paths \
15700 have drifted onto different emit-sets"
15701 );
15702 }
15703 // Round-trip witness: every arm's forward `From` output re-parses
15704 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
15705 // to the original variant. Closes the two-way `WitShape ↔
15706 // &'static str` round-trip on the trait-idiomatic axis pair
15707 // directly (no wire-vocab intermediate the peer [`CaixaKind`]
15708 // axis pair requires — the emit-side [`WitShape::as_str`] and
15709 // the parse-side [`WitShape::from_wire`] dispatch on the same
15710 // four inline census-label byte-strings by construction), and
15711 // in the same way the peer [`PlacementStrategy`] axis pair
15712 // (afa3562) closes on its three-arm surface — mirroring the
15713 // pre-existing method-named `as_str` + `from_wire` round-trip
15714 // on the substrate-primitive axis pair.
15715 for &variant in WitShape::ALL {
15716 let emitted: &'static str = variant.into();
15717 let re_parsed: Result<WitShape, ()> = <WitShape as TryFrom<&str>>::try_from(emitted);
15718 assert_eq!(
15719 re_parsed,
15720 Ok(variant),
15721 "trait-idiomatic axis pair must round-trip \
15722 WitShape::{variant:?} through `.into::<&'static \
15723 str>()` and back through `TryFrom<&str>` — a break \
15724 signals the forward-emit and reverse-parse axes have \
15725 drifted onto different vocabularies"
15726 );
15727 }
15728 }
15729
15730 #[test]
15731 fn wit_shape_classify_matches_wit_contract_target_arm_on_valid_inputs() {
15732 // Cross-surface equivalence pin: for every canonical
15733 // truth-table row that also validates cleanly through
15734 // [`WitContract::target`], the pre-projection [`WitShape`] arm
15735 // matches the post-projection [`WitTarget`] arm — the pre- and
15736 // post-validation classifications agree on the arm identity
15737 // even though the payload-carrying view carries additional
15738 // per-arm information. A future edit that reroutes
15739 // `WitContract::target`'s HTTP/pubsub/store dispatch through a
15740 // different predicate than the [`WitShape::classify`] the free
15741 // predicates now route through would trip here at the offending
15742 // row rather than at a downstream renderer.
15743 //
15744 // The Capability arm is excluded from the paired sweep: an
15745 // arbitrary Capability-classified string need not pass
15746 // [`crate::render::is_wit_world_ref`]'s value-shape gate, so
15747 // `WitContract::target` would raise `ContratoWitInvalid`
15748 // rather than return `WitTarget::Capability`; the arm-identity
15749 // agreement lives in the payload-arm rows.
15750 //
15751 // Per-row shape: `(wit, endpoint, subject, slot)` — one row per
15752 // payload arm with its shape's canonical payload field filled
15753 // and the peer fields `None`. Named type-alias closes the
15754 // `clippy::type_complexity` warning the raw tuple triggers.
15755 type WitTargetArmRow = (
15756 &'static str,
15757 Option<&'static str>,
15758 Option<&'static str>,
15759 Option<&'static str>,
15760 );
15761 let cases: [WitTargetArmRow; 6] = [
15762 ("wasi:http/proxy", Some("/x"), None, None),
15763 ("http:incoming", Some("/x"), None, None),
15764 ("nats:events", None, Some("subject.x"), None),
15765 ("kafka:topic", None, Some("subject.x"), None),
15766 ("wasi:keyvalue/store", None, None, Some("bucket/x")),
15767 ("kv:cache", None, None, Some("bucket/x")),
15768 ];
15769 for (wit, endpoint, subject, slot) in cases {
15770 let c = WitContract {
15771 de: "cart".into(),
15772 para: "catalog".into(),
15773 wit: wit.to_string(),
15774 endpoint: endpoint.map(str::to_string),
15775 subject: subject.map(str::to_string),
15776 slot: slot.map(str::to_string),
15777 };
15778 let target = c.target().unwrap_or_else(|e| {
15779 panic!("expected target() to validate for wit={wit:?}, got: {e}")
15780 });
15781 let shape = WitShape::classify(wit);
15782 // Match arm-for-arm — the raw &str classifier and the
15783 // validated payload view must agree on which arm carries
15784 // the edge.
15785 let agree = matches!(
15786 (shape, target),
15787 (WitShape::Http, WitTarget::Http { .. })
15788 | (WitShape::PubSub, WitTarget::PubSub { .. })
15789 | (WitShape::Store, WitTarget::Store { .. })
15790 | (WitShape::Capability, WitTarget::Capability)
15791 );
15792 assert!(
15793 agree,
15794 "WitShape::classify({wit:?}) and WitContract::target arm-identity disagree",
15795 );
15796 }
15797 }
15798
15799 #[test]
15800 fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
15801 // Composition-witness pin: [`wit_shape_matches`] agrees with
15802 // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
15803 // dispatch (the prior non-`const` implementation) across
15804 // boundary lengths — empty `wit`, empty prefix, one-byte
15805 // slack, prefix longer than `wit`, one-byte trailing slack.
15806 // The rewrite to a byte-level manual starts_with loop (the
15807 // enabler for the `pub const fn` posture) must not change any
15808 // truth-table entry on the canonical accept-set — this pin
15809 // sweeps a targeted boundary corpus and asserts byte-for-byte
15810 // agreement, locking the const-fn rewrite's semantics against
15811 // the prior iterator body by construction.
15812 let prefixes = &["wasi:http/", "http:"][..];
15813 let cases: [(&str, bool); 12] = [
15814 ("wasi:http/proxy", true),
15815 ("wasi:http/", true), // exact-length match on prefix
15816 ("wasi:http", false), // one byte short
15817 ("http:", true),
15818 ("http:incoming", true),
15819 ("http", false), // one byte short
15820 ("", false),
15821 ("wasi:https/proxy", false),
15822 ("nats:events", false),
15823 ("HTTPS:", false), // uppercase — no case-fold in classifier
15824 ("wasi:HTTP/proxy", false),
15825 ("wasi:http", false),
15826 ];
15827 for (wit, expected) in cases {
15828 assert_eq!(
15829 wit_shape_matches(wit, prefixes),
15830 expected,
15831 "wit_shape_matches disagrees with reference at wit={wit:?}",
15832 );
15833 // Byte-equal to the iterator body it replaced.
15834 let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
15835 assert_eq!(
15836 wit_shape_matches(wit, prefixes),
15837 via_iter,
15838 "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
15839 );
15840 }
15841 // Empty prefix set → always false regardless of `wit`.
15842 let empty: &[&str] = &[];
15843 assert!(!wit_shape_matches("", empty));
15844 assert!(!wit_shape_matches("wasi:http/proxy", empty));
15845 // Empty prefix inside a non-empty set → always true (every
15846 // string starts with the empty string, matching the
15847 // iterator body's semantics on `str::starts_with("")`).
15848 let contains_empty: &[&str] = &["nats:", ""];
15849 assert!(wit_shape_matches("", contains_empty));
15850 assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
15851 }
15852
15853 #[test]
15854 fn wit_contract_is_capability_partitions_the_wit_shape_space() {
15855 // 4-way partition-witness pin: for every canonical prefix in
15856 // the payload-arm accept-sets, exactly one of the four
15857 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
15858 // [`WitContract::is_store`] / [`WitContract::is_capability`]
15859 // predicates returns `true` and the other three return `false`
15860 // — the four-arm partition witness that locks the substrate's
15861 // WIT-shape-space closure on the pre-projection axis load-
15862 // bearing. A future arm addition (a hypothetical fourth
15863 // payload-shape prefix set, a `wasi:sockets/*` transport-layer
15864 // shape) that landed on one of the payload-arm predicates
15865 // without shrinking [`WitContract::is_capability`]'s accept-set
15866 // would surface here as two arms returning `true` simultaneously
15867 // — a partition-witness break the pin catches at caixa-core
15868 // build time rather than a silent per-consumer misclassification
15869 // at renderer emit time. Peer of the sibling `WitTarget`-side
15870 // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
15871 // partition-witness pin on the post-projection payload-scalar
15872 // arm-set — extends the discipline onto the pre-projection
15873 // 4-arm shape-space.
15874 for shape_set in [
15875 WIT_HTTP_SHAPE_PREFIXES,
15876 WIT_PUBSUB_SHAPE_PREFIXES,
15877 WIT_STORE_SHAPE_PREFIXES,
15878 ] {
15879 for prefix in shape_set {
15880 let c = WitContract {
15881 de: "cart".into(),
15882 para: "catalog".into(),
15883 wit: format!("{prefix}x"),
15884 endpoint: None,
15885 subject: None,
15886 slot: None,
15887 };
15888 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
15889 .iter()
15890 .filter(|&&b| b)
15891 .count();
15892 assert_eq!(
15893 hits,
15894 1,
15895 "WitContract WIT-shape 4-way predicate partition must \
15896 admit exactly one arm per canonical prefix; got {hits} \
15897 hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
15898 is_capability={})",
15899 c.wit,
15900 c.is_http(),
15901 c.is_pubsub(),
15902 c.is_store(),
15903 c.is_capability(),
15904 );
15905 }
15906 }
15907 // Capability-arm sweep: two representative capability shapes
15908 // (a bare WIT world outside the three payload-arm prefix sets,
15909 // and the deliberately-shaped empty string that
15910 // [`crate::render::is_wit_world_ref`] rejects at
15911 // [`WitContract::target`] time but which the pure classifier
15912 // still admits — see the method docstring's "purely syntactic
15913 // classification" note). Both must land on the fourth arm
15914 // exclusively, so the partition witness holds across the full
15915 // 4-arm closure.
15916 for wit in ["custom:capability-only", ""] {
15917 let c = WitContract {
15918 de: "cart".into(),
15919 para: "catalog".into(),
15920 wit: wit.into(),
15921 endpoint: None,
15922 subject: None,
15923 slot: None,
15924 };
15925 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
15926 .iter()
15927 .filter(|&&b| b)
15928 .count();
15929 assert_eq!(
15930 hits, 1,
15931 "WitContract WIT-shape 4-way predicate partition must \
15932 admit exactly one arm on Capability-shaped wit={wit:?}"
15933 );
15934 assert!(
15935 c.is_capability(),
15936 "wit={wit:?} must project onto the Capability arm"
15937 );
15938 }
15939 }
15940
15941 #[test]
15942 fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
15943 // Composition-witness pin: [`WitContract::is_capability`] is the
15944 // exact-inverse disjunction of the sibling payload-arm predicate
15945 // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
15946 // [`WitContract::is_store`]. A future reimplementation that
15947 // grew its own prefix-set scan (e.g. inlining a fourth
15948 // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
15949 // own today) rather than delegating to the sibling trio would
15950 // drift loudly here — the composition contract binds the
15951 // fourth-arm predicate to the exact-inverse of the three
15952 // payload-arm predicates, so any rebrand of any prefix-set const
15953 // flows through this method by construction without a
15954 // coordinated per-consumer rewrite. Sweeps the union of the
15955 // three payload-arm prefix sets plus two Capability-shaped
15956 // shapes (a bare non-prefix-matching WIT world, the deliberately-
15957 // empty string the pure classifier still admits per the method
15958 // docstring's "purely syntactic classification" note).
15959 let mut cases: Vec<String> = Vec::new();
15960 for shape_set in [
15961 WIT_HTTP_SHAPE_PREFIXES,
15962 WIT_PUBSUB_SHAPE_PREFIXES,
15963 WIT_STORE_SHAPE_PREFIXES,
15964 ] {
15965 for prefix in shape_set {
15966 cases.push(format!("{prefix}x"));
15967 }
15968 }
15969 cases.push("custom:capability-only".to_string());
15970 cases.push(String::new());
15971 for wit in cases {
15972 let c = WitContract {
15973 de: "cart".into(),
15974 para: "catalog".into(),
15975 wit: wit.clone(),
15976 endpoint: None,
15977 subject: None,
15978 slot: None,
15979 };
15980 assert_eq!(
15981 c.is_capability(),
15982 !c.is_http() && !c.is_pubsub() && !c.is_store(),
15983 "WitContract::is_capability must equal \
15984 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
15985 );
15986 }
15987 }
15988
15989 #[test]
15990 fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
15991 // Cross-projection-witness pin: whenever [`WitContract::target`]
15992 // succeeds, the pre-projection [`WitContract::is_capability`]
15993 // classification agrees with the post-projection
15994 // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
15995 // predicate — the 4-arm typed partition on the substrate's
15996 // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
15997 // partition on the pre-projection axis line up by construction.
15998 // A future divergence between the two axes (a peer
15999 // [`WitTarget`] variant addition that landed on the typed-view
16000 // surface without a peer prefix-set + [`WitContract`] predicate
16001 // extension, or vice versa) would surface here at caixa-core
16002 // build time rather than a silent per-consumer split at renderer
16003 // emit time. Peer of the sibling pre-/post-projection
16004 // agreement pins the payload-carrier trio
16005 // ([`WitContract::endpoint`] / [`WitContract::subject`] /
16006 // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
16007 // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
16008 // post-projection — b11bb49 trio lift) already carry across the
16009 // three payload arms — this pin closes the pair on the fourth
16010 // payload-less arm.
16011 let http = WitContract {
16012 de: "cart".into(),
16013 para: "catalog".into(),
16014 wit: "wasi:http/proxy".into(),
16015 endpoint: Some("/x".into()),
16016 subject: None,
16017 slot: None,
16018 };
16019 assert!(!http.is_capability());
16020 assert!(!http.target().unwrap().is_capability());
16021
16022 let nats = WitContract {
16023 de: "cart".into(),
16024 para: "catalog".into(),
16025 wit: "nats:pub-sub".into(),
16026 endpoint: None,
16027 subject: Some("events.x".into()),
16028 slot: None,
16029 };
16030 assert!(!nats.is_capability());
16031 assert!(!nats.target().unwrap().is_capability());
16032
16033 let kv = WitContract {
16034 de: "cart".into(),
16035 para: "catalog".into(),
16036 wit: "wasi:keyvalue/store".into(),
16037 endpoint: None,
16038 subject: None,
16039 slot: Some("checkout/$orderId".into()),
16040 };
16041 assert!(!kv.is_capability());
16042 assert!(!kv.target().unwrap().is_capability());
16043
16044 let cap = WitContract {
16045 de: "cart".into(),
16046 para: "catalog".into(),
16047 wit: "custom:capability-only".into(),
16048 endpoint: None,
16049 subject: None,
16050 slot: None,
16051 };
16052 assert!(cap.is_capability());
16053 assert!(cap.target().unwrap().is_capability());
16054 }
16055
16056 #[test]
16057 fn wit_contract_pre_projection_accessor_family_is_const_fn() {
16058 // Fail-before-pass-after pin on the [`WitContract`] pre-
16059 // projection accessor family's `const`-eval-surface posture.
16060 // Each of the three per-`:contratos` byte-string scalar
16061 // accessors ([`WitContract::source`] / [`WitContract::destination`]
16062 // / [`WitContract::world_ref`], each projecting through
16063 // `String::as_str` — const-stable since Rust 1.87, well within
16064 // the workspace MSRV) and each of the four peer WIT-shape
16065 // predicates ([`WitContract::is_http`] /
16066 // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
16067 // [`WitContract::is_capability`], each composing
16068 // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
16069 // free-function classifier family the sibling
16070 // [`wit_shape_classifier_family_is_const_fn`] pin already
16071 // anchors on the raw `&str → bool` axis) must be `pub const fn`
16072 // — any future accidental downgrade to non-`const` fails the
16073 // `const fn` wrappers below at caixa-core build time with E0015
16074 // (`cannot call non-const function`), strictly stronger than a
16075 // runtime `assert!` and strictly stronger than a
16076 // module-scope `const _: () = assert!(…)` pin (which cannot be
16077 // formed on a `&WitContract` fixture because the type's
16078 // `String` / `Option<String>` carriers rule out `const`-context
16079 // construction; the `const fn` wrapper is the load-bearing
16080 // shape that side-steps the destructor-in-const restriction on
16081 // the value axis while still pinning the `const`-fn posture on
16082 // the callee).
16083 //
16084 // Peer of the sibling free-function classifier pin
16085 // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
16086 // raw `&str → bool` axis — this pin extends the same
16087 // `const`-eval-surface discipline onto the peer method surface
16088 // that composes through those free-function classifiers, and
16089 // simultaneously onto the underlying per-`:contratos`
16090 // byte-string scalar-accessor trio each predicate reads
16091 // through. Sibling of the peer M3
16092 // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
16093 // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
16094 // M2
16095 // [`child_spec_restart_accessor_is_const_fn`] /
16096 // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
16097 // and M3
16098 // [`placement_estrategia_accessor_is_const_fn`] /
16099 // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
16100 // sibling `const`-eval-surface-pass axes.
16101 const fn source_via_const_fn(c: &WitContract) -> &str {
16102 c.source()
16103 }
16104 const fn destination_via_const_fn(c: &WitContract) -> &str {
16105 c.destination()
16106 }
16107 const fn world_ref_via_const_fn(c: &WitContract) -> &str {
16108 c.world_ref()
16109 }
16110 const fn is_http_via_const_fn(c: &WitContract) -> bool {
16111 c.is_http()
16112 }
16113 const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
16114 c.is_pubsub()
16115 }
16116 const fn is_store_via_const_fn(c: &WitContract) -> bool {
16117 c.is_store()
16118 }
16119 const fn is_capability_via_const_fn(c: &WitContract) -> bool {
16120 c.is_capability()
16121 }
16122 // Sweep one canonical accept-set sample per WIT-shape arm plus
16123 // a payload-less capability sample, asserting the wrapper and
16124 // direct dispatches agree byte-for-byte across the closed
16125 // 4-arm partition on both the scalar-accessor trio and the
16126 // WIT-shape-predicate family.
16127 for (wit, is_http, is_pubsub, is_store, is_capability) in [
16128 ("wasi:http/proxy", true, false, false, false),
16129 ("http:incoming", true, false, false, false),
16130 ("nats:events", false, true, false, false),
16131 ("kafka:topic", false, true, false, false),
16132 ("wasi:keyvalue/store", false, false, true, false),
16133 ("kv:cache", false, false, true, false),
16134 ("custom:capability-only", false, false, false, true),
16135 ("", false, false, false, true),
16136 ] {
16137 let c = WitContract {
16138 de: "cart".into(),
16139 para: "catalog".into(),
16140 wit: wit.into(),
16141 endpoint: None,
16142 subject: None,
16143 slot: None,
16144 };
16145 assert_eq!(source_via_const_fn(&c), c.source());
16146 assert_eq!(destination_via_const_fn(&c), c.destination());
16147 assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
16148 assert_eq!(is_http_via_const_fn(&c), c.is_http());
16149 assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
16150 assert_eq!(is_store_via_const_fn(&c), c.is_store());
16151 assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
16152 assert_eq!(c.source(), "cart");
16153 assert_eq!(c.destination(), "catalog");
16154 assert_eq!(c.world_ref(), wit);
16155 assert_eq!(c.is_http(), is_http);
16156 assert_eq!(c.is_pubsub(), is_pubsub);
16157 assert_eq!(c.is_store(), is_store);
16158 assert_eq!(c.is_capability(), is_capability);
16159 }
16160 }
16161
16162 #[test]
16163 fn wit_contract_identity_projection_accessor_is_const_fn() {
16164 // Fail-before-pass-after pin on the [`WitContract::identity`]
16165 // six-arm composite-projection accessor's `const`-eval-surface
16166 // posture. The accessor projects the typed edge's six identity
16167 // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
16168 // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
16169 // every callee is itself `pub const fn` ([`WitContract::source`]
16170 // / [`WitContract::destination`] / [`WitContract::world_ref`]
16171 // through `String::as_str`, const-stable since Rust 1.87;
16172 // [`WitContract::endpoint`] / [`WitContract::subject`] /
16173 // [`WitContract::slot`] through the sibling `match &self
16174 // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
16175 // 0650f64 closed the const-eval surface on) and the tuple
16176 // constructor from borrowed-reference / `Option`-of-borrowed-
16177 // reference arms is trivially const. Any future accidental
16178 // downgrade fails the `identity_via_const_fn` wrapper at
16179 // caixa-core build time with E0015 (`cannot call non-const
16180 // method`), strictly stronger than a runtime `assert!` and
16181 // strictly stronger than a module-scope `const _: () =
16182 // assert!(…)` pin (which cannot be formed on a `&WitContract`
16183 // fixture because the type's `String` / `Option<String>`
16184 // carriers rule out `const`-context value construction; the
16185 // `const fn` wrapper is the load-bearing shape that side-steps
16186 // the destructor-in-const restriction on the value axis while
16187 // still pinning the `const`-fn posture on the callee — mirror
16188 // of the sibling
16189 // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
16190 // pin's discipline verbatim on the peer scalar-accessor
16191 // surface).
16192 //
16193 // Peer of the sibling
16194 // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
16195 // (279823b) pin on the six per-`:contratos` scalar-accessor
16196 // callees this composite-projection reads through — where that
16197 // pin anchors the const-eval surface at the six individual
16198 // scalar-accessor arms, this pin extends the same posture onto
16199 // the composite six-tuple projection every consumer that dedups
16200 // typed edges on the [`ContratoIdentity`] axis keys off (the
16201 // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
16202 // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
16203 // materializer's per-edge identity-based admission webhook; a
16204 // future L7 policy-emitter that shards CNPs by identity-tuple
16205 // rather than by name). Same fail-before-pass-after wrapper
16206 // discipline as the peer M2 / M3 accessor-family pins on the
16207 // sibling `const`-eval-surface passes.
16208 const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
16209 c.identity()
16210 }
16211 // Sweep one canonical WIT-shape sample per payload-carrier arm
16212 // plus a payload-less capability sample so the pin exercises
16213 // both `Some(_)`-carrying and `None`-carrying arms on all three
16214 // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
16215 // / `:slot`) — every wrapper dispatch must agree byte-for-byte
16216 // with the direct method call on every arm of the closed WIT-
16217 // shape partition.
16218 for (wit, endpoint, subject, slot) in [
16219 ("wasi:http/proxy", Some("/checkout"), None, None),
16220 ("http:incoming", Some("/api"), None, None),
16221 ("nats:events", None, Some("orders.placed"), None),
16222 ("kafka:topic", None, Some("orders.stream"), None),
16223 ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
16224 ("kv:cache", None, None, Some("session/{token}")),
16225 ("custom:capability-only", None, None, None),
16226 ] {
16227 let c = WitContract {
16228 de: "cart".into(),
16229 para: "catalog".into(),
16230 wit: wit.into(),
16231 endpoint: endpoint.map(str::to_string),
16232 subject: subject.map(str::to_string),
16233 slot: slot.map(str::to_string),
16234 };
16235 assert_eq!(identity_via_const_fn(&c), c.identity());
16236 assert_eq!(
16237 c.identity(),
16238 ("cart", "catalog", wit, endpoint, subject, slot,),
16239 );
16240 }
16241 }
16242
16243 #[test]
16244 fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
16245 // Fail-before-pass-after pin on the four M3 mesh-slot
16246 // `String → &str` scalar accessors ([`Membro::nome`] /
16247 // [`Membro::versao_requirement`] on the per-`:membros` axis,
16248 // [`Entrada::hostname`] / [`Entrada::destination`] on the
16249 // per-`:entrada` axis) — each projects the typed slot's
16250 // [`String`] storage through the `pub const fn`
16251 // [`String::as_str`] (const-stable since Rust 1.87, well
16252 // within the workspace MSRV) and any future accidental
16253 // downgrade to non-`const` fails the corresponding
16254 // `<name>_via_const_fn` wrapper at caixa-core build time with
16255 // E0015 (`cannot call non-const method`), strictly stronger
16256 // than a runtime `assert!` and strictly stronger than a
16257 // module-scope `const _: () = assert!(…)` pin (which cannot
16258 // be formed on `&Membro` / `&Entrada` fixtures because the
16259 // types' `String` carriers rule out `const`-context value
16260 // construction; the `const fn` wrapper is the load-bearing
16261 // shape that side-steps the destructor-in-const restriction
16262 // on the value axis while still pinning the `const`-fn
16263 // posture on the callee — mirror of the sibling
16264 // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
16265 // (279823b) pin on the per-`:contratos` axis). Peer of the
16266 // sibling per-M2/M3/universal-axis `String → &str` accessor
16267 // family pins on the sibling `const`-eval-surface passes
16268 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
16269 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
16270 // typed-newtype wrapper,
16271 // [`crate::supervisor::ChildSpec::nome`] /
16272 // [`crate::supervisor::ChildSpec::versao_requirement`] at the
16273 // M2 supervisor-tree axis,
16274 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
16275 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
16276 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
16277 // axis, and the sibling per-`:contratos`
16278 // [`WitContract::source`] / [`WitContract::destination`] /
16279 // [`WitContract::world_ref`] trio at 279823b).
16280 const fn membro_nome_via_const_fn(m: &Membro) -> &str {
16281 m.nome()
16282 }
16283 const fn membro_versao_via_const_fn(m: &Membro) -> &str {
16284 m.versao_requirement()
16285 }
16286 const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
16287 e.hostname()
16288 }
16289 const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
16290 e.destination()
16291 }
16292 for (caixa, versao) in [
16293 ("cart", "^0.1"),
16294 ("catalog-v2", "~0.2.3"),
16295 ("checkout", "*"),
16296 ] {
16297 let m = Membro {
16298 caixa: caixa.into(),
16299 versao: versao.into(),
16300 };
16301 assert_eq!(membro_nome_via_const_fn(&m), m.nome());
16302 assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
16303 assert_eq!(m.nome(), caixa);
16304 assert_eq!(m.versao_requirement(), versao);
16305 }
16306 for (host, para) in [
16307 ("cart.example.com", "cart"),
16308 ("api.checkout.io", "checkout"),
16309 ] {
16310 let e = Entrada {
16311 host: host.into(),
16312 para: para.into(),
16313 paths: vec![],
16314 port: DEFAULT_SERVICO_PORT,
16315 };
16316 assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
16317 assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
16318 assert_eq!(e.hostname(), host);
16319 assert_eq!(e.destination(), para);
16320 }
16321 }
16322
16323 #[test]
16324 fn m3_option_string_scalar_accessor_family_is_const_fn() {
16325 // Fail-before-pass-after pin on the five M3 mesh-slot
16326 // `Option<String> → Option<&str>` scalar accessors
16327 // ([`WitContract::endpoint`] / [`WitContract::subject`] /
16328 // [`WitContract::slot`] on the per-`:contratos` HTTP /
16329 // pub-sub / key-value payload-carrier trio,
16330 // [`Placement::shard_key`] / [`Placement::affinity`] on the
16331 // per-`:placement` Akka-sharding-key + Adaptive-compression-
16332 // hint pair). Each accessor destructures the typed slot's
16333 // `Option<String>` storage through the `match &self.<field> {
16334 // Some(s) => Some(s.as_str()), None => None }` shape —
16335 // routing through [`String::as_str`] (const-stable since Rust
16336 // 1.87, well within the workspace MSRV) rather than the
16337 // non-const [`Option::as_deref`] the pre-lift bodies carried
16338 // — and any future accidental downgrade to non-`const` fails
16339 // the corresponding `<name>_via_const_fn` wrapper at
16340 // caixa-core build time with E0015 (`cannot call non-const
16341 // method`), strictly stronger than a runtime `assert!` and
16342 // strictly stronger than a module-scope `const _: () =
16343 // assert!(…)` pin (which cannot be formed on `&WitContract`
16344 // / `&Placement` fixtures because the types' `String` /
16345 // `Option<String>` carriers rule out `const`-context value
16346 // construction; the `const fn` wrapper is the load-bearing
16347 // shape that side-steps the destructor-in-const restriction
16348 // on the value axis while still pinning the `const`-fn
16349 // posture on the callee — mirror of the sibling
16350 // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
16351 // (279823b) and
16352 // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
16353 // (29c5d7e) pins on the peer `String → &str` axes at the same
16354 // structs).
16355 //
16356 // Peer of the sibling per-`Caixa` `Option<String> →
16357 // Option<&str>` accessor family pin
16358 // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
16359 // on the top-level manifest's optional universal-axis surface
16360 // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
16361 // `:restart-window`).
16362 const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
16363 w.endpoint()
16364 }
16365 const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
16366 w.subject()
16367 }
16368 const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
16369 w.slot()
16370 }
16371 const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
16372 p.shard_key()
16373 }
16374 const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
16375 p.affinity()
16376 }
16377 // Sweep every closed shape-arm partition on the
16378 // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
16379 // Some, sibling pair None), pub-sub (`:subject` Some, sibling
16380 // pair None), key-value (`:slot` Some, sibling pair None),
16381 // and Capability (all three None) so each accessor's
16382 // Some/None arm carries a pin through the const dispatch.
16383 for (wit, endpoint, subject, slot) in [
16384 ("wasi:http/proxy", Some("/api"), None, None),
16385 ("nats:pub-sub", None, Some("orders.paid"), None),
16386 ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
16387 ("custom:capability-only", None, None, None),
16388 ] {
16389 let c = WitContract {
16390 de: "cart".into(),
16391 para: "catalog".into(),
16392 wit: wit.into(),
16393 endpoint: endpoint.map(str::to_string),
16394 subject: subject.map(str::to_string),
16395 slot: slot.map(str::to_string),
16396 };
16397 assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
16398 assert_eq!(wit_subject_via_const_fn(&c), c.subject());
16399 assert_eq!(wit_slot_via_const_fn(&c), c.slot());
16400 assert_eq!(c.endpoint(), endpoint);
16401 assert_eq!(c.subject(), subject);
16402 assert_eq!(c.slot(), slot);
16403 }
16404 // Sweep both `Some`/`None` arms on each per-`:placement`
16405 // optional-scalar so the shard-key + affinity pair carries a
16406 // const-dispatch pin on both arms.
16407 for (shard_key, affinity) in [
16408 (Some("tenantId"), Some("data-locality")),
16409 (Some("$tenantId"), None),
16410 (None, Some("low-latency")),
16411 (None, None),
16412 ] {
16413 let p = Placement {
16414 estrategia: PlacementStrategy::default(),
16415 clusters: vec![],
16416 affinity: affinity.map(str::to_string),
16417 shard_key: shard_key.map(str::to_string),
16418 };
16419 assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
16420 assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
16421 assert_eq!(p.shard_key(), shard_key);
16422 assert_eq!(p.affinity(), affinity);
16423 }
16424 }
16425
16426 #[test]
16427 fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
16428 // Fail-before-pass-after pin on the two M3-mesh-slot inner-
16429 // composite `Vec → &[String]` slice-return accessors on
16430 // [`Placement::clusters`] and [`Entrada::paths`]. Each
16431 // destructures the typed slot's `Vec<String>` storage through
16432 // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
16433 // 1.66, well within the workspace MSRV) — any future accidental
16434 // downgrade to non-`const` fails the corresponding
16435 // `<name>_via_const_fn` wrapper at caixa-core build time with
16436 // E0015 (`cannot call non-const method`), strictly stronger
16437 // than a runtime `assert!`. Sibling of the peer
16438 // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
16439 // pin on the outer-`AplicacaoSpec` reference-return family
16440 // (`:membros` / `:contratos` slice-return + `:politicas` /
16441 // `:placement` / `:entrada` composite-reference), and of the
16442 // peer M2 slice-return axis pins
16443 // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
16444 // (on `SupervisorSpec::children`) and
16445 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
16446 // (on `UpgradeFromEntry::instructions`). Together the four
16447 // pins close the last unlifted reference-return accessor
16448 // family across the substrate primitive.
16449 const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
16450 p.clusters()
16451 }
16452 const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
16453 e.paths()
16454 }
16455 // Sweep both the empty-Vec (no author-declared entries) and
16456 // the populated-Vec arms on every slice-return accessor so
16457 // each carries a const-dispatch pin on both arms.
16458 let p_empty = Placement {
16459 estrategia: PlacementStrategy::default(),
16460 clusters: vec![],
16461 affinity: None,
16462 shard_key: None,
16463 };
16464 let p_full = Placement {
16465 estrategia: PlacementStrategy::default(),
16466 clusters: vec!["prod-a".into(), "prod-b".into()],
16467 affinity: None,
16468 shard_key: None,
16469 };
16470 assert_eq!(
16471 placement_clusters_via_const_fn(&p_empty),
16472 p_empty.clusters()
16473 );
16474 assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
16475 assert!(p_empty.clusters().is_empty());
16476 assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
16477 let e_empty = Entrada {
16478 host: "web.example.com".into(),
16479 para: "web".into(),
16480 paths: vec![],
16481 port: DEFAULT_SERVICO_PORT,
16482 };
16483 let e_full = Entrada {
16484 host: "web.example.com".into(),
16485 para: "web".into(),
16486 paths: vec!["/api".into(), "/health".into()],
16487 port: DEFAULT_SERVICO_PORT,
16488 };
16489 assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
16490 assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
16491 assert!(e_empty.paths().is_empty());
16492 assert_eq!(e_full.paths(), &["/api", "/health"]);
16493 }
16494
16495 #[test]
16496 fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
16497 // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
16498 // reference-return accessors — the two `Vec → &[T]` slice-
16499 // return accessors on [`AplicacaoSpec::membros`] and
16500 // [`AplicacaoSpec::contratos`] (each routes through the
16501 // `pub const fn` [`Vec::as_slice`], const-stable since Rust
16502 // 1.66), the two `&Composite` composite-reference accessors
16503 // on [`AplicacaoSpec::politicas`] and
16504 // [`AplicacaoSpec::placement`] (each routes through a raw
16505 // `&self.<field>` borrow, trivially const), and the one
16506 // `Option<&Composite>` optional-composite-reference accessor
16507 // on [`AplicacaoSpec::entrada`] (routes through the
16508 // `pub const fn` [`Option::as_ref`], const-stable since Rust
16509 // 1.83). Any future accidental downgrade to non-`const` fails
16510 // the corresponding `<name>_via_const_fn` wrapper at caixa-
16511 // core build time with E0015 (`cannot call non-const
16512 // method`), strictly stronger than a runtime `assert!`.
16513 // Sibling of the peer inner-composite pin
16514 // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
16515 // on the `Placement::clusters` + `Entrada::paths` slice-
16516 // return pair, and of the peer M2 axis pins on
16517 // [`crate::supervisor::SupervisorSpec::children`] and
16518 // [`crate::upgrade::UpgradeFromEntry::instructions`].
16519 const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
16520 s.membros()
16521 }
16522 const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
16523 s.contratos()
16524 }
16525 const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
16526 s.politicas()
16527 }
16528 const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
16529 s.placement()
16530 }
16531 const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
16532 s.entrada()
16533 }
16534 // Construct both a minimal "no :entrada" (internal-only
16535 // mesh) and a full "with :entrada" (external-gateway)
16536 // fixture so the family pins both the `None`-arm (author-
16537 // omitted `:entrada`) and the `Some`-arm (author-declared
16538 // `:entrada`) on the optional-composite axis.
16539 let membro = Membro {
16540 caixa: "web".into(),
16541 versao: "^0.1".into(),
16542 };
16543 let entrada_full = Entrada {
16544 host: "web.example.com".into(),
16545 para: "web".into(),
16546 paths: vec!["/api".into()],
16547 port: DEFAULT_SERVICO_PORT,
16548 };
16549 let internal_only = AplicacaoSpec {
16550 membros: vec![membro.clone()],
16551 contratos: vec![],
16552 politicas: MeshPolicy::default(),
16553 placement: Placement::default(),
16554 entrada: None,
16555 };
16556 let with_entrada = AplicacaoSpec {
16557 membros: vec![membro],
16558 contratos: vec![],
16559 politicas: MeshPolicy::default(),
16560 placement: Placement::default(),
16561 entrada: Some(entrada_full),
16562 };
16563 assert_eq!(
16564 aplicacao_membros_via_const_fn(&internal_only),
16565 internal_only.membros()
16566 );
16567 assert_eq!(
16568 aplicacao_membros_via_const_fn(&with_entrada),
16569 with_entrada.membros()
16570 );
16571 assert_eq!(
16572 aplicacao_contratos_via_const_fn(&internal_only),
16573 internal_only.contratos()
16574 );
16575 assert!(std::ptr::eq(
16576 aplicacao_politicas_via_const_fn(&internal_only),
16577 internal_only.politicas(),
16578 ));
16579 assert!(std::ptr::eq(
16580 aplicacao_placement_via_const_fn(&internal_only),
16581 internal_only.placement(),
16582 ));
16583 assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
16584 match (
16585 aplicacao_entrada_via_const_fn(&with_entrada),
16586 with_entrada.entrada(),
16587 ) {
16588 (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
16589 _ => panic!(
16590 "aplicacao_entrada_via_const_fn must agree with \
16591 AplicacaoSpec::entrada on the Some-arm reference"
16592 ),
16593 }
16594 }
16595
16596 #[test]
16597 fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
16598 // Load-bearing contract pin: on every canonical
16599 // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
16600 // [`WitContract::target_projected`] returns byte-equal to
16601 // [`WitContract::target`]`().unwrap()` — the post-validation
16602 // projection accessor is a thin panicking wrapper over the
16603 // pre-validation validator, no extra work in the projection
16604 // path. Any future divergence (a validator-side normalization
16605 // the projection doesn't route through, an accessor-side
16606 // caching layer the validator doesn't populate) would surface
16607 // here at caixa-core build time rather than a silent per-consumer
16608 // split at renderer emit time. Sweeps the closed 4-arm
16609 // [`WitTarget`] partition ([`WitTarget::Http`] /
16610 // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
16611 // [`WitTarget::Capability`]) so every arm carries a byte-equality
16612 // pin on the two-accessor pair.
16613 for (wit, endpoint, subject, slot) in [
16614 ("wasi:http/proxy", Some("/x"), None, None),
16615 ("nats:pub-sub", None, Some("events.x"), None),
16616 ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
16617 ("custom:capability-only", None, None, None),
16618 ] {
16619 let c = WitContract {
16620 de: "cart".into(),
16621 para: "catalog".into(),
16622 wit: wit.into(),
16623 endpoint: endpoint.map(str::to_string),
16624 subject: subject.map(str::to_string),
16625 slot: slot.map(str::to_string),
16626 };
16627 assert_eq!(
16628 c.target_projected(),
16629 c.target().unwrap(),
16630 "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
16631 );
16632 }
16633 }
16634
16635 #[test]
16636 #[should_panic(expected = "validated by typed_view")]
16637 fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
16638 // Panic-path pin: [`WitContract::target_projected`] threads the
16639 // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
16640 // through its expect-panic when called on a contract whose
16641 // (`:wit`, payload) shape has not been crossed by
16642 // [`AplicacaoSpec::validate`] — a contract with a structurally-
16643 // invalid `:wit` (hyphen-for-colon typo) that would surface
16644 // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
16645 // A future rebrand on the panic-message axis would land at one
16646 // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
16647 // and this pin's [`should_panic(expected = …)`] literal would
16648 // migrate alongside — the pin catches drift between the const
16649 // and the accessor's `expect(…)` call by construction.
16650 let c = WitContract {
16651 de: "cart".into(),
16652 para: "catalog".into(),
16653 // Hyphen-for-colon typo: `WitContract::target` returns
16654 // [`AplicacaoError::ContratoWitInvalid`] on this shape,
16655 // driving the [`WitContract::target_projected`] expect-panic.
16656 wit: "wasi-http/proxy".into(),
16657 endpoint: Some("/x".into()),
16658 subject: None,
16659 slot: None,
16660 };
16661 let _ = c.target_projected();
16662 }
16663
16664 #[test]
16665 fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
16666 // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
16667 // carries the exact byte-string the two prior open-coded
16668 // `.target().expect("validated by typed_view")` production
16669 // consumers threaded through inline before this lift converged
16670 // them onto [`WitContract::target_projected`] — the caixa-mesh
16671 // per-`(:de, :para)` CNP L7 introspection branch at
16672 // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
16673 // graph` per-`:contratos` payload-column printer at
16674 // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
16675 // byte-string load-bearing so a well-meaning const-side rebrand
16676 // that didn't carry a matched pin migration would surface here
16677 // at caixa-core build time rather than a silent per-consumer
16678 // panic-message drift at cluster-apply time. Peer of the
16679 // sibling [`WitTarget::CAPABILITY_LABEL`] /
16680 // [`WitTarget::CAPABILITY_EXPECTED`] /
16681 // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
16682 // the paired payload-less-arm scalar-const family.
16683 assert_eq!(
16684 WitContract::PROJECTED_INVARIANT_MSG,
16685 "validated by typed_view"
16686 );
16687 }
16688
16689 #[test]
16690 fn empty_wit_takes_precedence_over_invalid() {
16691 // Ordering pin: `EmptyWit` is the more self-locating
16692 // diagnostic on `""` and must lead — the value-shape gate is
16693 // only reached after the empty-check fires. Mirrors
16694 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
16695 // the peer payload axis.
16696 let mut s = three_member_spec();
16697 s.contratos.push(WitContract {
16698 de: "payment".into(),
16699 para: "catalog".into(),
16700 wit: String::new(),
16701 endpoint: None,
16702 subject: None,
16703 slot: None,
16704 });
16705 let err = s.validate().unwrap_err();
16706 assert!(
16707 matches!(err, AplicacaoError::EmptyWit { .. }),
16708 "got {err:?}"
16709 );
16710 }
16711
16712 #[test]
16713 fn wit_invalid_fires_before_payload_shape_arm() {
16714 // Ordering pin: a malformed `:wit` surfaces *its own*
16715 // diagnostic (which names the offending wit verbatim) before
16716 // any payload-field check — a contrato whose wit is
16717 // structurally invalid AND carries a wrong target field
16718 // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
16719 // because the dispatch on the wit is what decides which
16720 // payload field is "right" in the first place. Without this
16721 // ordering, the author would see "wrong target field" for a
16722 // wit that hasn't even been parsed, which doesn't name the
16723 // root cause.
16724 let mut s = three_member_spec();
16725 s.contratos.push(WitContract {
16726 de: "payment".into(),
16727 para: "catalog".into(),
16728 // Hyphen-for-colon typo + endpoint set: pre-gate this
16729 // raised `ContratoWrongTarget { expected: "none" }` (the
16730 // Capability arm rejecting the endpoint), masking the
16731 // real authoring mistake (the wit isn't `wasi:http/proxy`).
16732 wit: "wasi-http/proxy".into(),
16733 endpoint: Some("/x".into()),
16734 subject: None,
16735 slot: None,
16736 });
16737 let err = s.validate().unwrap_err();
16738 assert!(
16739 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
16740 if wit == "wasi-http/proxy"),
16741 "got {err:?}"
16742 );
16743 }
16744
16745 #[test]
16746 fn wit_invalid_diagnostic_carries_offending_wit() {
16747 // Diagnostic-shape pin — the offending `:wit` + `:de` +
16748 // `:para` + a non-empty reason flow through verbatim so the
16749 // author can grep their caixa.lisp for the offending contrato
16750 // block and fix it in one edit. Same shape as
16751 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
16752 let err = contrato_wit_err("WASI:HTTP/proxy");
16753 match err {
16754 AplicacaoError::ContratoWitInvalid {
16755 de,
16756 para,
16757 wit,
16758 reason,
16759 } => {
16760 assert_eq!(de, "payment");
16761 assert_eq!(para, "catalog");
16762 assert_eq!(wit, "WASI:HTTP/proxy");
16763 assert!(!reason.is_empty(), "reason field must be non-empty");
16764 }
16765 other => panic!("expected ContratoWitInvalid, got {other:?}"),
16766 }
16767 }
16768
16769 // ── :contratos :subject value-shape gate ─────────────────────────────
16770 //
16771 // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
16772 // suites on the peer payload axes. Until this gate landed
16773 // `WitContract::target()` only refused the empty string; a
16774 // structurally invalid subject silently passed validate and the
16775 // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
16776 // Subject'` on publish / subscribe, or as a silent message drop,
16777 // far from the source caixa.lisp. Every authoring footgun the
16778 // NATS server's subject parser would catch on admission now
16779 // becomes a caixa-build-time `ContratoSubjectInvalid` with the
16780 // offending `:subject` + `:de` + `:para` named verbatim. Same
16781 // diagnostic shape as `ContratoEndpointInvalid` /
16782 // `ContratoWitInvalid` on the peer payload axes; same shared
16783 // predicate (`crate::render::is_nats_subject`) ensures drift
16784 // between any two axes' rule enforcement is a build error at the
16785 // predicate, not piecemeal across renderers.
16786
16787 fn contrato_subject_err(subject: &str) -> AplicacaoError {
16788 // Fresh spec per call so the new contract doesn't collide on
16789 // identity with `three_member_spec`'s pre-existing entries.
16790 // The new edge uses `(payment, catalog)` — a pair the fixture
16791 // doesn't already declare — with `:wit "nats:pub-sub"` and the
16792 // varying `:subject`, so the subject-shape gate fires cleanly
16793 // after the wit-shape gate (which `"nats:pub-sub"` passes).
16794 let mut s = three_member_spec();
16795 s.contratos.push(WitContract {
16796 de: "payment".into(),
16797 para: "catalog".into(),
16798 wit: "nats:pub-sub".into(),
16799 endpoint: None,
16800 subject: Some(subject.into()),
16801 slot: None,
16802 });
16803 s.validate().unwrap_err()
16804 }
16805
16806 #[test]
16807 fn rejects_pubsub_contrato_subject_with_whitespace() {
16808 // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
16809 // landed at the NATS server as a malformed subject the parser
16810 // rejects with `-ERR 'Invalid Subject'`. Now caught at the
16811 // source caixa.lisp.
16812 let err = contrato_subject_err("foo bar");
16813 assert!(
16814 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16815 if subject == "foo bar" && reason.contains("whitespace")),
16816 "got {err:?}"
16817 );
16818 }
16819
16820 #[test]
16821 fn rejects_pubsub_contrato_subject_with_control_char() {
16822 let err = contrato_subject_err("foo\x01bar");
16823 assert!(
16824 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16825 if subject == "foo\x01bar" && reason.contains("control character")),
16826 "got {err:?}"
16827 );
16828 }
16829
16830 #[test]
16831 fn rejects_pubsub_contrato_subject_with_non_ascii() {
16832 // Un-percent-encoded non-ASCII byte — the canonical "I copied
16833 // the subject from a doc with smart quotes / accented
16834 // characters" footgun.
16835 let err = contrato_subject_err("foo.caf\u{e9}");
16836 assert!(
16837 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16838 if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
16839 "got {err:?}"
16840 );
16841 }
16842
16843 #[test]
16844 fn rejects_pubsub_contrato_subject_with_leading_dot() {
16845 // Empty leading token — NATS rejects.
16846 let err = contrato_subject_err(".foo");
16847 assert!(
16848 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16849 if subject == ".foo" && reason.contains("must not start with `.`")),
16850 "got {err:?}"
16851 );
16852 }
16853
16854 #[test]
16855 fn rejects_pubsub_contrato_subject_with_trailing_dot() {
16856 // Empty trailing token — NATS rejects. The remediation
16857 // (use `>` instead) is in the reason string.
16858 let err = contrato_subject_err("foo.");
16859 assert!(
16860 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16861 if subject == "foo." && reason.contains("must not end with `.`")),
16862 "got {err:?}"
16863 );
16864 }
16865
16866 #[test]
16867 fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
16868 // The canonical "I forgot to fill in the middle segment"
16869 // typo — `"foo..bar"`. NATS rejects empty tokens.
16870 let err = contrato_subject_err("foo..bar");
16871 assert!(
16872 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16873 if subject == "foo..bar" && reason.contains("consecutive `.`")),
16874 "got {err:?}"
16875 );
16876 }
16877
16878 #[test]
16879 fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
16880 // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
16881 // as the final segment. Pre-gate this passed as a typed edge
16882 // and surfaced at runtime as a NATS subscribe rejection.
16883 let err = contrato_subject_err("foo.>.bar");
16884 assert!(
16885 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16886 if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
16887 "got {err:?}"
16888 );
16889 }
16890
16891 #[test]
16892 fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
16893 // `foo*.bar` — NATS wildcards are standalone tokens. The
16894 // remediation is in the reason string.
16895 let err = contrato_subject_err("foo*.bar");
16896 assert!(
16897 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16898 if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
16899 "got {err:?}"
16900 );
16901 }
16902
16903 #[test]
16904 fn rejects_pubsub_contrato_subject_with_invalid_char() {
16905 // `foo,bar` — comma is not a valid NATS subject character.
16906 // Pinned separately from the wildcard arms so the invalid-
16907 // character diagnostic is in force.
16908 let err = contrato_subject_err("foo,bar");
16909 assert!(
16910 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16911 if subject == "foo,bar" && reason.contains("invalid character")),
16912 "got {err:?}"
16913 );
16914 }
16915
16916 #[test]
16917 fn rejects_pubsub_contrato_subject_too_long() {
16918 // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
16919 // The legitimate-shape arms all pass (one all-`a` token, no
16920 // `.`, no wildcards); only the cap arm fires. Surfaces the
16921 // paste-from-binary / accidental-multi-line-blob landing
16922 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
16923 // on the peer axis.
16924 let big = "a".repeat(257);
16925 assert_eq!(big.len(), 257);
16926 let err = contrato_subject_err(&big);
16927 assert!(
16928 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
16929 if subject == &big && reason.contains("max length of 256")),
16930 "got {err:?}"
16931 );
16932 }
16933
16934 #[test]
16935 fn pubsub_contrato_subject_max_length_validates() {
16936 // 256-byte subject — exactly the cap. Boundary pin: drift in
16937 // the cap surfaces here and at
16938 // `rejects_pubsub_contrato_subject_too_long` simultaneously,
16939 // mirroring `http_contrato_endpoint_max_length_validates` and
16940 // `wit_max_length_validates` on the peer axes.
16941 let big = "a".repeat(256);
16942 assert_eq!(big.len(), 256);
16943 let mut s = three_member_spec();
16944 s.contratos.push(WitContract {
16945 de: "payment".into(),
16946 para: "catalog".into(),
16947 wit: "nats:pub-sub".into(),
16948 endpoint: None,
16949 subject: Some(big),
16950 slot: None,
16951 });
16952 s.validate().unwrap();
16953 }
16954
16955 #[test]
16956 fn pubsub_contrato_subject_accepts_canonical_forms() {
16957 // Positive-set sweep: every canonical NATS subject shape the
16958 // substrate-side `is_nats_subject` predicate accepts (the
16959 // multi-dot `events.order.charged`, the snake_case / kebab-
16960 // case / mixed-case tokens, the digit-bearing tokens, the
16961 // single-token wildcard `*` at every segment position, and
16962 // the trailing `>` multi-token wildcard) must remain a valid
16963 // contrato subject too. Drift between this list and the
16964 // substrate-side `nats_subject_accepts_canonical_forms` sweep
16965 // surfaces at the shared predicate — one source of truth.
16966 // Uses a fresh `(payment, catalog)` edge so none of the swept
16967 // subjects collide with the pre-existing entries in
16968 // `three_member_spec`.
16969 for subject in [
16970 "checkout.events.charge.failed",
16971 "rio.events.order.charged",
16972 "orders",
16973 "orders.123",
16974 "snake_case.token",
16975 "kebab-case.token",
16976 "MixedCase.Token",
16977 "orders.*.charged",
16978 "*.events.*",
16979 "orders.>",
16980 ] {
16981 let mut s = three_member_spec();
16982 s.contratos.push(WitContract {
16983 de: "payment".into(),
16984 para: "catalog".into(),
16985 wit: "nats:pub-sub".into(),
16986 endpoint: None,
16987 subject: Some(subject.into()),
16988 slot: None,
16989 });
16990 s.validate()
16991 .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
16992 }
16993 }
16994
16995 #[test]
16996 fn contrato_subject_empty_takes_precedence_over_invalid() {
16997 // Ordering pin: `ContratoSubjectEmpty` is the more self-
16998 // locating diagnostic on `""` and must lead — the value-shape
16999 // gate is only reached after the empty-check fires. Mirrors
17000 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
17001 // the peer payload axis.
17002 let mut s = three_member_spec();
17003 s.contratos.push(WitContract {
17004 de: "payment".into(),
17005 para: "catalog".into(),
17006 wit: "nats:pub-sub".into(),
17007 endpoint: None,
17008 subject: Some(String::new()),
17009 slot: None,
17010 });
17011 let err = s.validate().unwrap_err();
17012 assert!(
17013 matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
17014 "got {err:?}"
17015 );
17016 }
17017
17018 #[test]
17019 fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
17020 // Diagnostic-shape pin — the offending `:subject` + `:de` +
17021 // `:para` + a non-empty reason flow through verbatim so the
17022 // author can grep their caixa.lisp for the offending contrato
17023 // block and fix it in one edit. Same shape as
17024 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
17025 // and `wit_invalid_diagnostic_carries_offending_wit`.
17026 let err = contrato_subject_err("foo..bar");
17027 match err {
17028 AplicacaoError::ContratoSubjectInvalid {
17029 de,
17030 para,
17031 subject,
17032 reason,
17033 } => {
17034 assert_eq!(de, "payment");
17035 assert_eq!(para, "catalog");
17036 assert_eq!(subject, "foo..bar");
17037 assert!(!reason.is_empty(), "reason field must be non-empty");
17038 }
17039 other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
17040 }
17041 }
17042
17043 #[test]
17044 fn target_view_pubsub_subject_passes_through_to_typed_view() {
17045 // The compounding theorem on the pub-sub axis: every
17046 // `WitTarget::PubSub { subject }` returned by `target()` carries
17047 // a NATS-server-accepted subject. Renderers downstream of
17048 // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
17049 // NATS Stream/Consumer CR emitter, the future `feira app graph`
17050 // view's subject labeller) can rely on this without re-checking
17051 // — the type system carries the proof. Mirrors
17052 // `target_view_payload_is_guaranteed_nonempty_after_target_call`
17053 // on the peer axes.
17054 let nats = WitContract {
17055 de: "a".into(),
17056 para: "b".into(),
17057 wit: "nats:pub-sub".into(),
17058 endpoint: None,
17059 subject: Some("orders.events.*.charged".into()),
17060 slot: None,
17061 };
17062 match nats.target().unwrap() {
17063 WitTarget::PubSub { subject } => {
17064 assert_eq!(subject, "orders.events.*.charged");
17065 }
17066 other => panic!("expected PubSub, got {other:?}"),
17067 }
17068 }
17069
17070 // ── :contratos :slot value-shape gate ────────────────────────────────
17071 //
17072 // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
17073 // (63e18a0) value-shape suites on the peer payload axes. Until this
17074 // gate landed `WitContract::target()` only refused the empty string
17075 // for the Store arm; a structurally invalid slot (raw whitespace,
17076 // control character, non-ASCII byte, paste-from-binary multi-line
17077 // blob) silently passed validate and surfaced at runtime as a
17078 // per-backend kv write rejection or a silent next-read corruption,
17079 // far from the source caixa.lisp with no field naming which
17080 // `:contratos` edge carried the typo. Every authoring footgun the
17081 // kv backend intersection-floor would catch on write now becomes a
17082 // caixa-build-time `ContratoSlotInvalid` with the offending
17083 // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
17084 // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
17085 // peer payload axes; same shared predicate
17086 // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
17087 // any two axes' rule enforcement is a build error at the
17088 // predicate, not piecemeal across renderers. Closes the typed
17089 // payload-axis value-shape trajectory across all three legs of the
17090 // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
17091
17092 fn contrato_slot_err(slot: &str) -> AplicacaoError {
17093 // Fresh spec per call so the new contract doesn't collide on
17094 // identity with `three_member_spec`'s pre-existing entries
17095 // and doesn't close a synchronous cycle the cycle detector
17096 // would reject before the slot-shape gate fires. The new edge
17097 // uses `(payment, catalog)` — a pair the fixture doesn't
17098 // already declare in either direction (the fixture carries
17099 // `cart -> catalog` and `cart -> payment`, so `payment ->
17100 // catalog` doesn't form a cycle on the sync subgraph) — with
17101 // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
17102 // slot-shape gate fires cleanly after the wit-shape gate
17103 // (which `"wasi:keyvalue/store"` passes). Same edge pair the
17104 // peer `contrato_subject_err` helper uses (63e18a0).
17105 let mut s = three_member_spec();
17106 s.contratos.push(WitContract {
17107 de: "payment".into(),
17108 para: "catalog".into(),
17109 wit: "wasi:keyvalue/store".into(),
17110 endpoint: None,
17111 subject: None,
17112 slot: Some(slot.into()),
17113 });
17114 s.validate().unwrap_err()
17115 }
17116
17117 #[test]
17118 fn rejects_store_contrato_slot_with_whitespace() {
17119 // Fail-before-pass-after pin — pre-gate `"check out/$order"`
17120 // silently landed at the kv backend with whitespace whose
17121 // runtime behavior varies unpredictably across backends (etcd
17122 // accepts, Redis accepts then breaks on next CLI op, DynamoDB
17123 // rejects on write). Now caught at the source caixa.lisp.
17124 let err = contrato_slot_err("check out/$order");
17125 assert!(
17126 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17127 if slot == "check out/$order" && reason.contains("whitespace")),
17128 "got {err:?}"
17129 );
17130 }
17131
17132 #[test]
17133 fn rejects_store_contrato_slot_with_tab() {
17134 // Tab byte arm-pinned separately from the space arm so a
17135 // future relaxation that admits one but not the other surfaces
17136 // here.
17137 let err = contrato_slot_err("check\tout");
17138 assert!(
17139 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17140 if slot == "check\tout" && reason.contains("whitespace")),
17141 "got {err:?}"
17142 );
17143 }
17144
17145 #[test]
17146 fn rejects_store_contrato_slot_with_control_char() {
17147 // SOH (0x01) — distinct from the whitespace arm. Redis admits
17148 // and corrupts on RESP protocol framing; DynamoDB rejects on
17149 // write.
17150 let err = contrato_slot_err("checkout/\x01order");
17151 assert!(
17152 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17153 if slot == "checkout/\x01order" && reason.contains("control character")),
17154 "got {err:?}"
17155 );
17156 }
17157
17158 #[test]
17159 fn rejects_store_contrato_slot_with_newline() {
17160 // Embedded newline — the canonical "the paste-from-binary slug
17161 // spans multiple lines" footgun. Distinct from the whitespace
17162 // arm because `\n` is a control character (0x0A).
17163 let err = contrato_slot_err("checkout\norder");
17164 assert!(
17165 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17166 if slot == "checkout\norder" && reason.contains("control character")),
17167 "got {err:?}"
17168 );
17169 }
17170
17171 #[test]
17172 fn rejects_store_contrato_slot_with_non_ascii() {
17173 // Un-percent-encoded non-ASCII byte — the canonical "I copied
17174 // the slot from a doc with accented characters" footgun. Each
17175 // kv backend re-encodes non-ASCII differently (etcd preserves
17176 // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
17177 // rejects), so the typed slot's value set is the intersection-
17178 // floor every backend admits identically (printable ASCII).
17179 let err = contrato_slot_err("ch\u{e9}ckout/$order");
17180 assert!(
17181 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17182 if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
17183 "got {err:?}"
17184 );
17185 }
17186
17187 #[test]
17188 fn rejects_store_contrato_slot_too_long() {
17189 // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
17190 // legitimate-shape arms all pass (a single all-`a` token, no
17191 // separators); only the cap arm fires. Surfaces the paste-
17192 // from-binary / accidental-multi-line-blob landing footgun.
17193 // Mirrors `rejects_pubsub_contrato_subject_too_long` and
17194 // `rejects_http_contrato_endpoint_too_long` on the peer
17195 // payload axes.
17196 let big = "a".repeat(513);
17197 assert_eq!(big.len(), 513);
17198 let err = contrato_slot_err(&big);
17199 assert!(
17200 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
17201 if slot == &big && reason.contains("max length of 512")),
17202 "got {err:?}"
17203 );
17204 }
17205
17206 #[test]
17207 fn store_contrato_slot_max_length_validates() {
17208 // 512-byte slot — exactly the cap. Boundary pin: drift in the
17209 // cap surfaces here and at `rejects_store_contrato_slot_too_long`
17210 // simultaneously, mirroring
17211 // `pubsub_contrato_subject_max_length_validates` and
17212 // `http_contrato_endpoint_max_length_validates` on the peer
17213 // payload axes.
17214 let big = "a".repeat(512);
17215 assert_eq!(big.len(), 512);
17216 let mut s = three_member_spec();
17217 s.contratos.push(WitContract {
17218 de: "payment".into(),
17219 para: "catalog".into(),
17220 wit: "wasi:keyvalue/store".into(),
17221 endpoint: None,
17222 subject: None,
17223 slot: Some(big),
17224 });
17225 s.validate().unwrap();
17226 }
17227
17228 #[test]
17229 fn store_contrato_slot_accepts_canonical_forms() {
17230 // Positive-set sweep: every canonical kv slot template the
17231 // substrate-side `is_wasi_keyvalue_slot` predicate accepts
17232 // (single-token identifiers, path-namespaced `$`-templates,
17233 // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
17234 // snake_case / kebab-case / MixedCase tokens, digit-bearing
17235 // tokens, percent-encoded fragments) must remain valid
17236 // contrato slots too. Drift between this list and the
17237 // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
17238 // surfaces at the shared predicate — one source of truth.
17239 // Uses a fresh `(payment, catalog)` edge so none of the swept
17240 // slots collide with the pre-existing entries in
17241 // `three_member_spec`.
17242 for slot in [
17243 "checkout",
17244 "checkout/$orderId",
17245 "users:{tenant}/{id}",
17246 "session.<sid>",
17247 "session.tokens.<sid>",
17248 "snake_case_key",
17249 "kebab-case-key",
17250 "MixedCase",
17251 "shard0",
17252 "v2/key",
17253 "users/caf%C3%A9",
17254 ] {
17255 let mut s = three_member_spec();
17256 s.contratos.push(WitContract {
17257 de: "payment".into(),
17258 para: "catalog".into(),
17259 wit: "wasi:keyvalue/store".into(),
17260 endpoint: None,
17261 subject: None,
17262 slot: Some(slot.into()),
17263 });
17264 s.validate()
17265 .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
17266 }
17267 }
17268
17269 #[test]
17270 fn contrato_slot_empty_takes_precedence_over_invalid() {
17271 // Ordering pin: `ContratoSlotEmpty` is the more self-locating
17272 // diagnostic on `""` and must lead — the value-shape gate is
17273 // only reached after the empty-check fires. Mirrors
17274 // `contrato_subject_empty_takes_precedence_over_invalid` and
17275 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
17276 // the peer payload axes.
17277 let mut s = three_member_spec();
17278 s.contratos.push(WitContract {
17279 de: "payment".into(),
17280 para: "catalog".into(),
17281 wit: "wasi:keyvalue/store".into(),
17282 endpoint: None,
17283 subject: None,
17284 slot: Some(String::new()),
17285 });
17286 let err = s.validate().unwrap_err();
17287 assert!(
17288 matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
17289 "got {err:?}"
17290 );
17291 }
17292
17293 #[test]
17294 fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
17295 // Diagnostic-shape pin — the offending `:slot` + `:de` +
17296 // `:para` + a non-empty reason flow through verbatim so the
17297 // author can grep their caixa.lisp for the offending contrato
17298 // block and fix it in one edit. Same shape as
17299 // `contrato_subject_invalid_diagnostic_carries_offending_subject`
17300 // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
17301 // on the peer payload axes.
17302 let err = contrato_slot_err("check out/$order");
17303 match err {
17304 AplicacaoError::ContratoSlotInvalid {
17305 de,
17306 para,
17307 slot,
17308 reason,
17309 } => {
17310 assert_eq!(de, "payment");
17311 assert_eq!(para, "catalog");
17312 assert_eq!(slot, "check out/$order");
17313 assert!(!reason.is_empty(), "reason field must be non-empty");
17314 }
17315 other => panic!("expected ContratoSlotInvalid, got {other:?}"),
17316 }
17317 }
17318
17319 #[test]
17320 fn target_view_store_slot_passes_through_to_typed_view() {
17321 // The compounding theorem on the store axis: every
17322 // `WitTarget::Store { slot }` returned by `target()` carries a
17323 // kv-backend-accepted slot template. Renderers downstream of
17324 // `typed_view()` (the future per-Servico `:capabilities
17325 // wasi:keyvalue/store` axis emitter, the future `feira app
17326 // graph` view's slot labeller, the future kv-provider CR
17327 // materializer) can rely on this without re-checking — the
17328 // type system carries the proof. Mirrors
17329 // `target_view_pubsub_subject_passes_through_to_typed_view` on
17330 // the peer payload axis.
17331 let store = WitContract {
17332 de: "a".into(),
17333 para: "b".into(),
17334 wit: "wasi:keyvalue/store".into(),
17335 endpoint: None,
17336 subject: None,
17337 slot: Some("checkout/$orderId".into()),
17338 };
17339 match store.target().unwrap() {
17340 WitTarget::Store { slot } => {
17341 assert_eq!(slot, "checkout/$orderId");
17342 }
17343 other => panic!("expected Store, got {other:?}"),
17344 }
17345 }
17346
17347 #[test]
17348 fn rejects_self_loop_in_synchronous_contratos() {
17349 // A synchronous self-edge (`cart → cart` over HTTP) is now
17350 // rejected by the dedicated `ContratoSelfLoop` gate — a precise
17351 // "this edge is degenerate" diagnostic — rather than incidentally
17352 // by the cycle detector framing it as a `["cart", "cart"]`
17353 // multi-node deadlock.
17354 let mut s = three_member_spec();
17355 s.contratos.push(contract_http("cart", "cart", "/loop"));
17356 let err = s.validate().unwrap_err();
17357 match err {
17358 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
17359 assert_eq!(caixa, "cart");
17360 assert_eq!(wit, "wasi:http/proxy");
17361 }
17362 other => panic!("expected ContratoSelfLoop, got {other:?}"),
17363 }
17364 }
17365
17366 #[test]
17367 fn rejects_self_loop_in_pubsub_contratos() {
17368 // The cycle detector excludes pub-sub edges (acyclic by
17369 // construction), so before the explicit gate a `nats:pub-sub`
17370 // self-edge silently validated and rendered a self-allow CNP.
17371 // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
17372 let mut s = three_member_spec();
17373 s.contratos.push(WitContract {
17374 de: "payment".into(),
17375 para: "payment".into(),
17376 wit: "nats:pub-sub".into(),
17377 endpoint: None,
17378 subject: Some("rio.events.payment".into()),
17379 slot: None,
17380 });
17381 let err = s.validate().unwrap_err();
17382 match err {
17383 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
17384 assert_eq!(caixa, "payment");
17385 assert_eq!(wit, "nats:pub-sub");
17386 }
17387 other => panic!("expected ContratoSelfLoop, got {other:?}"),
17388 }
17389 }
17390
17391 #[test]
17392 fn self_loop_fires_before_payload_shape_check() {
17393 // The structural "this edge can't exist" error precedes the
17394 // narrower payload-shape diagnostics: a self-edge carrying an
17395 // otherwise-malformed endpoint still reports ContratoSelfLoop,
17396 // not ContratoEndpointInvalid.
17397 let mut s = three_member_spec();
17398 s.contratos.push(WitContract {
17399 de: "cart".into(),
17400 para: "cart".into(),
17401 wit: "wasi:http/proxy".into(),
17402 endpoint: Some("not-absolute".into()),
17403 subject: None,
17404 slot: None,
17405 });
17406 match s.validate().unwrap_err() {
17407 AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
17408 other => panic!("expected ContratoSelfLoop, got {other:?}"),
17409 }
17410 }
17411
17412 #[test]
17413 fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
17414 // A self-edge naming a non-member reports the more fundamental
17415 // ContratoMemberMissing first (the member doesn't exist), so the
17416 // self-loop gate is reached only once both endpoints resolve.
17417 let mut s = three_member_spec();
17418 s.contratos.push(contract_http("ghost", "ghost", "/loop"));
17419 match s.validate().unwrap_err() {
17420 AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
17421 other => panic!("expected ContratoMemberMissing, got {other:?}"),
17422 }
17423 }
17424
17425 #[test]
17426 fn rejects_two_node_synchronous_cycle() {
17427 let mut s = three_member_spec();
17428 // existing edges: cart → catalog, cart → payment
17429 // adding catalog → cart closes a 2-cycle on the HTTP subgraph
17430 s.contratos
17431 .push(contract_http("catalog", "cart", "/refresh"));
17432 let err = s.validate().unwrap_err();
17433 match err {
17434 AplicacaoError::ContratoCycle { cycle } => {
17435 // Cycle traversal should mention both endpoints, with
17436 // the back-edge target appearing as both first and last
17437 // element to close the loop.
17438 assert!(cycle.len() >= 3);
17439 assert_eq!(cycle.first(), cycle.last());
17440 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
17441 assert!(body.contains("cart"));
17442 assert!(body.contains("catalog"));
17443 }
17444 other => panic!("expected ContratoCycle, got {other:?}"),
17445 }
17446 }
17447
17448 #[test]
17449 fn rejects_three_node_synchronous_cycle() {
17450 let mut s = three_member_spec();
17451 // Reset to a clean 3-cycle: catalog → cart → payment → catalog
17452 s.contratos = vec![
17453 contract_http("catalog", "cart", "/x"),
17454 contract_http("cart", "payment", "/y"),
17455 contract_http("payment", "catalog", "/z"),
17456 ];
17457 let err = s.validate().unwrap_err();
17458 match err {
17459 AplicacaoError::ContratoCycle { cycle } => {
17460 assert_eq!(cycle.first(), cycle.last());
17461 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
17462 assert_eq!(body.len(), 3);
17463 assert!(body.contains("cart"));
17464 assert!(body.contains("catalog"));
17465 assert!(body.contains("payment"));
17466 }
17467 other => panic!("expected ContratoCycle, got {other:?}"),
17468 }
17469 }
17470
17471 #[test]
17472 fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
17473 // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
17474 // "acyclic by construction" — so a cycle whose closing edge
17475 // is pub-sub should NOT raise ContratoCycle.
17476 let mut s = three_member_spec();
17477 s.contratos = vec![
17478 contract_http("catalog", "cart", "/x"),
17479 contract_http("cart", "payment", "/y"),
17480 // Closing edge is pub-sub — async; not a sync deadlock.
17481 WitContract {
17482 de: "payment".into(),
17483 para: "catalog".into(),
17484 wit: "nats:pub-sub".into(),
17485 endpoint: None,
17486 subject: Some("checkout.events.charge.completed".into()),
17487 slot: None,
17488 },
17489 ];
17490 s.validate().expect("pub-sub edge breaks the sync cycle");
17491 }
17492
17493 #[test]
17494 fn store_edge_counts_as_synchronous_for_cycle_detection() {
17495 // wasi:keyvalue/store is request/response; a cycle through one
17496 // *is* a sync deadlock, just like HTTP.
17497 let mut s = three_member_spec();
17498 s.contratos = vec![
17499 contract_http("catalog", "cart", "/x"),
17500 WitContract {
17501 de: "cart".into(),
17502 para: "catalog".into(),
17503 wit: "wasi:keyvalue/store".into(),
17504 endpoint: None,
17505 subject: None,
17506 slot: Some("session/$id".into()),
17507 },
17508 ];
17509 let err = s.validate().unwrap_err();
17510 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
17511 }
17512
17513 #[test]
17514 fn capability_edge_counts_as_synchronous_for_cycle_detection() {
17515 // Capability-only edges (unknown WIT shape, no payload) default
17516 // to synchronous — safer; authors with truly async capability
17517 // semantics can model them as pub-sub explicitly.
17518 let mut s = three_member_spec();
17519 s.contratos = vec![
17520 contract_http("catalog", "cart", "/x"),
17521 WitContract {
17522 de: "cart".into(),
17523 para: "catalog".into(),
17524 wit: "custom:exchange".into(),
17525 endpoint: None,
17526 subject: None,
17527 slot: None,
17528 },
17529 ];
17530 let err = s.validate().unwrap_err();
17531 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
17532 }
17533
17534 #[test]
17535 fn long_acyclic_chain_validates() {
17536 // A long sync chain (no back-edges) must validate even when
17537 // every node is reachable from the first.
17538 let mut s = three_member_spec();
17539 s.membros = vec![
17540 membro("a", "^0.1"),
17541 membro("b", "^0.1"),
17542 membro("c", "^0.1"),
17543 membro("d", "^0.1"),
17544 membro("e", "^0.1"),
17545 ];
17546 s.contratos = vec![
17547 contract_http("a", "b", "/1"),
17548 contract_http("b", "c", "/2"),
17549 contract_http("c", "d", "/3"),
17550 contract_http("d", "e", "/4"),
17551 ];
17552 s.entrada.as_mut().unwrap().para = "a".into();
17553 s.validate().unwrap();
17554 }
17555
17556 #[test]
17557 fn diamond_acyclic_validates() {
17558 // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
17559 let mut s = three_member_spec();
17560 s.membros = vec![
17561 membro("a", "^0.1"),
17562 membro("b", "^0.1"),
17563 membro("c", "^0.1"),
17564 membro("d", "^0.1"),
17565 ];
17566 s.contratos = vec![
17567 contract_http("a", "b", "/1"),
17568 contract_http("a", "c", "/2"),
17569 contract_http("b", "d", "/3"),
17570 contract_http("c", "d", "/4"),
17571 ];
17572 s.entrada.as_mut().unwrap().para = "a".into();
17573 s.validate().unwrap();
17574 }
17575
17576 // ── duplicate-`:contratos` build-error gate ──────────────────────────
17577
17578 #[test]
17579 fn rejects_duplicate_http_contrato() {
17580 // Fail-before-pass-after pin: the fixture's `cart → catalog`
17581 // HTTP edge appears once. Push an identical entry — same
17582 // (de, para, wit, endpoint) — and validate() must reject it.
17583 // Until this gate landed the typed surface accepted the
17584 // duplicate silently and caixa-mesh's `cilium_network_policies`
17585 // emitted two ``CiliumNetworkPolicy`` objects with identical
17586 // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
17587 // admission rejects on `kubectl apply` far from the source.
17588 let mut s = three_member_spec();
17589 s.contratos
17590 .push(contract_http("cart", "catalog", "/products/:id"));
17591 let err = s.validate().unwrap_err();
17592 assert!(
17593 matches!(
17594 err,
17595 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
17596 if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
17597 ),
17598 "got {err:?}"
17599 );
17600 }
17601
17602 #[test]
17603 fn rejects_duplicate_pubsub_contrato() {
17604 // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
17605 // edges with identical (de, para, subject) are degenerate;
17606 // pin that the typed surface refuses both at validate time.
17607 let mut s = three_member_spec();
17608 let pubsub = WitContract {
17609 de: "payment".into(),
17610 para: "cart".into(),
17611 wit: "nats:pub-sub".into(),
17612 endpoint: None,
17613 subject: Some("checkout.events.charge.failed".into()),
17614 slot: None,
17615 };
17616 s.contratos.push(pubsub.clone());
17617 s.contratos.push(pubsub);
17618 let err = s.validate().unwrap_err();
17619 assert!(
17620 matches!(
17621 err,
17622 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
17623 if de == "payment" && para == "cart" && wit == "nats:pub-sub"
17624 ),
17625 "got {err:?}"
17626 );
17627 }
17628
17629 #[test]
17630 fn rejects_duplicate_store_contrato() {
17631 // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
17632 // edges with identical (de, para, slot) collapse to one mesh-
17633 // policy edge; pin the build error.
17634 let mut s = three_member_spec();
17635 let store = WitContract {
17636 de: "cart".into(),
17637 para: "payment".into(),
17638 wit: "wasi:keyvalue/store".into(),
17639 endpoint: None,
17640 subject: None,
17641 slot: Some("checkout/$orderId".into()),
17642 };
17643 // Drop the conflicting HTTP `cart → payment` edge from the
17644 // fixture so the duplicate-store pair is the only one
17645 // distinguishable on this pair.
17646 s.contratos
17647 .retain(|c| !(c.de == "cart" && c.para == "payment"));
17648 s.contratos.push(store.clone());
17649 s.contratos.push(store);
17650 let err = s.validate().unwrap_err();
17651 assert!(
17652 matches!(
17653 err,
17654 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
17655 if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
17656 ),
17657 "got {err:?}"
17658 );
17659 }
17660
17661 #[test]
17662 fn rejects_duplicate_capability_contrato() {
17663 // Same gate on the pure-capability axis (no payload selector).
17664 // Two contracts with identical (de, para, wit) and no
17665 // endpoint/subject/slot are duplicate edges; pin so a future
17666 // `target_label` change can't accidentally collapse the
17667 // capability arm into a None-shaped key that compares equal
17668 // to a populated one.
17669 let mut s = three_member_spec();
17670 let capability = WitContract {
17671 de: "cart".into(),
17672 para: "catalog".into(),
17673 wit: "pleme:cap/audit".into(),
17674 endpoint: None,
17675 subject: None,
17676 slot: None,
17677 };
17678 s.contratos.push(capability.clone());
17679 s.contratos.push(capability);
17680 let err = s.validate().unwrap_err();
17681 match err {
17682 AplicacaoError::ContratoDuplicate {
17683 de,
17684 para,
17685 wit,
17686 target,
17687 } => {
17688 assert_eq!(de, "cart");
17689 assert_eq!(para, "catalog");
17690 assert_eq!(wit, "pleme:cap/audit");
17691 assert!(
17692 target.contains("capability"),
17693 "capability-edge duplicate diagnostic must surface the \
17694 no-payload shape (got target = {target:?})"
17695 );
17696 }
17697 other => panic!("expected ContratoDuplicate, got {other:?}"),
17698 }
17699 }
17700
17701 #[test]
17702 fn accepts_distinct_http_paths_between_same_pair() {
17703 // Negative pin: two HTTP contracts cart → catalog at distinct
17704 // endpoints (`/products/:id` and `/search`) are *not*
17705 // duplicates — they're distinct typed edges differing on the
17706 // payload axis. The duplicate-gate must not over-match here,
17707 // since the cart-calls-catalog-on-multiple-paths shape is the
17708 // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
17709 // example: cart calls catalog at /products/:id, payment at
17710 // /charge — same shape extends to two paths on one para).
17711 let mut s = three_member_spec();
17712 s.contratos
17713 .push(contract_http("cart", "catalog", "/search"));
17714 s.validate()
17715 .expect("distinct endpoints between same (de, para) must validate");
17716 }
17717
17718 #[test]
17719 fn accepts_same_endpoint_on_different_pairs() {
17720 // Negative pin: the same `/charge` endpoint reused on two
17721 // different (de, para) pairs is two distinct edges, not a
17722 // duplicate. Pinning this shape so the gate's identity key
17723 // includes both `de` and `para` (not just `(wit, endpoint)`).
17724 let mut s = three_member_spec();
17725 s.contratos
17726 .push(contract_http("payment", "catalog", "/charge"));
17727 s.validate()
17728 .expect("same endpoint reused on distinct (de, para) must validate");
17729 }
17730
17731 #[test]
17732 fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
17733 // Pin the diagnostic shape: the duplicate-edge error names
17734 // *which* target field carried the conflict, so the author
17735 // doesn't have to re-grep the source caixa.lisp to find it.
17736 // Same self-locating diagnostic discipline as
17737 // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
17738 let mut s = three_member_spec();
17739 s.contratos
17740 .push(contract_http("cart", "catalog", "/products/:id"));
17741 let err = s.validate().unwrap_err();
17742 let msg = format!("{err}");
17743 assert!(
17744 msg.contains("\"/products/:id\""),
17745 "duplicate-contrato diagnostic must name the offending \
17746 :endpoint payload (got: {msg:?})"
17747 );
17748 assert!(
17749 msg.contains("cart") && msg.contains("catalog"),
17750 "diagnostic must name both endpoints of the duplicate edge \
17751 (got: {msg:?})"
17752 );
17753 }
17754
17755 #[test]
17756 fn duplicate_contrato_gate_runs_after_membership_check() {
17757 // Order pin: a duplicate contract whose `:de` is *also* not in
17758 // `:membros` surfaces the membership error first — the
17759 // missing-member diagnostic is more locating than the
17760 // duplicate-edge one (the author has to fix the membership
17761 // before the duplicate is meaningful). Same ordering
17762 // discipline as `membros_validation_runs_before_contratos_membership_check`.
17763 let mut s = three_member_spec();
17764 s.contratos.push(contract_http("phantom", "catalog", "/x"));
17765 s.contratos.push(contract_http("phantom", "catalog", "/x"));
17766 let err = s.validate().unwrap_err();
17767 assert!(
17768 matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
17769 "membership-missing must fire before duplicate-edge (got {err:?})"
17770 );
17771 }
17772
17773 #[test]
17774 fn duplicate_contrato_gate_runs_after_target_shape_check() {
17775 // Order pin: a contract with a malformed target (e.g. an HTTP
17776 // wit world with an empty :endpoint) surfaces the target-shape
17777 // error first, not the duplicate one. Even when two such
17778 // malformed entries are identical, the per-contract `target()`
17779 // check fires inside the loop *before* the duplicate-key
17780 // insert, so the diagnostic remains the most-locating one.
17781 let mut s = three_member_spec();
17782 let malformed = WitContract {
17783 de: "cart".into(),
17784 para: "catalog".into(),
17785 wit: "wasi:http/proxy".into(),
17786 endpoint: Some(String::new()),
17787 subject: None,
17788 slot: None,
17789 };
17790 s.contratos.push(malformed.clone());
17791 s.contratos.push(malformed);
17792 let err = s.validate().unwrap_err();
17793 assert!(
17794 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
17795 "endpoint-empty must fire before duplicate-edge (got {err:?})"
17796 );
17797 }
17798
17799 #[test]
17800 fn wit_target_label_pins_per_variant_format() {
17801 // Label format is the single source of truth every duplicate-
17802 // `:contratos` diagnostic + every future `feira app graph`
17803 // consumer routes through. Pin the shape per variant so a
17804 // future edit to `WitTarget::label` (e.g. a JSON emitter that
17805 // strips the leading `:`, or a rename from `endpoint` →
17806 // `path`) surfaces as a red-red test rather than as a silent
17807 // downstream diagnostic drift. Together with the exhaustive
17808 // `match` on `WitTarget` inside `label()`, adding a future
17809 // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
17810 // peer, per-edge WIT registry variants) is a compile error at
17811 // the label site — not a fall-through into the `Capability`
17812 // "no payload" default the prior raw-field-probe helper
17813 // silently landed on.
17814 assert_eq!(
17815 WitTarget::Http {
17816 endpoint: "/charge",
17817 }
17818 .label(),
17819 "\
17820:endpoint \"/charge\""
17821 );
17822 assert_eq!(
17823 WitTarget::PubSub {
17824 subject: "events.checkout.paid",
17825 }
17826 .label(),
17827 "\
17828:subject \"events.checkout.paid\""
17829 );
17830 assert_eq!(
17831 WitTarget::Store {
17832 slot: "checkout/$order",
17833 }
17834 .label(),
17835 "\
17836:slot \"checkout/$order\""
17837 );
17838 assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
17839 // Capability-arm label routes through the lifted
17840 // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
17841 // declaration per arm, next to the variant" discipline the
17842 // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
17843 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
17844 // consts already carry extends to the payload-less arm; the
17845 // byte-string equality pin below plus this label-routes-
17846 // through-the-const pin make a future rebrand on either the
17847 // const declaration or the `label()` template a build error
17848 // here rather than a downstream consumer surprise.
17849 assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
17850 assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
17851 }
17852
17853 #[test]
17854 fn wit_target_display_routes_through_label_helper() {
17855 // Fail-before-pass-after pin on the fourth (and only remaining)
17856 // typed-shape-discriminator axis to converge onto the
17857 // three-path-convergence discipline the sibling M3
17858 // [`PlacementStrategy`] (0a2f653) and M2
17859 // [`crate::supervisor::RestartStrategy`] /
17860 // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
17861 // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
17862 // through [`WitTarget::label`], so every consumer reaching for
17863 // `format!("{v}")` on a typed payload target lands on the same
17864 // stable author-facing byte-string [`WitTarget::label`] returns
17865 // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
17866 // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
17867 // `:contratos` gate seeds via [`WitTarget::label`] at
17868 // aplicacao.rs:5491 already threads through.
17869 //
17870 // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
17871 // through to the `Debug` derive's structural output
17872 // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
17873 // rather than the [`WitTarget::label`] helper's stable byte-
17874 // string (`:endpoint "/charge"` — the author-facing `:contratos`
17875 // keyword form). Every future consumer that reaches for
17876 // `format!("{target}")` — the canonical shape every user-facing
17877 // pretty-print site on the sibling typed-enum axes
17878 // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
17879 // [`crate::supervisor::RestartPolicy`]) already uses — would
17880 // silently land under a different byte-string than the
17881 // [`WitTarget::label`] callers that the duplicate-`:contratos`
17882 // diagnostic already threads through, with the mismatch
17883 // surfacing as a downstream diagnostic / graph / audit line
17884 // reading one spelling while the substrate's own gate emitted
17885 // another.
17886 //
17887 // Pin the routing here so a future
17888 // `impl std::fmt::Display for WitTarget<'_>` reimplementation
17889 // that hand-rolls the per-arm formatting instead of delegating
17890 // to [`WitTarget::label`] fails at caixa-core build time.
17891 for variant in [
17892 WitTarget::Http {
17893 endpoint: "/charge",
17894 },
17895 WitTarget::PubSub {
17896 subject: "events.checkout.paid",
17897 },
17898 WitTarget::Store {
17899 slot: "checkout/$order",
17900 },
17901 WitTarget::Capability,
17902 ] {
17903 assert_eq!(
17904 variant.to_string(),
17905 variant.label(),
17906 "WitTarget::{variant:?} Display must route through \
17907 WitTarget::label (single source of truth: the lifted \
17908 payload_pair 4-arm dispatch the label helper already \
17909 threads through)"
17910 );
17911 }
17912 }
17913
17914 #[test]
17915 fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
17916 // Consumer-side pin on the three-path convergence:
17917 // [`std::fmt::Display`] agrees byte-for-byte with the
17918 // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
17919 // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
17920 // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
17921 // Pre-lift the two paths were structurally independent — the
17922 // substrate-side gate reached for `target_view.label()` while a
17923 // future downstream diagnostic / graph / audit line reaching
17924 // for `format!("{target}")` would silently land on the `Debug`
17925 // derive's structural output. Pin the two paths byte-for-byte
17926 // here so any future variant addition (M4 `Rest`/`Grpc` split
17927 // of [`WitTarget::Http`], `Queue`-shaped peer of
17928 // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
17929 // match error at [`WitTarget::payload_pair`] rather than a
17930 // silent per-consumer dispatch miss.
17931 for variant in [
17932 WitTarget::Http {
17933 endpoint: "/charge",
17934 },
17935 WitTarget::PubSub {
17936 subject: "events.checkout.paid",
17937 },
17938 WitTarget::Store {
17939 slot: "checkout/$order",
17940 },
17941 WitTarget::Capability,
17942 ] {
17943 assert_eq!(
17944 format!("{variant}"),
17945 variant.label(),
17946 "WitTarget::{variant:?} Display byte-string must match \
17947 the AplicacaoError::ContratoDuplicate `target:` carrier \
17948 the AplicacaoSpec::validate duplicate-`:contratos` gate \
17949 seeds via WitTarget::label — three-path convergence: \
17950 Display + label + payload_pair all resolve to the same \
17951 per-arm byte-string"
17952 );
17953 }
17954 }
17955
17956 #[test]
17957 fn wit_target_payload_pair_pins_per_variant() {
17958 // Pin the per-arm `(field-name, payload)` pair single-sourced
17959 // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
17960 // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
17961 // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
17962 // and [`WitTarget::field_name`] (returns the first component)
17963 // route through. Until this lift landed [`WitTarget::label`]
17964 // dispatched on the same three arms with a per-arm
17965 // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
17966 // paired [`WitTarget::HTTP_FIELD_NAME`] /
17967 // [`WitTarget::PUBSUB_FIELD_NAME`] /
17968 // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
17969 // canonical "same shape, written N times" duplication
17970 // THEORY.md §I.3.5 promotes to a build-time concern. A future
17971 // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
17972 // [`WitTarget::Http`], `Queue`-shaped peer of
17973 // [`WitTarget::Store`]) is one match-arm edit at
17974 // [`WitTarget::payload_pair`], visible here as a compile-time
17975 // exhaustiveness error on both this pin and the label-format
17976 // pin above.
17977 assert_eq!(
17978 WitTarget::Http {
17979 endpoint: "/charge"
17980 }
17981 .payload_pair(),
17982 Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
17983 );
17984 assert_eq!(
17985 WitTarget::PubSub {
17986 subject: "events.x",
17987 }
17988 .payload_pair(),
17989 Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
17990 );
17991 assert_eq!(
17992 WitTarget::Store {
17993 slot: "checkout/$order",
17994 }
17995 .payload_pair(),
17996 Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
17997 );
17998 assert_eq!(WitTarget::Capability.payload_pair(), None);
17999 }
18000
18001 #[test]
18002 fn wit_target_field_name_pins_per_variant() {
18003 // Pin the per-arm author-facing `:contratos` payload field
18004 // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
18005 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
18006 // + returned by [`WitTarget::field_name`]. Every downstream
18007 // consumer (the [`WitContract::target`] gate's `expected:`
18008 // scalar, the [`WitTarget::label`] template's keyword prefix,
18009 // the `feira app graph` verb's `endpoint=…` prefix) routes
18010 // through the same three peer consts, so a rename on the
18011 // author-surface `(defcaixa … :contratos ((:de … :para …
18012 // :wit … :endpoint …)))` field lands in exactly one place.
18013 assert_eq!(
18014 WitTarget::Http {
18015 endpoint: "/charge"
18016 }
18017 .field_name(),
18018 Some(WitTarget::HTTP_FIELD_NAME),
18019 );
18020 assert_eq!(
18021 WitTarget::PubSub {
18022 subject: "events.x",
18023 }
18024 .field_name(),
18025 Some(WitTarget::PUBSUB_FIELD_NAME),
18026 );
18027 assert_eq!(
18028 WitTarget::Store {
18029 slot: "checkout/$order",
18030 }
18031 .field_name(),
18032 Some(WitTarget::STORE_FIELD_NAME),
18033 );
18034 // Capability arm carries no payload field — the diagnostic
18035 // never reports `expected: "capability"` because the gate's
18036 // Capability arm accepts no payload at all (it fires the
18037 // "expected: none" WrongTarget error instead), so the field-
18038 // name method returns None here rather than a placeholder.
18039 assert_eq!(WitTarget::Capability.field_name(), None);
18040
18041 // Peer const scalar values pinned so a rename on either side
18042 // (author-surface field name in the `(defcaixa …)` DSL, or
18043 // the diagnostic's `expected:` scalar) can't drift without
18044 // failing here first.
18045 assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
18046 assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
18047 assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
18048 }
18049
18050 #[test]
18051 fn wit_target_payload_pins_per_variant() {
18052 // Pin the per-arm payload scalar single-sourced onto the
18053 // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
18054 // [`WitTarget::payload`] — the peer per-half projection to
18055 // [`WitTarget::field_name`] on the paired sub-selector axis. The
18056 // three payload-carrying arms round-trip their author-declared
18057 // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
18058 // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
18059 // the payload-less [`WitTarget::Capability`] arm returns `None`.
18060 // Same shape as the sibling `wit_target_field_name_pins_per_variant`
18061 // (c6ec2af) pin on the Component-0 projection axis, extended
18062 // onto the Component-1 projection axis so both per-half readers
18063 // on the paired dispatch carry their own byte-shape pin.
18064 assert_eq!(
18065 WitTarget::Http {
18066 endpoint: "/charge",
18067 }
18068 .payload(),
18069 Some("/charge"),
18070 );
18071 assert_eq!(
18072 WitTarget::PubSub {
18073 subject: "events.x",
18074 }
18075 .payload(),
18076 Some("events.x"),
18077 );
18078 assert_eq!(
18079 WitTarget::Store {
18080 slot: "checkout/$order",
18081 }
18082 .payload(),
18083 Some("checkout/$order"),
18084 );
18085 assert_eq!(WitTarget::Capability.payload(), None);
18086 }
18087
18088 #[test]
18089 fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
18090 // Per-variant equivalence pin: for every arm of [`WitTarget`],
18091 // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
18092 // byte-for-byte. Guards the drift surface where a future refactor
18093 // that split one accessor off the shared match onto its own
18094 // dispatch — a well-meaning "inline the pair back into per-half
18095 // fields for one crate-internal caller who only wanted one half"
18096 // or a scratch `impl` shadowing the derived projection — would
18097 // silently desynchronize [`WitTarget::payload`] from the
18098 // authoritative [`WitTarget::payload_pair`] dispatch, and every
18099 // downstream consumer that thinks "the payload half of the pair"
18100 // would drift from the diagnostic / graph consumers reading the
18101 // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
18102 // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
18103 // per-half projection pin (`gitrefspec_ref_pair_projects_
18104 // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
18105 // FluxCD source-controller `spec.ref.<field>` axis — same "one
18106 // paired dispatch, both per-half projections agree byte-for-
18107 // byte" discipline extended onto the M3 `:contratos` payload-
18108 // arm surface.
18109 for variant in [
18110 WitTarget::Http {
18111 endpoint: "/charge",
18112 },
18113 WitTarget::PubSub {
18114 subject: "events.checkout.paid",
18115 },
18116 WitTarget::Store {
18117 slot: "checkout/$order",
18118 },
18119 WitTarget::Capability,
18120 ] {
18121 let via_projection = variant.payload();
18122 let via_pair = variant.payload_pair().map(|(_, p)| p);
18123 assert_eq!(
18124 via_projection, via_pair,
18125 "WitTarget::{variant:?} payload() must equal \
18126 payload_pair().map(|(_, p)| p) byte-for-byte — a \
18127 regression that splits the two per-half projections off \
18128 their shared match would silently desynchronize the \
18129 payload accessor from the paired dispatch every \
18130 diagnostic / graph consumer reads through",
18131 );
18132 }
18133 }
18134
18135 #[test]
18136 fn wit_target_http_endpoint_pins_per_variant() {
18137 // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
18138 // [`WitTarget::http_endpoint`] 2-arm dispatch — the
18139 // substrate-primitive per-arm post-projection accessor every
18140 // L7-HTTP-facing consumer routes through, sibling to the peer
18141 // WitContract pre-projection [`WitContract::endpoint`] (7020470)
18142 // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
18143 // arm round-trips its author-declared endpoint verbatim as
18144 // `Some("/charge")`; the three sibling arms
18145 // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
18146 // [`WitTarget::Capability`]) each return `None` because they
18147 // carry no HTTP endpoint by definition. Same fail-before-pass-
18148 // after per-variant discipline as the sibling
18149 // `wit_target_payload_pins_per_variant` (5d6dc92) /
18150 // `wit_target_field_name_pins_per_variant` (c6ec2af) /
18151 // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
18152 // the peer pan-arm / per-half projection axes — extended onto
18153 // the per-arm HTTP-shape post-projection axis so a future
18154 // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
18155 // [`WitTarget::Http`], a `Queue`-shaped peer of
18156 // [`WitTarget::Store`]) trips a compile-time exhaustiveness
18157 // error on the sibling [`WitTarget::http_endpoint`] match arms
18158 // whose payload the L7-HTTP-shape accept-set is meant to bound.
18159 assert_eq!(
18160 WitTarget::Http {
18161 endpoint: "/charge",
18162 }
18163 .http_endpoint(),
18164 Some("/charge"),
18165 );
18166 assert_eq!(
18167 WitTarget::PubSub {
18168 subject: "events.checkout.paid",
18169 }
18170 .http_endpoint(),
18171 None,
18172 );
18173 assert_eq!(
18174 WitTarget::Store {
18175 slot: "checkout/$order",
18176 }
18177 .http_endpoint(),
18178 None,
18179 );
18180 assert_eq!(WitTarget::Capability.http_endpoint(), None);
18181 }
18182
18183 #[test]
18184 fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
18185 // Per-variant coherence pin: for every arm of [`WitTarget`],
18186 // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
18187 // arm (both project the same author-declared request-path
18188 // scalar), and returns `None` on every sibling arm regardless of
18189 // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
18190 // Store carry their own payload the pan-arm accessor surfaces,
18191 // but that payload is not an HTTP endpoint — the per-arm
18192 // accessor must not leak it through the HTTP-shape channel).
18193 // Guards the drift surface where a future refactor that
18194 // conflated the per-arm HTTP projection with the pan-arm
18195 // [`WitTarget::payload`] projection — a well-meaning "one
18196 // accessor for the L7 branch, one for the graph" collapse that
18197 // routes both through the same 4-arm dispatch — would silently
18198 // widen the L7-HTTP-shape accept-set onto pub-sub / store
18199 // payloads at the caixa-mesh L7 emit branch, admitting a
18200 // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
18201 // rule with the operator-side apply-time symptom (Cilium's
18202 // eBPF data-plane rejects every ingress edge whose L7 filter
18203 // doesn't match the wire-format HTTP request line) far from
18204 // the source refactor. Sibling to the peer
18205 // `wit_target_payload_matches_payload_pair_second_component_
18206 // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
18207 // extended onto the per-arm HTTP specialization axis so both
18208 // the pan-arm and the per-arm projections carry their own
18209 // byte-shape coherence witness against the substrate's typed
18210 // arm-family accept-set.
18211 for variant in [
18212 WitTarget::Http {
18213 endpoint: "/charge",
18214 },
18215 WitTarget::PubSub {
18216 subject: "events.checkout.paid",
18217 },
18218 WitTarget::Store {
18219 slot: "checkout/$order",
18220 },
18221 WitTarget::Capability,
18222 ] {
18223 let per_arm = variant.http_endpoint();
18224 let pan_arm = variant.payload();
18225 if variant.is_http() {
18226 assert_eq!(
18227 per_arm, pan_arm,
18228 "WitTarget::{variant:?} http_endpoint() must equal \
18229 payload() on the Http arm — a per-arm-vs-pan-arm \
18230 split would silently drift the L7 emit branch's \
18231 path-scalar source from the graph verb's payload \
18232 scalar source",
18233 );
18234 } else {
18235 assert_eq!(
18236 per_arm, None,
18237 "WitTarget::{variant:?} http_endpoint() must return \
18238 None on non-Http arms — a leak that surfaced a \
18239 pub-sub :subject or a key/value :slot through the \
18240 HTTP-endpoint accessor would silently widen the \
18241 Cilium L7 HTTP `path:` rule accept-set onto \
18242 protocol shapes Cilium's eBPF data-plane can't \
18243 introspect",
18244 );
18245 }
18246 }
18247 }
18248
18249 #[test]
18250 fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
18251 // Per-variant coherence pin: for every arm of [`WitTarget`],
18252 // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
18253 // drift surface where a future extension of the
18254 // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
18255 // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
18256 // accessor to cover both peers) landed without a paired
18257 // extension of the [`gen_platform::IsVariant`]-derived
18258 // `is_http()` predicate's accept-set, or vice versa — a
18259 // regression that split the "which arms count as HTTP-shaped
18260 // for L7-path emission?" answer between two dispatch surfaces
18261 // the substrate ships. Sibling to the peer
18262 // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
18263 // on the paired dispatch axis — extended onto the per-arm
18264 // predicate-vs-accessor coherence axis so the gen-platform
18265 // IsVariant predicate and the substrate-lifted per-arm
18266 // accessor carry one shared answer to "is this the HTTP arm?".
18267 for variant in [
18268 WitTarget::Http {
18269 endpoint: "/charge",
18270 },
18271 WitTarget::PubSub {
18272 subject: "events.checkout.paid",
18273 },
18274 WitTarget::Store {
18275 slot: "checkout/$order",
18276 },
18277 WitTarget::Capability,
18278 ] {
18279 assert_eq!(
18280 variant.http_endpoint().is_some(),
18281 variant.is_http(),
18282 "WitTarget::{variant:?} http_endpoint().is_some() must \
18283 equal is_http() — a drift would split the L7 emit \
18284 branch's arm-set gate from the substrate-derived \
18285 shape-discrimination predicate on the same axis",
18286 );
18287 }
18288 }
18289
18290 #[test]
18291 fn wit_target_pubsub_subject_pins_per_variant() {
18292 // Fail-before-pass-after pin: the substrate-canonical per-arm
18293 // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
18294 // is the single dispatch every future pub-sub-facing consumer
18295 // routes through, sibling to the peer [`WitContract::subject`]
18296 // (63e18a0) pre-projection scalar accessor on the raw-field
18297 // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
18298 // post-projection per-arm accessor on the sibling HTTP-shape
18299 // axis. The [`WitTarget::PubSub`] arm round-trips its
18300 // author-declared subject verbatim as
18301 // `Some("events.checkout.paid")`; the three sibling arms each
18302 // return `None` because they carry no NATS-shaped subject by
18303 // definition. Same fail-before-pass-after per-variant discipline
18304 // as the sibling `wit_target_http_endpoint_pins_per_variant`
18305 // pin on the peer per-arm axis — extended onto the per-arm
18306 // pub-sub-shape post-projection axis so a future [`WitTarget`]
18307 // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
18308 // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
18309 // compile-time exhaustiveness error on the sibling
18310 // [`WitTarget::pubsub_subject`] match arms whose payload the
18311 // pub-sub-shape accept-set is meant to bound.
18312 assert_eq!(
18313 WitTarget::PubSub {
18314 subject: "events.checkout.paid",
18315 }
18316 .pubsub_subject(),
18317 Some("events.checkout.paid"),
18318 );
18319 assert_eq!(
18320 WitTarget::Http {
18321 endpoint: "/charge",
18322 }
18323 .pubsub_subject(),
18324 None,
18325 );
18326 assert_eq!(
18327 WitTarget::Store {
18328 slot: "checkout/$order",
18329 }
18330 .pubsub_subject(),
18331 None,
18332 );
18333 assert_eq!(WitTarget::Capability.pubsub_subject(), None);
18334 }
18335
18336 #[test]
18337 fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
18338 // Per-variant coherence pin: for every arm of [`WitTarget`],
18339 // `.pubsub_subject()` equals `.payload()` on the
18340 // [`WitTarget::PubSub`] arm (both project the same
18341 // author-declared subject scalar), and returns `None` on every
18342 // sibling arm regardless of whether [`WitTarget::payload`]
18343 // itself returns `Some` (Http / Store carry their own payload
18344 // the pan-arm accessor surfaces, but that payload is not a
18345 // pub-sub subject — the per-arm accessor must not leak it
18346 // through the pub-sub-shape channel). Sibling to the peer
18347 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
18348 // coherence pin on the per-arm HTTP-shape axis — extended onto
18349 // the per-arm pub-sub specialization axis so both per-arm
18350 // projections carry their own byte-shape coherence witness
18351 // against the substrate's typed arm-family accept-set.
18352 for variant in [
18353 WitTarget::Http {
18354 endpoint: "/charge",
18355 },
18356 WitTarget::PubSub {
18357 subject: "events.checkout.paid",
18358 },
18359 WitTarget::Store {
18360 slot: "checkout/$order",
18361 },
18362 WitTarget::Capability,
18363 ] {
18364 let per_arm = variant.pubsub_subject();
18365 let pan_arm = variant.payload();
18366 if variant.is_pubsub() {
18367 assert_eq!(
18368 per_arm, pan_arm,
18369 "WitTarget::{variant:?} pubsub_subject() must equal \
18370 payload() on the PubSub arm — a per-arm-vs-pan-arm \
18371 split would silently drift the pub-sub-shape emit \
18372 branch's subject-scalar source from the graph verb's \
18373 payload scalar source",
18374 );
18375 } else {
18376 assert_eq!(
18377 per_arm, None,
18378 "WitTarget::{variant:?} pubsub_subject() must return \
18379 None on non-PubSub arms — a leak that surfaced an \
18380 HTTP :endpoint or a key/value :slot through the \
18381 pub-sub-subject accessor would silently widen the \
18382 downstream NATS-shape accept-set onto protocol \
18383 shapes NATS servers can't route",
18384 );
18385 }
18386 }
18387 }
18388
18389 #[test]
18390 fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
18391 // Per-variant coherence pin: for every arm of [`WitTarget`],
18392 // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
18393 // drift surface where a future extension of the
18394 // [`WitTarget::pubsub_subject`] accessor's accept-set landed
18395 // without a paired extension of the [`gen_platform::IsVariant`]-
18396 // derived `is_pubsub()` predicate's accept-set, or vice versa
18397 // — a regression that split the "which arms count as pub-sub-
18398 // shaped for subject emission?" answer between two dispatch
18399 // surfaces the substrate ships. Sibling to the peer
18400 // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
18401 // pin on the per-arm HTTP-shape axis — extended onto the
18402 // per-arm pub-sub predicate-vs-accessor coherence axis so the
18403 // gen-platform IsVariant predicate and the substrate-lifted
18404 // per-arm accessor carry one shared answer to "is this the
18405 // PubSub arm?".
18406 for variant in [
18407 WitTarget::Http {
18408 endpoint: "/charge",
18409 },
18410 WitTarget::PubSub {
18411 subject: "events.checkout.paid",
18412 },
18413 WitTarget::Store {
18414 slot: "checkout/$order",
18415 },
18416 WitTarget::Capability,
18417 ] {
18418 assert_eq!(
18419 variant.pubsub_subject().is_some(),
18420 variant.is_pubsub(),
18421 "WitTarget::{variant:?} pubsub_subject().is_some() must \
18422 equal is_pubsub() — a drift would split the pub-sub \
18423 emit branch's arm-set gate from the substrate-derived \
18424 shape-discrimination predicate on the same axis",
18425 );
18426 }
18427 }
18428
18429 #[test]
18430 fn wit_target_store_slot_pins_per_variant() {
18431 // Fail-before-pass-after pin: the substrate-canonical per-arm
18432 // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
18433 // is the single dispatch every future store-facing consumer
18434 // routes through, sibling to the peer [`WitContract::slot`]
18435 // pre-projection scalar accessor on the raw-field axis and to
18436 // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
18437 // [`WitTarget::pubsub_subject`] post-projection per-arm
18438 // accessors on the sibling per-payload-arm axes. The
18439 // [`WitTarget::Store`] arm round-trips its author-declared
18440 // slot verbatim as `Some("checkout/$order")`; the three
18441 // sibling arms each return `None` because they carry no
18442 // WASI-key/value slot by definition. Same fail-before-pass-
18443 // after per-variant discipline as the sibling
18444 // `wit_target_http_endpoint_pins_per_variant` +
18445 // `wit_target_pubsub_subject_pins_per_variant` pins on the
18446 // peer per-arm axes — extended onto the per-arm store-shape
18447 // post-projection axis so a future [`WitTarget`] variant
18448 // addition trips a compile-time exhaustiveness error on the
18449 // sibling [`WitTarget::store_slot`] match arms whose payload
18450 // the store-shape accept-set is meant to bound.
18451 assert_eq!(
18452 WitTarget::Store {
18453 slot: "checkout/$order",
18454 }
18455 .store_slot(),
18456 Some("checkout/$order"),
18457 );
18458 assert_eq!(
18459 WitTarget::Http {
18460 endpoint: "/charge",
18461 }
18462 .store_slot(),
18463 None,
18464 );
18465 assert_eq!(
18466 WitTarget::PubSub {
18467 subject: "events.checkout.paid",
18468 }
18469 .store_slot(),
18470 None,
18471 );
18472 assert_eq!(WitTarget::Capability.store_slot(), None);
18473 }
18474
18475 #[test]
18476 fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
18477 // Per-variant coherence pin: for every arm of [`WitTarget`],
18478 // `.store_slot()` equals `.payload()` on the
18479 // [`WitTarget::Store`] arm (both project the same
18480 // author-declared slot scalar), and returns `None` on every
18481 // sibling arm regardless of whether [`WitTarget::payload`]
18482 // itself returns `Some`. Sibling to the peer
18483 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
18484 // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
18485 // pins on the per-arm HTTP and PubSub axes — closes the
18486 // per-arm-vs-pan-arm byte-shape coherence trio across all
18487 // three payload arms.
18488 for variant in [
18489 WitTarget::Http {
18490 endpoint: "/charge",
18491 },
18492 WitTarget::PubSub {
18493 subject: "events.checkout.paid",
18494 },
18495 WitTarget::Store {
18496 slot: "checkout/$order",
18497 },
18498 WitTarget::Capability,
18499 ] {
18500 let per_arm = variant.store_slot();
18501 let pan_arm = variant.payload();
18502 if variant.is_store() {
18503 assert_eq!(
18504 per_arm, pan_arm,
18505 "WitTarget::{variant:?} store_slot() must equal \
18506 payload() on the Store arm — a per-arm-vs-pan-arm \
18507 split would silently drift the store-shape emit \
18508 branch's slot-scalar source from the graph verb's \
18509 payload scalar source",
18510 );
18511 } else {
18512 assert_eq!(
18513 per_arm, None,
18514 "WitTarget::{variant:?} store_slot() must return \
18515 None on non-Store arms — a leak that surfaced an \
18516 HTTP :endpoint or a NATS :subject through the \
18517 key/value-slot accessor would silently widen the \
18518 downstream WASI-key/value slot accept-set onto \
18519 protocol shapes the kv backends can't route",
18520 );
18521 }
18522 }
18523 }
18524
18525 #[test]
18526 fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
18527 // Per-variant coherence pin: for every arm of [`WitTarget`],
18528 // `.store_slot().is_some()` iff `.is_store()`. Guards the
18529 // drift surface where a future extension of the
18530 // [`WitTarget::store_slot`] accessor's accept-set landed
18531 // without a paired extension of the [`gen_platform::IsVariant`]-
18532 // derived `is_store()` predicate's accept-set. Sibling to the
18533 // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
18534 // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
18535 // pins — closes the per-arm predicate-vs-accessor coherence
18536 // trio across all three payload arms so the gen-platform
18537 // IsVariant predicate and the substrate-lifted per-arm
18538 // accessor carry one shared answer to "is this the Store arm?".
18539 for variant in [
18540 WitTarget::Http {
18541 endpoint: "/charge",
18542 },
18543 WitTarget::PubSub {
18544 subject: "events.checkout.paid",
18545 },
18546 WitTarget::Store {
18547 slot: "checkout/$order",
18548 },
18549 WitTarget::Capability,
18550 ] {
18551 assert_eq!(
18552 variant.store_slot().is_some(),
18553 variant.is_store(),
18554 "WitTarget::{variant:?} store_slot().is_some() must \
18555 equal is_store() — a drift would split the store-shape \
18556 emit branch's arm-set gate from the substrate-derived \
18557 shape-discrimination predicate on the same axis",
18558 );
18559 }
18560 }
18561
18562 #[test]
18563 fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
18564 // Fail-before-pass-after cross-axis pin on the trio
18565 // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
18566 // payload-carrying arm of [`WitTarget`], exactly one per-arm
18567 // accessor returns `Some(payload)` and the two peers return
18568 // `None`; and on the payload-less [`WitTarget::Capability`]
18569 // arm, all three return `None`. Guards the drift surface where
18570 // a future extension of one per-arm accessor's accept-set (e.g.
18571 // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
18572 // that widened `http_endpoint` to cover both peers without
18573 // narrowing the peer `pubsub_subject` / `store_slot` accept-
18574 // sets to keep the partition mutually exclusive) landed without
18575 // threading through the peer per-arm accessors — the resulting
18576 // silent overlap would land the same edge's payload on two
18577 // downstream per-shape emit branches at once, or leak a
18578 // pub-sub subject through the store-slot channel, at renderer
18579 // emit time far from the substrate primitive's arm-widening
18580 // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
18581 // 3-way pin on the payload-field-name axis — extended onto the
18582 // per-arm-accessor payload-projection axis so the substrate-
18583 // owned partition invariant is load-bearing at every per-arm
18584 // consumer's read site.
18585 let payload_variants = [
18586 (
18587 WitTarget::Http {
18588 endpoint: "/charge",
18589 },
18590 "http",
18591 ),
18592 (
18593 WitTarget::PubSub {
18594 subject: "events.checkout.paid",
18595 },
18596 "pubsub",
18597 ),
18598 (
18599 WitTarget::Store {
18600 slot: "checkout/$order",
18601 },
18602 "store",
18603 ),
18604 ];
18605 for (variant, own_arm_label) in payload_variants {
18606 let own_arm_hit = match own_arm_label {
18607 "http" => variant.is_http(),
18608 "pubsub" => variant.is_pubsub(),
18609 "store" => variant.is_store(),
18610 other => panic!("unknown own-arm label {other:?}"),
18611 };
18612 let per_arm_results = [
18613 ("http_endpoint", variant.http_endpoint()),
18614 ("pubsub_subject", variant.pubsub_subject()),
18615 ("store_slot", variant.store_slot()),
18616 ];
18617 let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
18618 assert_eq!(
18619 some_count, 1,
18620 "WitTarget::{variant:?} must land exactly one per-arm \
18621 post-projection accessor's Some result — the trio \
18622 (http_endpoint, pubsub_subject, store_slot) must \
18623 partition the payload arm-set; got {per_arm_results:?}",
18624 );
18625 assert!(
18626 own_arm_hit,
18627 "WitTarget::{variant:?} own-arm gen-platform predicate \
18628 must return true on its own arm — a partition failure \
18629 upstream of this pin",
18630 );
18631 assert!(
18632 variant.payload().is_some(),
18633 "WitTarget::{variant:?} pan-arm payload() must return \
18634 Some on every payload-carrying arm the trio partitions",
18635 );
18636 }
18637 // The payload-less Capability arm must return None on every
18638 // per-arm accessor — the partition's terminal-fallback shape.
18639 let cap = WitTarget::Capability;
18640 assert_eq!(cap.http_endpoint(), None);
18641 assert_eq!(cap.pubsub_subject(), None);
18642 assert_eq!(cap.store_slot(), None);
18643 assert_eq!(
18644 cap.payload(),
18645 None,
18646 "WitTarget::Capability pan-arm payload() must return None — \
18647 the trio's payload-less-arm coherence witness",
18648 );
18649 }
18650
18651 #[test]
18652 fn wit_target_field_names_are_pairwise_distinct() {
18653 // Distinctness pin: if any two of the three payload-field-name
18654 // scalars ever collapse (e.g. an accidental `endpoint` copy-
18655 // paste over the `subject` const), the [`WitContract::target`]
18656 // gate's diagnostic would point authors at the wrong field —
18657 // an "expected `:endpoint`" error on a pub-sub edge would
18658 // silently misroute the fix. Same cross-axis-distinctness
18659 // discipline as the peer M3 `:placement :estrategia` variant-
18660 // discriminator scalar-value pins (cc8f749) applied to the
18661 // payload-field-name axis.
18662 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
18663 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
18664 assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
18665 }
18666
18667 #[test]
18668 fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
18669 // Fail-before-pass-after pin: the graph-verb payload column's
18670 // per-arm `{field}={payload}` byte-string is derived through the
18671 // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
18672 // payload-carrying arms, not through a hand-rolled per-arm match
18673 // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
18674 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
18675 // inline. A future variant addition — the M4-and-later per-edge
18676 // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
18677 // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
18678 // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
18679 // and both [`WitTarget::label`] (duplicate-`:contratos`
18680 // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
18681 // payload column) pick up the new arm from the same dispatch.
18682 // Prior to this lift the graph verb open-coded the 4-arm match
18683 // in caixa-feira, so a variant addition would have to be threaded
18684 // through both projections in lockstep or the graph verb would
18685 // silently drop the new arm to `(capability-only)`.
18686 for variant in [
18687 WitTarget::Http {
18688 endpoint: "/charge",
18689 },
18690 WitTarget::PubSub {
18691 subject: "events.checkout.paid",
18692 },
18693 WitTarget::Store {
18694 slot: "checkout/$order",
18695 },
18696 ] {
18697 let (field, payload) = variant
18698 .payload_pair()
18699 .expect("payload arm must expose (field, payload)");
18700 assert_eq!(
18701 variant.graph_label(),
18702 format!("{field}={payload}"),
18703 "WitTarget::{variant:?} graph_label must route the \
18704 `{{field}}={{payload}}` template through payload_pair — \
18705 a regression to a hand-rolled per-arm match at the graph \
18706 verb would silently disagree with a future variant \
18707 addition landed only at payload_pair"
18708 );
18709 }
18710 }
18711
18712 #[test]
18713 fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
18714 // Fail-before-pass-after pin on the payload-less arm: the graph
18715 // verb's `(capability-only)` byte-string routes through the
18716 // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
18717 // [`WitTarget::Capability`] arm, not through an inline
18718 // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
18719 // per-`:contratos` payload column. Peer of the sibling
18720 // [`wit_target_label_pins_per_variant_format`] Capability-arm
18721 // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
18722 // extended here onto the third payload-less-arm consumer axis
18723 // (graph verb, sibling to the duplicate-`:contratos` diagnostic
18724 // axis and the wrong-target diagnostic axis).
18725 assert_eq!(
18726 WitTarget::Capability.graph_label(),
18727 WitTarget::CAPABILITY_GRAPH_LABEL,
18728 );
18729 assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
18730 }
18731
18732 #[test]
18733 fn wit_target_capability_graph_label_distinct_from_capability_label() {
18734 // Cross-consumer-axis distinctness pin: the graph-verb
18735 // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
18736 // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
18737 // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
18738 // payload)`) surface the payload-less arm on two distinct
18739 // consumer axes; a collapse (an accidental rebrand that lands
18740 // one spelling on both consts, a copy-paste that unifies them
18741 // "for consistency") would silently merge the two byte-strings
18742 // and lose the vocabulary distinction the graph verb's
18743 // compact-column form and the diagnostic's descriptive-clause
18744 // form each carry on purpose. Peer of the sibling 4-way
18745 // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
18746 // pin on the `ContratoWrongTarget::expected` scalar-value axis —
18747 // extended here onto the cross-consumer-axis distinctness of the
18748 // two payload-less-arm consts.
18749 assert_ne!(
18750 WitTarget::CAPABILITY_GRAPH_LABEL,
18751 WitTarget::CAPABILITY_LABEL,
18752 "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
18753 and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
18754 diagnostic) must remain distinct — a collapse would silently \
18755 merge two consumer axes onto one spelling"
18756 );
18757 }
18758
18759 #[test]
18760 fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
18761 // 4-way distinctness pin extending the sibling
18762 // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
18763 // (which covers only the HTTP / PubSub / Store payload arms)
18764 // onto the fourth scalar the shared
18765 // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
18766 // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
18767 // (`"none"`), the payload-less Capability-arm rejection scalar.
18768 //
18769 // All four [`WitTarget::HTTP_FIELD_NAME`] /
18770 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
18771 // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
18772 // dispatch surface [`WitContract::target`] writes onto the
18773 // `ContratoWrongTarget::expected` field — the same `&'static
18774 // str` axis authors read as "this WIT world's shape admits
18775 // (only|not) `:<field>`". Pairwise-distinctness is the invariant
18776 // downstream consumers rely on: an `expected: "endpoint"`
18777 // diagnostic on a Capability-shaped edge tells the author to
18778 // add a `:endpoint "…"` slot to a WIT world that admits none,
18779 // silently misrouting the fix. Until this pin landed the three
18780 // payload-arm consts were distinctness-guarded by the sibling
18781 // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
18782 // scalar (d4f54f2) sat unguarded — a rebrand collision (the
18783 // author-facing vocabulary shift from `"none"` to `"endpoint"`
18784 // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
18785 // into per-shape peers) would have silently landed one
18786 // Capability-arm rejection on a payload-arm's `expected:` byte-
18787 // string and desynchronized the diagnostic from the author's
18788 // typed shape.
18789 //
18790 // Same 4-way pairwise-distinctness pin discipline as the peer
18791 // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
18792 // (cc8f749) applies on the sibling M3 closed-set typed-enum
18793 // scalar-value dispatch axis; extends the pin trajectory the
18794 // sibling `wit_target_field_names_are_pairwise_distinct`
18795 // 3-way pin opened to cover the last unguarded corner on the
18796 // `ContratoWrongTarget::expected` scalar-value axis.
18797 //
18798 // Fail-before-pass-after locally verified by mutating
18799 // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
18800 // — this pin fires as expected; restoring passes.
18801 let all = [
18802 WitTarget::HTTP_FIELD_NAME,
18803 WitTarget::PUBSUB_FIELD_NAME,
18804 WitTarget::STORE_FIELD_NAME,
18805 WitTarget::CAPABILITY_EXPECTED,
18806 ];
18807 for (i, a) in all.iter().enumerate() {
18808 for (j, b) in all.iter().enumerate() {
18809 if i != j {
18810 assert_ne!(
18811 a, b,
18812 "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
18813 STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
18814 pairwise distinct — got duplicate {a:?} at indices \
18815 {i} and {j}; all four scalars thread through the \
18816 shared `AplicacaoError::ContratoWrongTarget::expected` \
18817 &'static str axis, so a collapse silently misdirects \
18818 the diagnostic on which typed shape the WIT world admits",
18819 );
18820 }
18821 }
18822 }
18823 }
18824
18825 #[test]
18826 fn wit_target_is_variant_predicates_partition_the_arm_set() {
18827 // Fail-before-pass-after pin on the
18828 // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
18829 // each of the four variants exactly one of the generated
18830 // `is_http` / `is_pubsub` / `is_store` / `is_capability`
18831 // predicates returns `true` and the other three return
18832 // `false`. Prior to this derive the only production
18833 // arm-discriminator on [`WitTarget`] — the sync-cycle
18834 // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
18835 // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
18836 // the variant that expressed no compile-time link back to
18837 // the closed-set typed dispatch a future fifth
18838 // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
18839 // split of [`WitTarget::PubSub`] into shape-specific peers,
18840 // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
18841 // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
18842 // to thread through in lockstep or the DFS exclusion would
18843 // silently disagree with the peer diagnostic templates on
18844 // which arms carry sync-versus-async semantics. Peer of the
18845 // sibling [`crate::CaixaKind`] (f5bba80),
18846 // [`PlacementStrategy`] (766ec63),
18847 // [`crate::supervisor::RestartStrategy`],
18848 // [`crate::supervisor::RestartPolicy`], and
18849 // [`crate::upgrade::UpgradeInstruction`] (915a934)
18850 // `IsVariant` derives on the sibling closed-set typed-enum
18851 // discriminator axes — extends the same one-typed-dispatch-
18852 // per-variant discipline onto the last unlifted closed-set
18853 // typed-enum discriminator on the caixa surface (the M3
18854 // mesh-slot per-`:contratos` target-arm axis), closing the
18855 // arm-discriminator convergence trajectory across every
18856 // closed-set typed enum in caixa-core.
18857 let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
18858 (
18859 WitTarget::Http { endpoint: "/x" },
18860 [true, false, false, false],
18861 ),
18862 (
18863 WitTarget::PubSub {
18864 subject: "events.x",
18865 },
18866 [false, true, false, false],
18867 ),
18868 (
18869 WitTarget::Store { slot: "kv/x" },
18870 [false, false, true, false],
18871 ),
18872 (WitTarget::Capability, [false, false, false, true]),
18873 ];
18874 for (variant, expected) in rows {
18875 let observed = [
18876 variant.is_http(),
18877 variant.is_pubsub(),
18878 variant.is_store(),
18879 variant.is_capability(),
18880 ];
18881 assert_eq!(
18882 observed, expected,
18883 "WitTarget::{variant:?} is_* predicates must partition \
18884 the arm set (http, pubsub, store, capability); got {observed:?}"
18885 );
18886 }
18887 }
18888
18889 #[test]
18890 fn wit_target_is_variant_predicates_are_const_fn() {
18891 // The [`gen_platform::IsVariant`] derive emits `const fn`
18892 // predicates on the peer [`crate::CaixaKind`] +
18893 // [`crate::upgrade::UpgradeInstruction`] +
18894 // [`crate::supervisor::RestartStrategy`] +
18895 // [`crate::supervisor::RestartPolicy`] +
18896 // [`PlacementStrategy`] closed-set typed enums — pin the
18897 // same posture on [`WitTarget`] so a future accidental
18898 // downgrade to non-`const` (an added runtime helper reachable
18899 // only from a non-`const` context, a manual hand-rolled
18900 // `impl` that shadows the derive-generated method) trips at
18901 // caixa-core build time rather than surfacing as a downstream
18902 // `const`-context regression far from the derive declaration.
18903 //
18904 // Unlike the peer unit-variant enums (`CaixaKind` /
18905 // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
18906 // whose `const` constructors need no arguments, the three
18907 // payload-carrying [`WitTarget`] arms are const-constructed
18908 // through `&'static str` payloads — the same `'static`
18909 // lifetime the closed-set typed enum's four-arm partition
18910 // pin above already threads through.
18911 //
18912 // The pin lives inside a `const { assert!(..) }` block so the
18913 // compiler enforces both halves (arm predicate is `const`-
18914 // callable AND returns `true` for the matching arm) at
18915 // caixa-core compile time — peer to the sibling
18916 // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
18917 // typed enum arm-predicate const-callability axis.
18918 const {
18919 assert!(WitTarget::Http { endpoint: "/x" }.is_http());
18920 assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
18921 assert!(WitTarget::Store { slot: "kv/x" }.is_store());
18922 assert!(WitTarget::Capability.is_capability());
18923 }
18924 }
18925
18926 #[test]
18927 fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
18928 // Consumer-side pin on the sole production converge site:
18929 // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
18930 // edges from the synchronous-subgraph DFS via the lifted
18931 // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
18932 // predicate (rebound from the prior raw
18933 // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
18934 // variant). Byte-equivalent today (`is_pubsub` is the
18935 // derive-generated `matches!(self, Self::PubSub { .. })` by
18936 // construction, the `#[is_variant(name = "pubsub")]` override
18937 // aliasing the auto-derived `is_pub_sub` back to the sibling
18938 // [`WitContract::is_pubsub`] name); pin the behavior so a
18939 // future accidental drift (a rebind onto a peer arm
18940 // predicate, a manual hand-rolled `impl` that shadows the
18941 // derive-generated method with different semantics, a peer
18942 // arm rename that shifts which variant carries sync-versus-
18943 // async semantics) trips at caixa-core test time rather than
18944 // at some downstream operator's runtime dispatch far from the
18945 // rebind commit.
18946 //
18947 // The fixture constructs a two-Servico Aplicacao with one
18948 // pub-sub edge that would close a sync-cycle if the DFS did
18949 // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
18950 // pub-sub exclusion means the DFS sees only the `b → a` HTTP
18951 // edge, which is not a cycle. A regression in the converge
18952 // (a rebind that reads the pub-sub arm as sync) would report
18953 // `AplicacaoError::ContratoCycle`.
18954 let s = AplicacaoSpec {
18955 membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
18956 contratos: vec![
18957 // Pub-sub edge: DFS must skip via is_pubsub().
18958 WitContract {
18959 de: "a".into(),
18960 para: "b".into(),
18961 wit: "nats:pub-sub".into(),
18962 endpoint: None,
18963 subject: Some("events.x".into()),
18964 slot: None,
18965 },
18966 // HTTP edge: DFS must include.
18967 WitContract {
18968 de: "b".into(),
18969 para: "a".into(),
18970 wit: "wasi:http/proxy".into(),
18971 endpoint: Some("/x".into()),
18972 subject: None,
18973 slot: None,
18974 },
18975 ],
18976 politicas: MeshPolicy::default(),
18977 placement: Placement {
18978 estrategia: PlacementStrategy::Replicated,
18979 clusters: vec!["rio".into()],
18980 affinity: None,
18981 shard_key: None,
18982 },
18983 entrada: None,
18984 };
18985 s.validate()
18986 .expect("pub-sub edge must be excluded from sync-cycle DFS");
18987 }
18988
18989 #[test]
18990 fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
18991 // Consumer-side pin: the same three peer consts thread through
18992 // both the [`WitTarget::label`] template (leading-`:` keyword
18993 // prefix in the duplicate-`:contratos` diagnostic) and the
18994 // [`WitContract::target`] gate's [`AplicacaoError::
18995 // ContratoMissingTarget`] `expected:` scalar (the field the
18996 // author needs to add). Pin both routes at once so a future
18997 // refactor can't accidentally split them onto separate string
18998 // literals — the "one place, everywhere reaches for it"
18999 // invariant the peer const set carries.
19000 let http_label = WitTarget::Http { endpoint: "/x" }.label();
19001 assert!(
19002 http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
19003 "label must lead with :{} keyword (got {http_label:?})",
19004 WitTarget::HTTP_FIELD_NAME,
19005 );
19006
19007 let mut s = three_member_spec();
19008 s.contratos.push(WitContract {
19009 de: "cart".into(),
19010 para: "catalog".into(),
19011 wit: "kafka:topic".into(),
19012 endpoint: None,
19013 subject: None,
19014 slot: None,
19015 });
19016 match s.validate().unwrap_err() {
19017 AplicacaoError::ContratoMissingTarget { expected, .. } => {
19018 assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
19019 }
19020 other => panic!("expected ContratoMissingTarget, got {other:?}"),
19021 }
19022 }
19023
19024 #[test]
19025 fn duplicate_pubsub_diagnostic_names_offending_subject() {
19026 // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
19027 // on the pub-sub target axis: the duplicate-edge diagnostic
19028 // must name the `:subject` payload verbatim (not just the
19029 // `(de, para, wit)` triple). Prior to lifting the label onto
19030 // [`WitTarget::label`] the diagnostic derived the label from
19031 // raw [`WitContract`] `Option<String>` probes — a future
19032 // `WitTarget` variant addition (M4 per-edge WIT registry)
19033 // would silently fall through to the `Capability` "no
19034 // payload" default without a compiler warning. Pinning the
19035 // pub-sub arm's format closes the second of three
19036 // payload-carrying `WitTarget` arms this diagnostic threads
19037 // through.
19038 let mut s = three_member_spec();
19039 let pubsub = WitContract {
19040 de: "payment".into(),
19041 para: "cart".into(),
19042 wit: "nats:pub-sub".into(),
19043 endpoint: None,
19044 subject: Some("events.checkout.paid".into()),
19045 slot: None,
19046 };
19047 s.contratos.push(pubsub.clone());
19048 s.contratos.push(pubsub);
19049 let err = s.validate().unwrap_err();
19050 let msg = format!("{err}");
19051 assert!(
19052 msg.contains(":subject \"events.checkout.paid\""),
19053 "duplicate-pubsub diagnostic must name the offending \
19054 :subject payload (got: {msg:?})"
19055 );
19056 }
19057
19058 #[test]
19059 fn duplicate_store_diagnostic_names_offending_slot() {
19060 // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
19061 // key-value target axis: the diagnostic must name the `:slot`
19062 // payload verbatim. Third of three payload-carrying
19063 // `WitTarget` arms this diagnostic threads through, closing
19064 // the per-arm label pin trilogy (`Http` — 6841,
19065 // `PubSub` + `Store` — this test + peer above).
19066 let mut s = three_member_spec();
19067 let store = WitContract {
19068 de: "cart".into(),
19069 para: "payment".into(),
19070 wit: "wasi:keyvalue/store".into(),
19071 endpoint: None,
19072 subject: None,
19073 slot: Some("checkout/$orderId".into()),
19074 };
19075 s.contratos
19076 .retain(|c| !(c.de == "cart" && c.para == "payment"));
19077 s.contratos.push(store.clone());
19078 s.contratos.push(store);
19079 let err = s.validate().unwrap_err();
19080 let msg = format!("{err}");
19081 assert!(
19082 msg.contains(":slot \"checkout/$orderId\""),
19083 "duplicate-store diagnostic must name the offending :slot \
19084 payload (got: {msg:?})"
19085 );
19086 }
19087
19088 #[test]
19089 fn rejects_entrada_path_without_leading_slash() {
19090 let mut s = three_member_spec();
19091 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
19092 let err = s.validate().unwrap_err();
19093 assert!(
19094 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
19095 "got {err:?}"
19096 );
19097 }
19098
19099 #[test]
19100 fn rejects_empty_entrada_path() {
19101 let mut s = three_member_spec();
19102 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
19103 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
19104 }
19105
19106 #[test]
19107 fn rejects_duplicate_entrada_paths() {
19108 let mut s = three_member_spec();
19109 s.entrada.as_mut().unwrap().paths = vec![
19110 "/api/cart".into(),
19111 "/api/products".into(),
19112 "/api/cart".into(),
19113 ];
19114 let err = s.validate().unwrap_err();
19115 assert!(
19116 matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
19117 "got {err:?}"
19118 );
19119 }
19120
19121 #[test]
19122 fn rejects_zero_entrada_port() {
19123 let mut s = three_member_spec();
19124 s.entrada.as_mut().unwrap().port = 0;
19125 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
19126 }
19127
19128 // ── :entrada :paths value-shape gate ─────────────────────────────
19129 //
19130 // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
19131 // sibling `:paths` axis. Every authoring footgun the K8s Gateway
19132 // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
19133 // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
19134 // time now becomes a caixa-build-time `EntradaPathInvalid` with
19135 // the offending `:paths` entry named verbatim.
19136
19137 #[test]
19138 fn rejects_entrada_path_with_query() {
19139 // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
19140 // silently passed validate and the Gateway API webhook
19141 // rejected it at apply time with no source citation.
19142 let mut s = three_member_spec();
19143 s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
19144 let err = s.validate().unwrap_err();
19145 assert!(
19146 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19147 if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
19148 "got {err:?}"
19149 );
19150 }
19151
19152 #[test]
19153 fn rejects_entrada_path_with_fragment() {
19154 let mut s = three_member_spec();
19155 s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
19156 let err = s.validate().unwrap_err();
19157 assert!(
19158 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19159 if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
19160 "got {err:?}"
19161 );
19162 }
19163
19164 #[test]
19165 fn rejects_entrada_path_with_space() {
19166 let mut s = three_member_spec();
19167 s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
19168 let err = s.validate().unwrap_err();
19169 assert!(
19170 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19171 if path == "/api/my cart" && reason.contains("whitespace")),
19172 "got {err:?}"
19173 );
19174 }
19175
19176 #[test]
19177 fn rejects_entrada_path_with_tab() {
19178 let mut s = three_member_spec();
19179 s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
19180 let err = s.validate().unwrap_err();
19181 assert!(
19182 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19183 if path == "/api/\tcart" && reason.contains("whitespace")),
19184 "got {err:?}"
19185 );
19186 }
19187
19188 #[test]
19189 fn rejects_entrada_path_with_control_char() {
19190 // 0x01 (SOH) — a non-whitespace control char surfaces the
19191 // distinct "control character" reason arm, separate from
19192 // the whitespace arm. Pinned so a future refactor that
19193 // collapses the two arms can't accidentally drop the more
19194 // self-locating diagnostic.
19195 let mut s = three_member_spec();
19196 s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
19197 let err = s.validate().unwrap_err();
19198 assert!(
19199 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19200 if path == "/api/\x01cart" && reason.contains("control character")),
19201 "got {err:?}"
19202 );
19203 }
19204
19205 #[test]
19206 fn rejects_entrada_path_with_non_ascii() {
19207 // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
19208 // unreserved-set rule rejects. The Gateway API webhook
19209 // rejects literal non-ASCII bytes; percent-encoding is the
19210 // only way to author non-ASCII in a path.
19211 let mut s = three_member_spec();
19212 s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
19213 let err = s.validate().unwrap_err();
19214 assert!(
19215 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19216 if path == "/api/café" && reason.contains("non-ASCII")),
19217 "got {err:?}"
19218 );
19219 }
19220
19221 #[test]
19222 fn rejects_entrada_path_with_consecutive_slashes() {
19223 let mut s = three_member_spec();
19224 s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
19225 let err = s.validate().unwrap_err();
19226 assert!(
19227 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19228 if path == "/api//cart" && reason.contains("consecutive `/`")),
19229 "got {err:?}"
19230 );
19231 }
19232
19233 #[test]
19234 fn rejects_entrada_path_with_dot_segment() {
19235 let mut s = three_member_spec();
19236 s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
19237 let err = s.validate().unwrap_err();
19238 assert!(
19239 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19240 if path == "/api/./cart" && reason.contains("`.` segment")),
19241 "got {err:?}"
19242 );
19243 }
19244
19245 #[test]
19246 fn rejects_entrada_path_with_trailing_dot_segment() {
19247 // The bare `/.` and the trailing `/foo/.` are both rejected
19248 // by the Gateway API webhook; pinned separately so a future
19249 // narrowing that catches only the inner form surfaces here.
19250 let mut s = three_member_spec();
19251 s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
19252 let err = s.validate().unwrap_err();
19253 assert!(
19254 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19255 if path == "/api/." && reason.contains("`.` segment")),
19256 "got {err:?}"
19257 );
19258 }
19259
19260 #[test]
19261 fn rejects_entrada_path_with_parent_segment() {
19262 let mut s = three_member_spec();
19263 s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
19264 let err = s.validate().unwrap_err();
19265 assert!(
19266 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19267 if path == "/api/../etc" && reason.contains("`..` parent-segment")),
19268 "got {err:?}"
19269 );
19270 }
19271
19272 #[test]
19273 fn rejects_entrada_path_with_trailing_parent_segment() {
19274 // Trailing `/..` — symmetric arm of the parent-segment rule,
19275 // pinned separately so a future relaxation that only checks
19276 // the inner form (`/../`) surfaces here.
19277 let mut s = three_member_spec();
19278 s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
19279 let err = s.validate().unwrap_err();
19280 assert!(
19281 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19282 if path == "/api/.." && reason.contains("`..` parent-segment")),
19283 "got {err:?}"
19284 );
19285 }
19286
19287 #[test]
19288 fn rejects_entrada_path_too_long() {
19289 // 1025-byte path — one over the Gateway API HTTPPathMatch.value
19290 // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
19291 // ASCII-alphanumeric body so only the length rule fires.
19292 let mut s = three_member_spec();
19293 let big = format!("/api/{}", "a".repeat(1020));
19294 assert_eq!(big.len(), 1025);
19295 s.entrada.as_mut().unwrap().paths = vec![big.clone()];
19296 let err = s.validate().unwrap_err();
19297 assert!(
19298 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19299 if path == &big && reason.contains("max length of 1024")),
19300 "got {err:?}"
19301 );
19302 }
19303
19304 #[test]
19305 fn entrada_path_max_length_validates() {
19306 // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
19307 // maxLength cap. Boundary pin: drift in the cap surfaces here
19308 // and at `rejects_entrada_path_too_long` simultaneously.
19309 let mut s = three_member_spec();
19310 let big = format!("/api/{}", "a".repeat(1019));
19311 assert_eq!(big.len(), 1024);
19312 s.entrada.as_mut().unwrap().paths = vec![big];
19313 s.validate().unwrap();
19314 }
19315
19316 #[test]
19317 fn entrada_accepts_canonical_paths() {
19318 // Positive-control sweep — every form the Gateway API
19319 // apiserver accepts must round-trip through validate. Covers
19320 // the root catch-all, plain paths, dot-prefixed segments
19321 // (hidden-file-style, distinct from `.` and `..` segments
19322 // which are rejected), digit-bearing segments, the canonical
19323 // route-template `:param` form (`:` is RFC 3986 reserved-set
19324 // valid in paths), trailing-slash form, percent-encoded
19325 // segments, and an interior `..` *substring* (`/foo..bar` is
19326 // not the `..` segment and is allowed).
19327 for path in [
19328 "/",
19329 "/api/cart",
19330 "/healthz",
19331 "/api/.config",
19332 "/v1/products",
19333 "/products/:id",
19334 "/api/cart/",
19335 "/api/caf%C3%A9",
19336 "/foo..bar",
19337 "/...",
19338 ] {
19339 let mut s = three_member_spec();
19340 s.entrada.as_mut().unwrap().paths = vec![path.into()];
19341 s.validate()
19342 .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
19343 }
19344 }
19345
19346 #[test]
19347 fn entrada_path_empty_takes_precedence_over_invalid() {
19348 // Ordering pin: `EntradaPathEmpty` is the more self-locating
19349 // diagnostic on `""` and must lead — `validate_entrada_path`
19350 // is only reached after the empty-check fires at the call
19351 // site. (The predicate itself defends against direct
19352 // invocation by returning the same error on `""`.)
19353 let mut s = three_member_spec();
19354 s.entrada.as_mut().unwrap().paths = vec![String::new()];
19355 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
19356 }
19357
19358 #[test]
19359 fn entrada_path_not_absolute_takes_precedence_over_invalid() {
19360 // Ordering pin: a path without a leading `/` surfaces the
19361 // narrower `EntradaPathNotAbsolute` diagnostic first; the
19362 // value-shape gate is only consulted on paths that already
19363 // satisfy the absolute-prefix invariant.
19364 let mut s = three_member_spec();
19365 // `bad path` would fire the whitespace rule under the
19366 // value-shape gate, but missing-leading-`/` is the more
19367 // self-locating diagnostic.
19368 s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
19369 let err = s.validate().unwrap_err();
19370 assert!(
19371 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
19372 "got {err:?}"
19373 );
19374 }
19375
19376 #[test]
19377 fn entrada_path_invalid_fires_before_duplicate_check() {
19378 // Ordering pin: a malformed path on the *first* entry of a
19379 // would-be duplicate pair fires the value-shape gate before
19380 // the duplicate gate, mirroring the
19381 // `placement_cluster_invalid_fires_before_duplicate_check`
19382 // (6cbb900) pattern on the peer axis.
19383 let mut s = three_member_spec();
19384 s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
19385 let err = s.validate().unwrap_err();
19386 assert!(
19387 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
19388 "got {err:?}"
19389 );
19390 }
19391
19392 #[test]
19393 fn entrada_path_diagnostic_carries_offending_path() {
19394 // Diagnostic-shape pin — the offending path + a non-empty
19395 // reason flow through verbatim so the author can grep their
19396 // caixa.lisp for `:paths` and fix it in one edit. Same shape
19397 // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
19398 let mut s = three_member_spec();
19399 s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
19400 let err = s.validate().unwrap_err();
19401 match err {
19402 AplicacaoError::EntradaPathInvalid { path, reason } => {
19403 assert_eq!(path, "/api?q=1");
19404 assert!(!reason.is_empty(), "reason field must be non-empty");
19405 }
19406 other => panic!("expected EntradaPathInvalid, got {other:?}"),
19407 }
19408 }
19409
19410 #[test]
19411 fn rejects_entrada_path_with_curly_brace_template_form() {
19412 // Per-axis pin on the shared `is_gateway_api_http_path`
19413 // reserved-byte arm: the canonical "I wrote an OpenAPI
19414 // path-template `{id}` instead of the Gateway API `:id` form"
19415 // footgun the K8s apiserver would otherwise catch at admission
19416 // time on every `HTTPRoute.spec.rules[].matches[].path.value`
19417 // landing site, far from the caixa.lisp. Surfaces as
19418 // `EntradaPathInvalid` carrying the offending path verbatim
19419 // plus the canonical `%7B`/`%7D` percent-encoding remediation
19420 // — the substrate-side `gateway_api_http_path_rejects_every_
19421 // reserved_printable_ascii_byte` predicate-level sweep pins the
19422 // full eleven-byte set; this per-axis pin confirms the
19423 // diagnostic flows through to the `EntradaPathInvalid` variant.
19424 let mut s = three_member_spec();
19425 s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
19426 let err = s.validate().unwrap_err();
19427 assert!(
19428 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
19429 if path == "/api/cart/{id}"
19430 && reason.contains("reserved character")
19431 && reason.contains("'{'")
19432 && reason.contains("%7B")),
19433 "got {err:?}"
19434 );
19435 }
19436
19437 #[test]
19438 fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
19439 // Per-axis peer of `rejects_entrada_path_with_curly_brace_
19440 // template_form` on the sibling `:contratos :endpoint` axis.
19441 // Same shared `is_gateway_api_http_path` reserved-byte arm
19442 // fires through `ContratoEndpointInvalid`, with the offending
19443 // endpoint + `:de` + `:para` + reason flowing through verbatim.
19444 // Pins that the lifted predicate's tightening lands on both
19445 // caller axes simultaneously — one source of truth for the
19446 // Gateway API HTTPPathMatch.value accepted set.
19447 let err = contrato_endpoint_err("/api/cart/{id}");
19448 assert!(
19449 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
19450 if endpoint == "/api/cart/{id}"
19451 && reason.contains("reserved character")
19452 && reason.contains("'{'")
19453 && reason.contains("%7B")),
19454 "got {err:?}"
19455 );
19456 }
19457
19458 // ── :entrada :host value-shape gate ──────────────────────────────
19459 //
19460 // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
19461 // the sibling `:host` axis. Every authoring footgun the K8s
19462 // Gateway API v1 apiserver would catch at admission time becomes
19463 // a caixa-build-time `EntradaHostInvalid` with the offending
19464 // `:host` named verbatim. Same diagnostic shape as
19465 // `MembroVersaoInvalid` (9888b13).
19466
19467 #[test]
19468 fn rejects_entrada_host_with_scheme() {
19469 // Fail-before-pass-after pin — pre-gate codebases silently
19470 // accepted `https://…` and the apiserver rejected it at apply
19471 // time with no source citation.
19472 let mut s = three_member_spec();
19473 s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
19474 let err = s.validate().unwrap_err();
19475 assert!(
19476 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
19477 if host == "https://checkout.quero.cloud"),
19478 "got {err:?}"
19479 );
19480 }
19481
19482 #[test]
19483 fn rejects_entrada_host_with_port() {
19484 // The `:8080` port suffix is the canonical "I forgot the port
19485 // belongs in `:entrada :port`" footgun. The top-level `:` arm
19486 // (introduced after the per-label loop-only impl silently
19487 // surfaced a deep "label \"cloud:8080\" contains invalid
19488 // character ':'" leak) names the canonical fix verbatim — the
19489 // `:entrada :port` slot.
19490 let mut s = three_member_spec();
19491 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
19492 let err = s.validate().unwrap_err();
19493 assert!(
19494 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
19495 if host == "checkout.quero.cloud:8080"
19496 && reason.contains(":entrada :port")),
19497 "got {err:?}"
19498 );
19499 }
19500
19501 #[test]
19502 fn rejects_entrada_host_with_trailing_colon() {
19503 // Trailing `:` (e.g. an in-progress `:host "example.com:"`
19504 // edit) — the per-label loop would land it as a deep
19505 // "label \"com:\" must start and end with an alphanumeric"
19506 // / "contains invalid character ':'" leak. The top-level
19507 // `:` arm pre-empts with the canonical `:port` slot
19508 // diagnostic.
19509 let mut s = three_member_spec();
19510 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
19511 let err = s.validate().unwrap_err();
19512 assert!(
19513 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
19514 if host == "checkout.quero.cloud:"
19515 && reason.contains(":entrada :port")),
19516 "got {err:?}"
19517 );
19518 }
19519
19520 #[test]
19521 fn rejects_entrada_host_unbracketed_ipv6_literal() {
19522 // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
19523 // literals across the board (peer with `rejects_entrada_host_
19524 // ipv4_literal` above for the four-label-all-digit IPv4 arm).
19525 // Before this top-level `:` arm landed the per-label loop
19526 // surfaced a single-label byte-class diagnostic that named the
19527 // `:` byte but not the IP-literal prohibition. The top-level
19528 // `:` arm names both the `:port` slot and the IP-literal
19529 // prohibition verbatim, so an author whose `:host "2001:..."`
19530 // value lands here gets a self-locating fix either way.
19531 let mut s = three_member_spec();
19532 s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
19533 let err = s.validate().unwrap_err();
19534 assert!(
19535 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
19536 if host == "2001:db8::1"
19537 && reason.contains("IPv6")),
19538 "got {err:?}"
19539 );
19540 }
19541
19542 #[test]
19543 fn rejects_entrada_host_wildcard_with_port() {
19544 // Wildcard host with port suffix — the `*.` strip and the
19545 // per-label loop on `["foo", "quero", "cloud:8080"]` would
19546 // surface the deep byte-class leak. The top-level `:` arm sits
19547 // upstream of the `*.` strip, so it names the canonical `:port`
19548 // fix verbatim regardless of whether the host is wildcard-led.
19549 let mut s = three_member_spec();
19550 s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
19551 let err = s.validate().unwrap_err();
19552 assert!(
19553 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
19554 if host == "*.quero.cloud:8080"
19555 && reason.contains(":entrada :port")),
19556 "got {err:?}"
19557 );
19558 }
19559
19560 #[test]
19561 fn rejects_entrada_host_with_path() {
19562 let mut s = three_member_spec();
19563 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
19564 let err = s.validate().unwrap_err();
19565 assert!(
19566 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
19567 if host == "checkout.quero.cloud/api"),
19568 "got {err:?}"
19569 );
19570 }
19571
19572 #[test]
19573 fn rejects_entrada_host_with_uppercase() {
19574 // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
19575 // rejected, not silently lower-cased.
19576 let mut s = three_member_spec();
19577 s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
19578 let err = s.validate().unwrap_err();
19579 assert!(
19580 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19581 if reason.contains("uppercase")),
19582 "got {err:?}"
19583 );
19584 }
19585
19586 #[test]
19587 fn rejects_entrada_host_with_underscore() {
19588 // RFC 1123 allows `[a-z0-9-]` only; underscore is the
19589 // canonical "I'm thinking of HTTP cookies / SRV records" leak.
19590 let mut s = three_member_spec();
19591 s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
19592 let err = s.validate().unwrap_err();
19593 assert!(
19594 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19595 if reason.contains('_')),
19596 "got {err:?}"
19597 );
19598 }
19599
19600 #[test]
19601 fn rejects_entrada_host_ipv4_literal() {
19602 // Gateway API v1 explicitly forbids IP literals as Hostnames.
19603 let mut s = three_member_spec();
19604 s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
19605 let err = s.validate().unwrap_err();
19606 assert!(
19607 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19608 if reason.contains("IPv4")),
19609 "got {err:?}"
19610 );
19611 }
19612
19613 #[test]
19614 fn rejects_entrada_host_with_trailing_dot() {
19615 // The Gateway API regex anchors at end-of-string with no
19616 // trailing `.` allowance — the FQDN root-dot form is rejected.
19617 let mut s = three_member_spec();
19618 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
19619 let err = s.validate().unwrap_err();
19620 assert!(
19621 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
19622 if host == "checkout.quero.cloud."),
19623 "got {err:?}"
19624 );
19625 }
19626
19627 #[test]
19628 fn rejects_entrada_host_with_leading_dot() {
19629 let mut s = three_member_spec();
19630 s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
19631 let err = s.validate().unwrap_err();
19632 assert!(
19633 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19634 if reason.contains("empty label")),
19635 "got {err:?}"
19636 );
19637 }
19638
19639 #[test]
19640 fn rejects_entrada_host_with_consecutive_dots() {
19641 let mut s = three_member_spec();
19642 s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
19643 let err = s.validate().unwrap_err();
19644 assert!(
19645 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19646 if reason.contains("empty label")),
19647 "got {err:?}"
19648 );
19649 }
19650
19651 #[test]
19652 fn rejects_entrada_host_with_leading_hyphen_label() {
19653 let mut s = three_member_spec();
19654 s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
19655 let err = s.validate().unwrap_err();
19656 assert!(
19657 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19658 if reason.contains("alphanumeric")),
19659 "got {err:?}"
19660 );
19661 }
19662
19663 #[test]
19664 fn rejects_entrada_host_with_trailing_hyphen_label() {
19665 let mut s = three_member_spec();
19666 s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
19667 let err = s.validate().unwrap_err();
19668 assert!(
19669 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19670 if reason.contains("alphanumeric")),
19671 "got {err:?}"
19672 );
19673 }
19674
19675 #[test]
19676 fn rejects_entrada_host_with_inner_wildcard() {
19677 // Gateway API allows `*` only as the first label (`*.foo`);
19678 // any inner or trailing `*` is rejected.
19679 let mut s = three_member_spec();
19680 s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
19681 let err = s.validate().unwrap_err();
19682 assert!(
19683 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19684 if reason.contains("wildcard")),
19685 "got {err:?}"
19686 );
19687 }
19688
19689 #[test]
19690 fn rejects_entrada_host_bare_wildcard() {
19691 // `*.` with no domain is meaningless; Gateway API rejects it.
19692 let mut s = three_member_spec();
19693 s.entrada.as_mut().unwrap().host = "*.".into();
19694 let err = s.validate().unwrap_err();
19695 assert!(
19696 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19697 if reason.contains("wildcard")),
19698 "got {err:?}"
19699 );
19700 }
19701
19702 #[test]
19703 fn rejects_entrada_host_with_whitespace() {
19704 let mut s = three_member_spec();
19705 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
19706 let err = s.validate().unwrap_err();
19707 assert!(
19708 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19709 if reason.contains("whitespace")),
19710 "got {err:?}"
19711 );
19712 }
19713
19714 #[test]
19715 fn rejects_entrada_host_space_names_offending_byte() {
19716 // Embedded space in the `:entrada :host` axis surfaces the
19717 // byte-naming diagnostic through the lifted
19718 // `find_ascii_whitespace_byte` predicate. Peer with the
19719 // sibling `parse_rejects_leading_whitespace` pins on
19720 // `supervisor::duration_codec` (a7ae622) — same "the
19721 // diagnostic carries the offending byte's `0x{b:02x}` shape"
19722 // discipline extended from the shared duration codec to the
19723 // Gateway API v1 Hostname axis.
19724 let mut s = three_member_spec();
19725 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
19726 let err = s.validate().unwrap_err();
19727 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
19728 panic!("expected EntradaHostInvalid, got {err:?}");
19729 };
19730 assert!(
19731 reason.contains("ASCII whitespace byte"),
19732 "expected byte-naming diagnostic, got {reason:?}"
19733 );
19734 assert!(
19735 reason.contains("0x20"),
19736 "expected offending space byte 0x20, got {reason:?}"
19737 );
19738 }
19739
19740 #[test]
19741 fn rejects_entrada_host_tab_names_offending_byte() {
19742 // Embedded tab byte in the `:entrada :host` axis — the
19743 // canonical paste-from-YAML-block-scalar / paste-from-
19744 // indented-doc footgun. Pins that the lifted predicate covers
19745 // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
19746 // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
19747 // not just the leading-space case the pre-lift `.bytes().any`
19748 // arm's opaque "must not contain whitespace" reason already
19749 // covered. Peer with `parse_rejects_tab_byte` on
19750 // `supervisor::duration_codec` (a7ae622).
19751 let mut s = three_member_spec();
19752 s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
19753 let err = s.validate().unwrap_err();
19754 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
19755 panic!("expected EntradaHostInvalid, got {err:?}");
19756 };
19757 assert!(
19758 reason.contains("ASCII whitespace byte"),
19759 "expected byte-naming diagnostic, got {reason:?}"
19760 );
19761 assert!(
19762 reason.contains("0x09"),
19763 "expected offending tab byte 0x09, got {reason:?}"
19764 );
19765 }
19766
19767 #[test]
19768 fn rejects_entrada_host_lf_names_offending_byte() {
19769 // Embedded LF byte in the `:entrada :host` axis — the
19770 // canonical paste-from-shell-heredoc / paste-from-multiline-
19771 // doc footgun the caixa-mesh YAML emitter would silently
19772 // reinterpret at the Gateway API v1 HTTPRoute admission
19773 // layer (an embedded LF byte in a YAML plain scalar either
19774 // truncates the value at the emitter or crashes the parser
19775 // on the k8s-apiserver side). Pins the third representative
19776 // of the full ASCII-whitespace set through the shared
19777 // predicate.
19778 let mut s = three_member_spec();
19779 s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
19780 let err = s.validate().unwrap_err();
19781 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
19782 panic!("expected EntradaHostInvalid, got {err:?}");
19783 };
19784 assert!(
19785 reason.contains("ASCII whitespace byte"),
19786 "expected byte-naming diagnostic, got {reason:?}"
19787 );
19788 assert!(
19789 reason.contains("0x0a"),
19790 "expected offending LF byte 0x0a, got {reason:?}"
19791 );
19792 }
19793
19794 #[test]
19795 fn rejects_entrada_host_nbsp_names_offending_codepoint() {
19796 // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
19797 // axis — the canonical paste-from-typography /
19798 // paste-from-word-processor footgun. Before the non-ASCII
19799 // Unicode `White_Space` scan lifted through the shared
19800 // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
19801 // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
19802 // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
19803 // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
19804 // with the far-from-source `label "…" must start and end
19805 // with an alphanumeric` diagnostic — burying the
19806 // paste-from-typography origin under a label-shape leak.
19807 // Peer with the sibling non-ASCII-whitespace pins at
19808 // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
19809 // — 1b75b38), `limits::parse_duration`,
19810 // `limits::parse_millicores`, and the shared duration codec
19811 // — same "the diagnostic carries the offending Unicode
19812 // codepoint's `U+XXXX` shape" discipline extended from every
19813 // typed-magnitude codec to the Gateway API v1 Hostname axis.
19814 let mut s = three_member_spec();
19815 s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
19816 let err = s.validate().unwrap_err();
19817 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
19818 panic!("expected EntradaHostInvalid, got {err:?}");
19819 };
19820 assert!(
19821 reason.contains("non-ASCII Unicode whitespace character"),
19822 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
19823 );
19824 assert!(
19825 reason.contains("U+00A0"),
19826 "expected offending NBSP codepoint U+00A0, got {reason:?}"
19827 );
19828 }
19829
19830 #[test]
19831 fn rejects_entrada_host_line_separator_names_offending_codepoint() {
19832 // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
19833 // `:entrada :host` axis — the canonical paste-from-web-doc /
19834 // paste-from-published-HTML footgun. `char::is_whitespace`
19835 // returns true for `U+2028` per the Unicode `White_Space`
19836 // property, so `str::trim` at any downstream site would
19837 // silently strip it — same drift class as NBSP but on a
19838 // different codepoint region. Pins the second representative
19839 // (non-Latin-1 `char::is_whitespace` member) through the
19840 // shared predicate. Peer with
19841 // `parse_byte_size_rejects_internal_line_separator` on
19842 // `limits::parse_byte_size` (1b75b38).
19843 let mut s = three_member_spec();
19844 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
19845 let err = s.validate().unwrap_err();
19846 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
19847 panic!("expected EntradaHostInvalid, got {err:?}");
19848 };
19849 assert!(
19850 reason.contains("non-ASCII Unicode whitespace character"),
19851 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
19852 );
19853 assert!(
19854 reason.contains("U+2028"),
19855 "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
19856 );
19857 }
19858
19859 #[test]
19860 fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
19861 // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
19862 // labels in the `:entrada :host` axis — the canonical
19863 // paste-from-CJK-typography footgun (CJK IMEs default to
19864 // full-width whitespace when the space bar is pressed in
19865 // Japanese / Chinese input modes). Pins the third
19866 // representative of the non-ASCII Unicode `White_Space` set
19867 // through the shared predicate: the CJK block, distinct from
19868 // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
19869 // SEPARATOR `U+2028` — covering the same axis breadth the
19870 // sibling `parse_byte_size_rejects_trailing_ideographic_space`
19871 // (1b75b38) pins on `limits::parse_byte_size`.
19872 let mut s = three_member_spec();
19873 s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
19874 let err = s.validate().unwrap_err();
19875 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
19876 panic!("expected EntradaHostInvalid, got {err:?}");
19877 };
19878 assert!(
19879 reason.contains("non-ASCII Unicode whitespace character"),
19880 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
19881 );
19882 assert!(
19883 reason.contains("U+3000"),
19884 "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
19885 );
19886 }
19887
19888 #[test]
19889 fn rejects_entrada_host_too_long() {
19890 // Total length cap = 253; build a 254-byte host out of two
19891 // 63-byte labels + one 62-byte label + dots.
19892 let mut s = three_member_spec();
19893 let big = format!(
19894 "{}.{}.{}.{}",
19895 "a".repeat(63),
19896 "b".repeat(63),
19897 "c".repeat(63),
19898 "d".repeat(254 - 63 * 3 - 3)
19899 );
19900 assert_eq!(big.len(), 254);
19901 s.entrada.as_mut().unwrap().host = big;
19902 let err = s.validate().unwrap_err();
19903 assert!(
19904 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19905 if reason.contains("max length of 253")),
19906 "got {err:?}"
19907 );
19908 }
19909
19910 #[test]
19911 fn rejects_entrada_host_label_too_long() {
19912 let mut s = three_member_spec();
19913 // 64-byte label — one over the per-label cap.
19914 s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
19915 let err = s.validate().unwrap_err();
19916 assert!(
19917 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
19918 if reason.contains("label max length of 63")),
19919 "got {err:?}"
19920 );
19921 }
19922
19923 #[test]
19924 fn entrada_host_diagnostic_carries_offending_host() {
19925 // Diagnostic-shape pin — the offending host + a non-empty
19926 // reason flow through verbatim so the author can grep their
19927 // caixa.lisp for `:host "<host>"` and fix it in one edit.
19928 let mut s = three_member_spec();
19929 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
19930 let err = s.validate().unwrap_err();
19931 match err {
19932 AplicacaoError::EntradaHostInvalid { host, reason } => {
19933 assert_eq!(host, "checkout.quero.cloud:8080");
19934 assert!(!reason.is_empty(), "reason field must be non-empty");
19935 }
19936 other => panic!("expected EntradaHostInvalid, got {other:?}"),
19937 }
19938 }
19939
19940 // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
19941 // substrate primitive that folds the fourteen
19942 // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
19943 // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
19944 // one dispatch — peer with the sixteen equivalence pins the
19945 // [`crate::LayoutError`] `_violation` constructor family carries in
19946 // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
19947 // fixture host + reason are fixed `&'static str`s so both fields of
19948 // both constructed variants pin verbatim: the `host` axis is pinned
19949 // through the shared `host.to_string()` wrap (the ctor's uniform
19950 // one-slot construction) and the `reason` axis is pinned through
19951 // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
19952 // routing). Any future regression on the lift (an extra field
19953 // introduced without updating the ctor, a diverging string
19954 // conversion at either arm) surfaces at this pin's diagnostic
19955 // rather than at a per-wire-up struct-literal reintroduction.
19956 #[test]
19957 fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
19958 let host = "checkout.quero.cloud:8080";
19959 let reason = "sample reason text";
19960 assert_eq!(
19961 AplicacaoError::entrada_host_invalid(host, reason),
19962 AplicacaoError::EntradaHostInvalid {
19963 host: host.to_string(),
19964 reason: reason.to_string(),
19965 },
19966 "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
19967 );
19968 }
19969
19970 // Routing pin — the ctor's `host: &str` argument threads through
19971 // `.to_string()` verbatim on the `host` field, so the constructed
19972 // variant carries the offending host bytes without any wrapper-
19973 // side transformation (no `.to_ascii_lowercase()` normalization,
19974 // no `.trim()` strip, no truncation) — the same "diagnostic carries
19975 // the offending value verbatim so the author can grep their
19976 // caixa.lisp" discipline every peer typed-slot ctor at this
19977 // altitude carries.
19978 #[test]
19979 fn entrada_host_invalid_ctor_routes_host_through_to_string() {
19980 // Uppercase + trailing whitespace + port suffix — three
19981 // wrapper-side transformations the ctor must *not* apply.
19982 let host = " Checkout.quero.CLOUD:8080 ";
19983 let err = AplicacaoError::entrada_host_invalid(host, "sample");
19984 match err {
19985 AplicacaoError::EntradaHostInvalid { host: h, .. } => {
19986 assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
19987 }
19988 other => panic!("expected EntradaHostInvalid, got {other:?}"),
19989 }
19990 }
19991
19992 // Routing pin — the ctor's `reason: impl Into<String>` accepts both
19993 // `&str` literals and `format!(…)` outputs identically and both
19994 // route through `Into::into` verbatim onto the `reason` field.
19995 // Pins both codepaths against the same host to prove the two
19996 // shapes the fourteen wire-up sites use at their per-arm diagnostic
19997 // (ten `&str` literals — some with `.to_string()` at the caller,
19998 // some without — plus four `format!(…)` outputs) each produce
19999 // byte-equal `reason` fields against the same offending host.
20000 #[test]
20001 fn entrada_host_invalid_ctor_routes_reason_through_into() {
20002 let host = "checkout.quero.cloud";
20003 // `&str` literal — the ctor's `impl Into<String>` accepts it
20004 // without a caller-side `.to_string()`.
20005 let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
20006 // Owned `String` from `format!` — the peer `format!(…)`-shaped
20007 // wire-up arm.
20008 let from_format =
20009 AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
20010 // `String` from `.to_string()` on a literal — the peer
20011 // `"literal".to_string()`-shaped wire-up arm the pre-lift
20012 // sites carried.
20013 let from_to_string =
20014 AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
20015 match (&from_literal, &from_format, &from_to_string) {
20016 (
20017 AplicacaoError::EntradaHostInvalid {
20018 reason: r_lit,
20019 host: h_lit,
20020 },
20021 AplicacaoError::EntradaHostInvalid {
20022 reason: r_fmt,
20023 host: h_fmt,
20024 },
20025 AplicacaoError::EntradaHostInvalid {
20026 reason: r_ts,
20027 host: h_ts,
20028 },
20029 ) => {
20030 assert_eq!(r_lit, "literal reason text");
20031 assert_eq!(r_fmt, "literal reason text");
20032 assert_eq!(r_ts, "literal reason text");
20033 assert_eq!(h_lit, host);
20034 assert_eq!(h_fmt, host);
20035 assert_eq!(h_ts, host);
20036 }
20037 _ => panic!("expected three EntradaHostInvalid variants"),
20038 }
20039 // Cross-arm equivalence — the three shapes must produce
20040 // byte-equal `AplicacaoError` values, so the fourteen wire-up
20041 // sites' mixed per-arm shapes fold onto one canonical form.
20042 assert_eq!(from_literal, from_format);
20043 assert_eq!(from_literal, from_to_string);
20044 }
20045
20046 // Equivalence pins for the six sibling
20047 // [`aplicacao_field_reason_ctors!`]-generated constructors that
20048 // fold the peer `{ <field>: String, reason: String }` variants
20049 // onto the same substrate-primitive family
20050 // `entrada_host_invalid` (17dd504) already carries pins for.
20051 // Each ctor's fixture pair (a fixed `&'static str` value and a
20052 // fixed `&'static str` reason) pins both fields verbatim so any
20053 // future regression on the macro (an extra field introduced
20054 // without updating the macro, a diverging string conversion at
20055 // either arm, a field-name typo on one variant that dropped it
20056 // off the shared shape) surfaces at the affected variant's pin
20057 // rather than at a per-wire-up struct-literal reintroduction. Peer
20058 // discipline of the sixteen `LayoutError` _violation ctor pins in
20059 // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
20060 // and the paired
20061 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
20062 // `contrato_missing_target_ctor_matches_struct_literal_wrap`
20063 // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
20064 // (8580068) equivalence pins on the sibling `AplicacaoError`
20065 // ctor macros.
20066 #[test]
20067 fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
20068 let caixa = "cart-svc";
20069 let reason = "sample reason text";
20070 assert_eq!(
20071 AplicacaoError::membro_caixa_invalid(caixa, reason),
20072 AplicacaoError::MembroCaixaInvalid {
20073 caixa: caixa.to_string(),
20074 reason: reason.to_string(),
20075 },
20076 );
20077 }
20078
20079 #[test]
20080 fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
20081 let para = "checkout";
20082 let reason = "sample reason text";
20083 assert_eq!(
20084 AplicacaoError::entrada_para_invalid(para, reason),
20085 AplicacaoError::EntradaParaInvalid {
20086 para: para.to_string(),
20087 reason: reason.to_string(),
20088 },
20089 );
20090 }
20091
20092 #[test]
20093 fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
20094 let path = "/api/cart";
20095 let reason = "sample reason text";
20096 assert_eq!(
20097 AplicacaoError::entrada_path_invalid(path, reason),
20098 AplicacaoError::EntradaPathInvalid {
20099 path: path.to_string(),
20100 reason: reason.to_string(),
20101 },
20102 );
20103 }
20104
20105 #[test]
20106 fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
20107 let cluster = "rio";
20108 let reason = "sample reason text";
20109 assert_eq!(
20110 AplicacaoError::placement_cluster_invalid(cluster, reason),
20111 AplicacaoError::PlacementClusterInvalid {
20112 cluster: cluster.to_string(),
20113 reason: reason.to_string(),
20114 },
20115 );
20116 }
20117
20118 #[test]
20119 fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
20120 let affinity = "data-locality";
20121 let reason = "sample reason text";
20122 assert_eq!(
20123 AplicacaoError::placement_affinity_invalid(affinity, reason),
20124 AplicacaoError::PlacementAffinityInvalid {
20125 affinity: affinity.to_string(),
20126 reason: reason.to_string(),
20127 },
20128 );
20129 }
20130
20131 #[test]
20132 fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
20133 let shard_key = "tenantId";
20134 let reason = "sample reason text";
20135 assert_eq!(
20136 AplicacaoError::shard_key_invalid(shard_key, reason),
20137 AplicacaoError::ShardKeyInvalid {
20138 shard_key: shard_key.to_string(),
20139 reason: reason.to_string(),
20140 },
20141 );
20142 }
20143
20144 // Pin the three-slot per-`:contratos <slot>` sibling of the
20145 // two-slot `aplicacao_field_reason_ctors!` family — the sole
20146 // per-axis ctor carrying the extra `slot: &'static str` axis-tag
20147 // distinguishing the two-arm `:de` / `:para` cascade. Sweeps both
20148 // canonical author-side slot tags through the ctor and asserts
20149 // byte-equality against the pre-lift struct-literal shape so no
20150 // per-arm wrapper transformation drifts in against the sole
20151 // in-crate wire-up.
20152 #[test]
20153 fn contrato_caixa_invalid_ctor_matches_struct_literal_wrap() {
20154 let caixa = "cart-svc";
20155 let reason = "sample reason text";
20156 for slot in [
20157 crate::render::CONTRATO_AUTHOR_KEY_DE,
20158 crate::render::CONTRATO_AUTHOR_KEY_PARA,
20159 ] {
20160 assert_eq!(
20161 AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
20162 AplicacaoError::ContratoCaixaInvalid {
20163 slot,
20164 caixa: caixa.to_string(),
20165 reason: reason.to_string(),
20166 },
20167 );
20168 }
20169 }
20170
20171 // The `reason: impl Into<String>` bound accepts both a `&str`
20172 // literal and a `format!(…)` owned-`String` output verbatim,
20173 // matching the peer `aplicacao_field_reason_ctors!` family's
20174 // reason-axis invariance so the sole in-crate wire-up's
20175 // `require_valid_dns_1123_label`-delivered owned-`String` return
20176 // and any future `&str` literal caller land on the same variant.
20177 #[test]
20178 fn contrato_caixa_invalid_ctor_routes_reason_through_into_uniformly() {
20179 let via_literal = "literal reason text";
20180 let via_format = format!("{} reason text", "literal");
20181 for slot in [
20182 crate::render::CONTRATO_AUTHOR_KEY_DE,
20183 crate::render::CONTRATO_AUTHOR_KEY_PARA,
20184 ] {
20185 assert_eq!(
20186 AplicacaoError::contrato_caixa_invalid(slot, "c", via_literal),
20187 AplicacaoError::contrato_caixa_invalid(slot, "c", via_format.clone()),
20188 );
20189 }
20190 }
20191
20192 // Pin the paired one-slot empty-arm sibling of the three-slot
20193 // `contrato_caixa_invalid` per-`:contratos <slot>` ctor — the sole
20194 // closure-form empty-arm on the shared
20195 // [`crate::render::require_valid_dns_1123_label`] two-closure
20196 // cascade at [`validate_contrato_caixa`], carrying the same
20197 // `slot: &'static str` axis-tag that distinguishes the two-arm
20198 // `:de` / `:para` cascade. Sweeps both canonical author-side slot
20199 // tags through the ctor and asserts byte-equality against the
20200 // pre-lift struct-literal shape so no per-arm wrapper transformation
20201 // drifts in against the sole in-crate wire-up. Peer of the sibling
20202 // [`crate::behavior::BehaviorError::empty_path`] one-slot
20203 // `{ slot: &'static str }` equivalence pin on the paired
20204 // `BehaviorError` envelope's four-arm sandboxed-lisp-path cascade
20205 // ([`crate::render::require_sandboxed_lisp_path`]) — extended here
20206 // onto the sibling `AplicacaoError` envelope's two-arm
20207 // DNS-1123-label cascade so both empty-arm axes carry a
20208 // substrate-primitive equivalence pin rather than the pre-lift
20209 // hand-open struct-literal.
20210 #[test]
20211 fn contrato_caixa_empty_ctor_matches_struct_literal_wrap() {
20212 for slot in [
20213 crate::render::CONTRATO_AUTHOR_KEY_DE,
20214 crate::render::CONTRATO_AUTHOR_KEY_PARA,
20215 ] {
20216 assert_eq!(
20217 AplicacaoError::contrato_caixa_empty(slot),
20218 AplicacaoError::ContratoCaixaEmpty { slot },
20219 "generated contrato_caixa_empty ctor must produce \
20220 byte-equal AplicacaoError to the open-coded \
20221 struct-literal wrap on the same &'static str fixture \
20222 (slot = {slot:?})",
20223 );
20224 }
20225 }
20226
20227 // Cross-axis pin: sweep the constructor's single input axis (`slot:
20228 // &'static str`) through every canonical
20229 // [`crate::render::CONTRATO_AUTHOR_KEY_*`] tag *plus* a non-canonical
20230 // `&'static str` value (`":phantom"`), so any wrapper-side lowercase
20231 // / trim / truncate / re-order / fixed-slot substitution on the
20232 // one-field construction surfaces here rather than at a downstream
20233 // diagnostic-shape mismatch. The non-canonical arm proves the
20234 // constructor does not silently clamp `slot` to the `:de` /
20235 // `:para` roster (a future third `:contratos <slot>` axis lands on
20236 // this ctor without a per-arm rewrite), matching the discipline the
20237 // sibling [`Self::contrato_caixa_invalid`] ctor's tri-slot sweep
20238 // establishes at
20239 // `contrato_caixa_invalid_ctor_matches_struct_literal_wrap`
20240 // (18114) on the paired three-slot invalid-arm envelope.
20241 #[test]
20242 fn contrato_caixa_empty_ctor_routes_slot_verbatim_across_both_axes() {
20243 for slot in [
20244 crate::render::CONTRATO_AUTHOR_KEY_DE,
20245 crate::render::CONTRATO_AUTHOR_KEY_PARA,
20246 ":phantom",
20247 ] {
20248 assert_eq!(
20249 AplicacaoError::contrato_caixa_empty(slot),
20250 AplicacaoError::ContratoCaixaEmpty { slot },
20251 );
20252 }
20253 }
20254
20255 // End-to-end wire-up pin: `AplicacaoSpec::validate` on an empty
20256 // `:contratos :de` value must surface a diagnostic byte-equal to
20257 // the substrate primitive `AplicacaoError::contrato_caixa_empty`'s
20258 // output on the same slot fixture. Proves the sole in-crate
20259 // closure-form wire-up inside [`validate_contrato_caixa`]'s
20260 // [`crate::render::require_valid_dns_1123_label`] empty-arm routes
20261 // through the ctor rather than the pre-lift open-coded
20262 // struct-literal block, matching the sibling per-arm
20263 // `end_to_end_wire_up_routes_through_ctor` discipline the peer
20264 // per-envelope ctor pins the recent
20265 // [`Self::policy_rate_limit_cannot_admit_retry_burst`] (9703bd6),
20266 // [`Self::policy_breaker_trips_before_retries_exhausted`] (f54c539),
20267 // [`Self::policy_breaker_cannot_trip_under_rate_limit`] (6bb4e46),
20268 // and [`Self::policy_breaker_window_below_timeout`] (9b30c07)
20269 // cross-axis Policy* variants carry. Complements the two axis-tag
20270 // arms already pinned above the `:contratos` value-shape gate
20271 // block (`rejects_contrato_de_empty`, `rejects_contrato_para_empty`)
20272 // which anchor via the shape; this pin additionally verifies the
20273 // ctor is the exclusive construction path.
20274 #[test]
20275 fn contrato_caixa_empty_end_to_end_wire_up_routes_through_ctor() {
20276 // Empty `:de` — the sole in-crate wire-up hits the empty-arm
20277 // closure at the first `:contratos` value-shape gate, threading
20278 // the `CONTRATO_AUTHOR_KEY_DE` label through the ctor.
20279 let mut s_de = three_member_spec();
20280 s_de.contratos.push(contract_http("", "catalog", "/x"));
20281 assert_eq!(
20282 s_de.validate().unwrap_err(),
20283 AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_DE),
20284 );
20285 // Symmetric arm: an empty `:para` on a valid `:de` fires the
20286 // same closure with the `CONTRATO_AUTHOR_KEY_PARA` label.
20287 let mut s_para = three_member_spec();
20288 s_para.contratos.push(contract_http("cart", "", "/x"));
20289 assert_eq!(
20290 s_para.validate().unwrap_err(),
20291 AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_PARA),
20292 );
20293 }
20294
20295 // Cross-family invariance pin — the six sibling ctors and
20296 // `entrada_host_invalid` all route `reason: impl Into<String>` +
20297 // `<field>: &str` verbatim onto their respective typed variants
20298 // through the shared [`aplicacao_field_reason_ctors!`] macro.
20299 // Sweeps a fixture pair (`&str` literal, `format!` output) against
20300 // every ctor to pin that no per-arm wrapper transformation drifted
20301 // in against the uniform macro-generated body.
20302 #[test]
20303 fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
20304 let via_literal = "literal reason text";
20305 let via_format = format!("{} reason text", "literal");
20306 assert_eq!(
20307 AplicacaoError::membro_caixa_invalid("m", via_literal),
20308 AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
20309 );
20310 assert_eq!(
20311 AplicacaoError::entrada_para_invalid("p", via_literal),
20312 AplicacaoError::entrada_para_invalid("p", via_format.clone()),
20313 );
20314 assert_eq!(
20315 AplicacaoError::entrada_path_invalid("/a", via_literal),
20316 AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
20317 );
20318 assert_eq!(
20319 AplicacaoError::placement_cluster_invalid("c", via_literal),
20320 AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
20321 );
20322 assert_eq!(
20323 AplicacaoError::placement_affinity_invalid("a", via_literal),
20324 AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
20325 );
20326 assert_eq!(
20327 AplicacaoError::shard_key_invalid("k", via_literal),
20328 AplicacaoError::shard_key_invalid("k", via_format.clone()),
20329 );
20330 assert_eq!(
20331 AplicacaoError::entrada_host_invalid("h", via_literal),
20332 AplicacaoError::entrada_host_invalid("h", via_format),
20333 );
20334 }
20335
20336 #[test]
20337 fn entrada_host_empty_takes_precedence_over_invalid() {
20338 // Ordering pin: `EmptyEntradaHost` is the more self-locating
20339 // diagnostic on `""` and must lead — `validate_entrada_host`
20340 // is only reached after the empty-check fires at the call
20341 // site. (The predicate itself defends against direct
20342 // invocation by returning the same error on `""`.)
20343 let mut s = three_member_spec();
20344 s.entrada.as_mut().unwrap().host = String::new();
20345 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
20346 }
20347
20348 #[test]
20349 fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
20350 // Ordering pin: a missing :para member is the more
20351 // self-locating diagnostic and fires before the host gate.
20352 let mut s = three_member_spec();
20353 let e = s.entrada.as_mut().unwrap();
20354 e.para = "ghost".into();
20355 e.host = "BAD HOST".into();
20356 let err = s.validate().unwrap_err();
20357 assert!(
20358 matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
20359 "got {err:?}"
20360 );
20361 }
20362
20363 #[test]
20364 fn entrada_host_invalid_fires_before_port_zero() {
20365 // Ordering pin: the host gate fires before the port gate so
20366 // a malformed host is named even when the port is also wrong.
20367 let mut s = three_member_spec();
20368 let e = s.entrada.as_mut().unwrap();
20369 e.host = "Checkout.quero.cloud".into();
20370 e.port = 0;
20371 let err = s.validate().unwrap_err();
20372 assert!(
20373 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
20374 if host == "Checkout.quero.cloud"),
20375 "got {err:?}"
20376 );
20377 }
20378
20379 #[test]
20380 fn entrada_accepts_canonical_hosts() {
20381 // Positive-control sweep — every form the Gateway API
20382 // apiserver accepts must round-trip through validate. Covers
20383 // a plain DNS subdomain, a leading wildcard, a single-label
20384 // host (cluster-internal), a max-length-edge label, a
20385 // hyphen-bearing label, and a Punycode IDN label.
20386 for host in [
20387 "checkout.quero.cloud",
20388 "*.quero.cloud",
20389 "checkout",
20390 // 63-byte label — exactly the per-label cap.
20391 "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
20392 "foo-bar.quero.cloud",
20393 // Punycode IDN — valid because the author pre-encoded.
20394 "xn--bcher-kva.example.com",
20395 ] {
20396 let mut s = three_member_spec();
20397 s.entrada.as_mut().unwrap().host = host.into();
20398 s.validate()
20399 .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
20400 }
20401 }
20402
20403 #[test]
20404 fn entrada_host_max_length_validates() {
20405 // 253-byte host is the cap exactly — must validate. Build a
20406 // 253-byte host out of three 63-byte labels + one 61-byte
20407 // label + 3 dots = 252 bytes, then pad one byte to 253.
20408 let mut s = three_member_spec();
20409 let host = format!(
20410 "{}.{}.{}.{}",
20411 "a".repeat(63),
20412 "b".repeat(63),
20413 "c".repeat(63),
20414 "d".repeat(253 - 63 * 3 - 3)
20415 );
20416 assert_eq!(host.len(), 253);
20417 s.entrada.as_mut().unwrap().host = host;
20418 s.validate().unwrap();
20419 }
20420
20421 #[test]
20422 fn entrada_host_total_length_cap_threads_lifted_render_const() {
20423 // Cross-crate-side pin: the aplicacao-side `:entrada :host`
20424 // total-length gate now reads the K8s Gateway API v1 Hostname
20425 // `maxLength: 253` cap from the lifted
20426 // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
20427 // of truth — the same constant every future Gateway-API-Hostname
20428 // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
20429 // materializer's per-host validator, the future per-`Certificate`
20430 // SAN emitter for cert-manager, the multi-`:entrada`
20431 // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
20432 // from. Before the lift, the aplicacao-side reader consumed a
20433 // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
20434 // 253-byte value as the peer render-side canonical bounds
20435 // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
20436 // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
20437 // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
20438 // module boundary — a future 253-byte drift on either side would
20439 // silently split into two axes' worth of admission-schema mismatch
20440 // without a build-time signal. Pin the cap through a fresh 254-
20441 // byte host that hits the total-length arm, then read the reason
20442 // for the exact byte count the shared constant carries: any future
20443 // regression on the lift (a private alias reintroduced, a hard-
20444 // coded literal at the arm, a mismatch between the aplicacao-side
20445 // and render-side canonicals) surfaces as this pin's diagnostic
20446 // failing to match, not as a per-cluster admission rejection far
20447 // from the caixa.lisp source line.
20448 let mut s = three_member_spec();
20449 let over_cap = format!(
20450 "{}.{}.{}.{}",
20451 "a".repeat(63),
20452 "b".repeat(63),
20453 "c".repeat(63),
20454 "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
20455 );
20456 assert_eq!(
20457 over_cap.len(),
20458 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
20459 );
20460 s.entrada.as_mut().unwrap().host = over_cap;
20461 let err = s.validate().unwrap_err();
20462 match err {
20463 AplicacaoError::EntradaHostInvalid { reason, .. } => {
20464 let needle = format!(
20465 "max length of {} bytes",
20466 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
20467 );
20468 assert!(
20469 reason.contains(&needle),
20470 "diagnostic must name the lifted \
20471 GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
20472 );
20473 }
20474 other => panic!("expected EntradaHostInvalid, got {other:?}"),
20475 }
20476 }
20477
20478 #[test]
20479 fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
20480 // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
20481 // on the per-label-cap axis. Before the lift, the aplicacao-side
20482 // per-label arm consumed a private const alias
20483 // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
20484 // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
20485 // split from it at the module boundary — every `.`-separated
20486 // label in a Gateway API v1 Hostname is a DNS-1123 label under
20487 // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
20488 // so the private alias's 63 and the canonical const's 63 were
20489 // pinning the same underlying rule twice. Pin the cap through a
20490 // 64-byte label that hits the per-label arm, then read the reason
20491 // for the exact byte count the shared constant carries: any
20492 // future drift on either side (a private alias reintroduced, a
20493 // hard-coded literal at the arm, a mismatch between the two
20494 // 63-byte pins) surfaces at this pin's diagnostic rather than at
20495 // a per-cluster admission rejection whose "field is invalid"
20496 // opacity misframes the root cause.
20497 let mut s = three_member_spec();
20498 let over_cap_label = format!(
20499 "{}.quero.cloud",
20500 "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
20501 );
20502 s.entrada.as_mut().unwrap().host = over_cap_label;
20503 let err = s.validate().unwrap_err();
20504 match err {
20505 AplicacaoError::EntradaHostInvalid { reason, .. } => {
20506 let needle = format!(
20507 "label max length of {} bytes",
20508 crate::render::DNS_1123_LABEL_MAX_LEN,
20509 );
20510 assert!(
20511 reason.contains(&needle),
20512 "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
20513 cap verbatim on the per-label arm, got: {reason:?}",
20514 );
20515 }
20516 other => panic!("expected EntradaHostInvalid, got {other:?}"),
20517 }
20518 }
20519
20520 #[test]
20521 fn entrada_with_empty_paths_validates() {
20522 // Empty `:paths` is the documented "match every path" form;
20523 // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
20524 let mut s = three_member_spec();
20525 s.entrada.as_mut().unwrap().paths = vec![];
20526 s.validate().unwrap();
20527 }
20528
20529 #[test]
20530 fn entrada_root_path_validates() {
20531 // The author-supplied bare-root `:entrada :paths` entry is the
20532 // same byte-shape the peer emit-side catch-all constant
20533 // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
20534 // the author's `:paths` list is empty — sweeping the test-side
20535 // probe literal onto the lifted const closes the two-axis pin
20536 // (author-side admit + emit-side canonical fallback) around
20537 // one `&'static str`, so a future rebrand of the catch-all
20538 // reaches both consumers by construction. Peer to
20539 // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
20540 // on the canonical-literal pin surface.
20541 let mut s = three_member_spec();
20542 s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
20543 s.validate().unwrap();
20544 }
20545
20546 #[test]
20547 fn placement_strategy_variants_round_trip() {
20548 for s in [
20549 PlacementStrategy::SingleNode,
20550 PlacementStrategy::Replicated,
20551 PlacementStrategy::Sharded,
20552 ] {
20553 let p = Placement {
20554 estrategia: s,
20555 clusters: vec!["rio".into()],
20556 affinity: None,
20557 // Route the paired `:shard-key` fixture-builder through the
20558 // typed cross-slot invariant predicate
20559 // [`PlacementStrategy::requires_shard_key`] rather than the
20560 // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
20561 // arm-identity predicate — the two answer the same
20562 // question under today's closed accept-set but a future
20563 // arm addition that consumed `:shard-key` under a
20564 // non-`Sharded` name would silently mis-attach the
20565 // fixture's `:shard-key` if the builder read through the
20566 // arm-identity predicate. The cross-slot-invariant
20567 // predicate migrates through one caixa-core edit on any
20568 // future arm addition; the fixture keeps producing a
20569 // `validate()`-passing round-trip by construction.
20570 shard_key: if s.requires_shard_key() {
20571 Some("$key".into())
20572 } else {
20573 None
20574 },
20575 };
20576 let json = serde_json::to_string(&p).unwrap();
20577 let back: Placement = serde_json::from_str(&json).unwrap();
20578 assert_eq!(back, p);
20579 }
20580 }
20581
20582 #[test]
20583 fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
20584 // The fail-before-pass-after pin: pre-lift there was no
20585 // single-source binding between the [`PlacementStrategy`]
20586 // variant name the `Serialize` derive emits and the byte-
20587 // string every downstream cluster-side dispatcher (the
20588 // `lareira-fleet-programs` aggregator's per-entry strategy
20589 // branch, the future `app-operator` reconciler, the M3
20590 // Adaptive compression pass's per-strategy weighting) probes
20591 // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
20592 // future `#[serde(rename_all = "kebab-case")]` attribute on
20593 // the enum — or a variant rename in the source — would
20594 // silently rebrand the emitted scalar under one spelling
20595 // while every downstream dispatcher still probed the other,
20596 // with the failure surfacing at the aggregator's dispatch
20597 // step or the operator's reconcile posture (workloads coming
20598 // up under the `default()` `Replicated` arm rather than the
20599 // typed slot's declared strategy) far from the source
20600 // rebrand commit and with no field naming the drift. Pinning
20601 // the two paths (the `Serialize` derive's serialized string
20602 // AND the [`PlacementStrategy::as_str`] helper) to the same
20603 // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
20604 // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
20605 // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
20606 // makes any future drift on either endpoint fail here at
20607 // caixa-core build time.
20608 for (variant, expected) in [
20609 (
20610 PlacementStrategy::SingleNode,
20611 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
20612 ),
20613 (
20614 PlacementStrategy::Replicated,
20615 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
20616 ),
20617 (
20618 PlacementStrategy::Sharded,
20619 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
20620 ),
20621 ] {
20622 let json = serde_json::to_string(&variant).unwrap();
20623 assert_eq!(
20624 json,
20625 format!("\"{expected}\""),
20626 "PlacementStrategy::{variant:?} must serialize to {expected:?}"
20627 );
20628 assert_eq!(
20629 variant.as_str(),
20630 expected,
20631 "PlacementStrategy::{variant:?}.as_str() must return the lifted \
20632 M3_PLACEMENT_ESTRATEGIA_* constant"
20633 );
20634 }
20635 }
20636
20637 #[test]
20638 fn m3_placement_estrategia_consts_are_pairwise_distinct() {
20639 // Cross-arm drift-detection pin on the M3
20640 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
20641 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
20642 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
20643 // scalar-value pentad: a future collapse of two canonical
20644 // variant byte-strings onto the same value (an accidental
20645 // copy-paste flip of
20646 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
20647 // read `"SingleNode"`, a per-arm rebrand that lands one const
20648 // without touching its paired peer) would silently reroute
20649 // every downstream operator's per-strategy dispatch onto the
20650 // sibling arm's reconcile branch and pass every
20651 // propagation-probe test that expected only the stale arm's
20652 // value — a `Replicated`-declared Aplicacao would come up
20653 // under the `SingleNode` primary-and-standby reconcile
20654 // posture, so every-cluster active-active workload would
20655 // silently collapse onto one-cluster-runs-at-a-time takeover
20656 // semantics against its declared strategy, with no field
20657 // naming the strategy-value drift root cause. Peer of the
20658 // sibling
20659 // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
20660 // (09ffb2d) /
20661 // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
20662 // (ccdf955) /
20663 // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
20664 // (d739850) distinctness pins on the sibling OTP-shape /
20665 // caixa-kind closed-set typed-enum discriminator axes — the
20666 // fourth (and structurally the M3 mesh-primitive-defining)
20667 // closed-set typed-enum axis to converge on the same
20668 // "pairwise-distinct-by-construction" discipline.
20669 //
20670 // Fail-before-pass-after locally verified by mutating
20671 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
20672 // also read `"SingleNode"` — this pin fires as expected;
20673 // restoring passes.
20674 let all = [
20675 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
20676 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
20677 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
20678 ];
20679 for (i, a) in all.iter().enumerate() {
20680 for (j, b) in all.iter().enumerate() {
20681 if i != j {
20682 assert_ne!(
20683 a, b,
20684 "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
20685 distinct — got duplicate {a:?} at indices {i} and {j}",
20686 );
20687 }
20688 }
20689 }
20690 }
20691
20692 #[test]
20693 fn placement_strategy_display_routes_through_as_str_helper() {
20694 // The fail-before-pass-after pin: pre-lift the sibling
20695 // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
20696 // / [`crate::supervisor::RestartPolicy`] both carried a stable
20697 // [`std::fmt::Display`] surface via their
20698 // `#[discriminant(also_display)]` gen-platform derive, but
20699 // [`PlacementStrategy`] did not — every consumer reaching for
20700 // a strategy byte-string past the wire format had to pick
20701 // between three paths ([`PlacementStrategy::as_str`], the
20702 // `Serialize` derive's serialized string, or `format!("{v:?}")`
20703 // on the `Debug` derive), any two of which a future variant
20704 // rename or `#[serde(rename_all = "kebab-case")]` attribute
20705 // would silently desynchronize. Wiring [`std::fmt::Display`]
20706 // through [`PlacementStrategy::as_str`] closes the third path:
20707 // every `format!("{v}")` call reaches the same lifted
20708 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
20709 // and the [`PlacementStrategy::as_str`] helper already route
20710 // through, so a future variant rename lands at exactly one
20711 // place. Pin the routing here so a future
20712 // `impl std::fmt::Display for PlacementStrategy` reimplementation
20713 // that hand-rolls the arms instead of delegating to
20714 // [`PlacementStrategy::as_str`] fails at caixa-core build time.
20715 for variant in [
20716 PlacementStrategy::SingleNode,
20717 PlacementStrategy::Replicated,
20718 PlacementStrategy::Sharded,
20719 ] {
20720 assert_eq!(
20721 variant.to_string(),
20722 variant.as_str(),
20723 "PlacementStrategy::{variant:?} Display must route through \
20724 PlacementStrategy::as_str (single source of truth: the lifted \
20725 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
20726 );
20727 }
20728 }
20729
20730 #[test]
20731 fn placement_strategy_display_matches_serialized_wire_byte_string() {
20732 // The fail-before-pass-after pin on the second half of the
20733 // three-path convergence: `Display` (user-facing text) agrees
20734 // byte-for-byte with the `Serialize` derive's wire format
20735 // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
20736 // scalar) on every variant. Pre-lift the two paths were
20737 // structurally independent — a future
20738 // `#[serde(rename_all = "kebab-case")]` attribute on the enum
20739 // would silently rebrand the emitted wire scalar
20740 // (`single-node`, `replicated`, `sharded`) while every consumer
20741 // that pretty-prints the strategy (the M3 diagnostic templates,
20742 // the future `feira app graph` per-Aplicacao strategy line,
20743 // the future M4 CR materializer's admission-webhook rejection
20744 // body) would still emit the TitleCase form the `as_str` /
20745 // `Display` route returns, with the mismatch surfacing at
20746 // consumer parse time / operator dispatch time far from the
20747 // source rebrand commit. Pin the two paths byte-for-byte here
20748 // so any future serde-attribute or variant-rename drift is a
20749 // caixa-core-build-time test failure at this call, not a
20750 // silent per-consumer dispatch miss.
20751 for variant in [
20752 PlacementStrategy::SingleNode,
20753 PlacementStrategy::Replicated,
20754 PlacementStrategy::Sharded,
20755 ] {
20756 let wire = serde_json::to_string(&variant).unwrap();
20757 // Strip the outer `"…"` the JSON string form carries — the
20758 // wire scalar the K8s / YAML apiserver consumes is the
20759 // enclosed byte-string, not the quote wrapper.
20760 let unquoted = wire
20761 .strip_prefix('"')
20762 .and_then(|s| s.strip_suffix('"'))
20763 .expect("serialized PlacementStrategy is a JSON string");
20764 assert_eq!(
20765 variant.to_string(),
20766 unquoted,
20767 "PlacementStrategy::{variant:?} Display byte-string must match the \
20768 Serialize derive's wire byte-string (three-path convergence: \
20769 Display + as_str + Serialize all resolve to the same \
20770 M3_PLACEMENT_ESTRATEGIA_* const)"
20771 );
20772 }
20773 }
20774
20775 #[test]
20776 fn placement_strategy_as_ref_str_routes_through_as_str_accessor() {
20777 // Fail-before-pass-after byte-parity pin on the lifted
20778 // `impl AsRef<str> for PlacementStrategy` — asserts the
20779 // standard-library trait impl and the substrate-primitive
20780 // [`PlacementStrategy::as_str`] `pub const fn` accessor resolve
20781 // to the same `&str` per instance across the three-arm closed
20782 // set, so any future silent detour that routes the impl through
20783 // a divergent projection (a per-arm inline
20784 // `match self { PlacementStrategy::Sharded => "Sharded", … }`
20785 // re-inlining that opens a compile-time link to the un-lifted
20786 // arm-literal, a swap onto the kebab-case
20787 // [`gen_platform::Discriminant`] catalog identity that would
20788 // collide the wire axis with the dispatcher-catalog axis) trips
20789 // at caixa-core test time under `PartialEq` rather than at a
20790 // downstream `impl AsRef<str>`-bound consumer's silent split.
20791 // Sweeps every one of the three arms [`PlacementStrategy::ALL`]
20792 // carries so no arm's projection is covered only by the sibling
20793 // wire-format `Serialize` derive path. Peer of the sibling
20794 // [`crate::supervisor::tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
20795 // (419ea81) / `restart_strategy_as_ref_str_routes_through_as_str_accessor`
20796 // (63eb1a4) on the paired M2 per-supervisor closed-set typed
20797 // enums, and the [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
20798 // (16d5c7e) pin on the paired top-level `:versao` typed newtype
20799 // — the four pins together close the substrate primitive's
20800 // `AsRef<str>` projection axis on every closed-set typed enum
20801 // /newtype on the M2/M3 mesh + supervision + version surface.
20802 for &variant in PlacementStrategy::ALL {
20803 assert_eq!(
20804 <PlacementStrategy as AsRef<str>>::as_ref(&variant),
20805 variant.as_str(),
20806 "AsRef<str> impl on PlacementStrategy::{variant:?} must \
20807 byte-equal PlacementStrategy::as_str on the same instance \
20808 — divergence signals a silent detour off the substrate-\
20809 primitive accessor"
20810 );
20811 }
20812 }
20813
20814 #[test]
20815 fn placement_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
20816 // Fail-before-pass-after byte-parity pin on the three-path
20817 // convergence discipline the M3 per-Aplicacao distribution-
20818 // strategy primitive now carries on the `&str`-projection axis:
20819 // `<PlacementStrategy as AsRef<str>>::as_ref(&v)` (the newly
20820 // lifted impl), `format!("{v}")` (the pre-existing
20821 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
20822 // primitive `pub const fn` accessor both trait impls delegate
20823 // through) must resolve to the same byte-string on every
20824 // instance across the three-arm closed set. Refuses any future
20825 // divergence between the two trait impls (a stray
20826 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms rather
20827 // than delegating through the shared accessor; a hypothetical
20828 // `AsRef<str>` rewrite that inlines a per-arm literal cascade)
20829 // that would silently split the two projection paths of the
20830 // same closed-set typed enum. Mirrors the sibling three-path-
20831 // convergence discipline the peer
20832 // [`crate::supervisor::RestartPolicy`] typed enum carries on its
20833 // `AsRef<str>` / `Display` / `as_str` triple (supervisor.rs pin
20834 // `restart_policy_as_ref_str_routes_through_display_via_shared_accessor`,
20835 // 419ea81), the peer [`crate::supervisor::RestartStrategy`]
20836 // triple (supervisor.rs pin
20837 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
20838 // 63eb1a4), and the [`crate::CaixaVersion`] typed newtype
20839 // triple (version.rs pin
20840 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
20841 // 16d5c7e).
20842 for &variant in PlacementStrategy::ALL {
20843 let via_as_ref: &str = <PlacementStrategy as AsRef<str>>::as_ref(&variant);
20844 let via_display: String = format!("{variant}");
20845 let via_accessor: &str = variant.as_str();
20846 assert_eq!(via_as_ref, via_accessor);
20847 assert_eq!(via_display, via_accessor);
20848 assert_eq!(via_as_ref, via_display.as_str());
20849 }
20850 }
20851
20852 #[test]
20853 fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
20854 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
20855 // derive on [`PlacementStrategy`]: for each of the three variants
20856 // exactly one of the generated `is_single_node` / `is_replicated`
20857 // / `is_sharded` predicates returns `true` and the other two
20858 // return `false`. Prior to this derive the three per-arm
20859 // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
20860 // (the `placement_strategy_variants_round_trip` fixture, the
20861 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
20862 // fixture, and the
20863 // `validate_placement_reads_through_lifted_estrategia_accessor`
20864 // fixture) each open-coded a per-arm PartialEq compare against
20865 // the enum variant — three sites that expressed no compile-time
20866 // link back to the closed-set typed dispatch a future fourth
20867 // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
20868 // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
20869 // would have to thread through in lockstep or one fixture would
20870 // silently disagree with the others on which arms consume the
20871 // `:shard-key` axis. Peer of the sibling
20872 // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
20873 // / [`crate::supervisor::RestartPolicy`] /
20874 // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
20875 // the sibling closed-set typed-enum discriminator axes — extends
20876 // the same one-typed-dispatch-per-variant discipline onto the
20877 // fifth (and only remaining) closed-set typed-enum discriminator
20878 // on the caixa surface, closing the axis on the M3 mesh-slot
20879 // family.
20880 let rows: [(PlacementStrategy, [bool; 3]); 3] = [
20881 (PlacementStrategy::SingleNode, [true, false, false]),
20882 (PlacementStrategy::Replicated, [false, true, false]),
20883 (PlacementStrategy::Sharded, [false, false, true]),
20884 ];
20885 for (variant, expected) in rows {
20886 let observed = [
20887 variant.is_single_node(),
20888 variant.is_replicated(),
20889 variant.is_sharded(),
20890 ];
20891 assert_eq!(
20892 observed, expected,
20893 "PlacementStrategy::{variant:?} is_* predicates must partition \
20894 the arm set (single_node, replicated, sharded); got {observed:?}"
20895 );
20896 }
20897 }
20898
20899 #[test]
20900 fn placement_strategy_is_variant_predicates_are_const_fn() {
20901 // The [`gen_platform::IsVariant`] derive emits `const fn`
20902 // predicates on the peer [`crate::CaixaKind`] +
20903 // [`crate::upgrade::UpgradeInstruction`] +
20904 // [`crate::supervisor::RestartStrategy`] +
20905 // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
20906 // pin the same posture on [`PlacementStrategy`] so a future
20907 // accidental downgrade to non-`const` (an added runtime helper
20908 // reachable only from a non-`const` context, a manual hand-rolled
20909 // `impl` that shadows the derive-generated method) trips at
20910 // caixa-core build time rather than surfacing as a downstream
20911 // `const`-context regression far from the derive declaration.
20912 //
20913 // The pin lives inside a `const { assert!(..) }` block so the
20914 // compiler enforces both halves (arm predicate is `const`-
20915 // callable AND returns `true` for the matching arm) at
20916 // caixa-core compile time — peer to the sibling
20917 // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
20918 // pins on the closed-set typed enum arm-predicate const-
20919 // callability axis.
20920 const {
20921 assert!(PlacementStrategy::SingleNode.is_single_node());
20922 assert!(PlacementStrategy::Replicated.is_replicated());
20923 assert!(PlacementStrategy::Sharded.is_sharded());
20924 }
20925 }
20926
20927 #[test]
20928 fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
20929 // Fail-before-pass-after pin on the substrate-lifted
20930 // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
20931 // per-arm predicate: for each variant in the closed accept-set the
20932 // predicate returns `true` iff the variant consumes the paired
20933 // [`Placement::shard_key`] axis under
20934 // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
20935 // partition. Today the accept-set is the singleton `{Sharded}` —
20936 // `Sharded` is the Akka-style hash-keyed distribution arm
20937 // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
20938 // §II.1) and `Replicated` (active-active) refuse the axis through
20939 // [`AplicacaoError::ShardKeyOnNonSharded`].
20940 //
20941 // Pins the per-arm truth-table so a future arm addition (an
20942 // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
20943 // roadmap names, a `WeightedShard` promotion the future M5
20944 // adaptive-placement engine acknowledges) that landed a variant
20945 // without extending this predicate's arm-set would surface as a
20946 // caixa-core build-time exhaustiveness error at the
20947 // `match self { … }` arm-fan below rather than a silent per-consumer
20948 // mis-classification at renderer emit time. The paired
20949 // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
20950 // predicate stays a distinct question — arm-identity (which the
20951 // sibling
20952 // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
20953 // pin already locks) is not cross-slot-invariant consumption; today
20954 // they trip on the same singleton but the pair migrates through
20955 // one caixa-core edit on any future arm addition.
20956 //
20957 // Peer of the sibling per-arm classifier pins
20958 // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
20959 // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
20960 // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
20961 // derived paired predicate on the post-projection typed-view axis
20962 // — same "per-arm semantic-classification predicate paired with
20963 // the arm-identity predicate the derive already emits" discipline
20964 // extended onto the M3 mesh-slot `:placement :estrategia` ↔
20965 // `:placement :shard-key` cross-slot-invariant axis.
20966 let rows: [(PlacementStrategy, bool); 3] = [
20967 (PlacementStrategy::SingleNode, false),
20968 (PlacementStrategy::Replicated, false),
20969 (PlacementStrategy::Sharded, true),
20970 ];
20971 for (variant, expected) in rows {
20972 assert_eq!(
20973 variant.requires_shard_key(),
20974 expected,
20975 "PlacementStrategy::{variant:?}.requires_shard_key() must \
20976 be {expected} (the substrate-canonical cross-slot invariant \
20977 on the :placement :shard-key axis; today `Sharded` is the \
20978 singleton consuming arm — MESH-COMPOSITION §II.4)",
20979 );
20980 }
20981 }
20982
20983 #[test]
20984 fn placement_strategy_requires_shard_key_is_const_fn() {
20985 // The [`PlacementStrategy::requires_shard_key`] cross-slot-
20986 // invariant per-arm predicate is declared `#[must_use] pub const
20987 // fn` — pin the `const`-eval posture here so a future accidental
20988 // downgrade to non-`const` (an added runtime helper reachable
20989 // only from a non-`const` context, a manual hand-rolled `impl`
20990 // that shadows the current three-arm `match self { … }` dispatch)
20991 // trips at caixa-core build time rather than surfacing as a
20992 // downstream `const`-context regression far from the declaration.
20993 // Same shape as the sibling
20994 // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
20995 // the peer [`gen_platform::IsVariant`]-derived arm-identity
20996 // predicate axis, but here the load-bearing assertions live in
20997 // module-scope `const _: () = assert!(…)` items so a violation
20998 // fails at compile time (const-eval trip) rather than test time —
20999 // strictly stronger than the runtime `assert!(CONST)` pattern the
21000 // sibling pin uses, and side-steps the
21001 // `clippy::assertions_on_constants` lint the runtime pattern
21002 // otherwise accumulates on the module baseline.
21003 //
21004 // The test body simply witnesses that the module-scope items
21005 // compiled and the runtime dispatch agrees with the const-eval
21006 // dispatch on every arm — the runtime read gives the test a
21007 // failure surface (rather than an empty test body clippy would
21008 // flag as a no-op).
21009 const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
21010 const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
21011 const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
21012 assert_eq!(
21013 [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
21014 [
21015 PlacementStrategy::SingleNode.requires_shard_key(),
21016 PlacementStrategy::Replicated.requires_shard_key(),
21017 PlacementStrategy::Sharded.requires_shard_key(),
21018 ],
21019 "runtime and const-eval dispatch on \
21020 PlacementStrategy::requires_shard_key must agree on every arm",
21021 );
21022 }
21023
21024 #[test]
21025 fn placement_estrategia_accessor_is_const_fn() {
21026 // The [`Placement::estrategia`] per-`:placement` distribution-
21027 // strategy `Copy`-return scalar accessor is declared
21028 // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
21029 // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
21030 // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
21031 // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
21032 // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
21033 // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
21034 // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
21035 // [`RateLimit`], every one a `pub const fn`). Pin the
21036 // `const`-eval posture here so a future accidental downgrade to
21037 // non-`const` (an added runtime helper reachable only from a
21038 // non-`const` context, a slot promotion to a non-`Copy` return
21039 // that would silently drop the `const` qualifier, a manual
21040 // hand-rolled shadow) trips at caixa-core build time rather
21041 // than surfacing as a downstream `const`-context regression far
21042 // from the declaration.
21043 //
21044 // Same shape as the sibling
21045 // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
21046 // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
21047 // predicate axis — the load-bearing witness lives in the
21048 // module-scope `const fn` wrapper `estrategia_via_const_fn`
21049 // below: a body that calls [`Placement::estrategia`] under a
21050 // `const fn` signature is well-formed only when the callee is
21051 // itself `const fn`, so any future accidental downgrade of
21052 // [`Placement::estrategia`] to non-`const` fails at caixa-core
21053 // build time (const-eval E0015 / E0658 depending on the arm),
21054 // strictly stronger than a runtime `assert!(CONST)` and
21055 // side-stepping the destructor-in-const restriction that
21056 // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
21057 // items on `Placement`'s `Vec<String>` / `Option<String>`
21058 // carriers.
21059 //
21060 // The runtime body witnesses that the const-eval-shaped
21061 // wrapper agrees with a direct call on every closed-set arm.
21062 const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
21063 p.estrategia()
21064 }
21065 for estrategia in [
21066 PlacementStrategy::SingleNode,
21067 PlacementStrategy::Replicated,
21068 PlacementStrategy::Sharded,
21069 ] {
21070 let placement = Placement {
21071 estrategia,
21072 clusters: Vec::new(),
21073 affinity: None,
21074 shard_key: None,
21075 };
21076 assert_eq!(
21077 estrategia_via_const_fn(&placement),
21078 placement.estrategia(),
21079 "const-fn-wrapped and direct dispatch on \
21080 Placement::estrategia must agree for {estrategia:?}",
21081 );
21082 }
21083 }
21084
21085 #[test]
21086 fn entrada_port_accessor_is_const_fn() {
21087 // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
21088 // scalar accessor is declared `#[must_use] pub const fn` —
21089 // matching the peer M3 mesh-slot `Copy`-return accessor family
21090 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
21091 // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
21092 // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
21093 // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
21094 // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
21095 // [`RateLimit::window`] on the sibling [`RateLimit`], the
21096 // sibling per-`:placement` [`Placement::estrategia`] pinned by
21097 // [`placement_estrategia_accessor_is_const_fn`] above — every
21098 // one a `pub const fn`). Pin the `const`-eval posture here so
21099 // a future accidental downgrade to non-`const` (an added
21100 // runtime helper reachable only from a non-`const` context, an
21101 // `Option<u16>`-shape migration once the substrate grows
21102 // per-`:membros` heterogeneous listener ports that would
21103 // silently drop the `const` qualifier, a manual hand-rolled
21104 // shadow) trips at caixa-core build time rather than surfacing
21105 // as a downstream `const`-context regression far from the
21106 // declaration.
21107 //
21108 // Same shape as the sibling
21109 // [`placement_estrategia_accessor_is_const_fn`] pin above — the
21110 // load-bearing witness lives in the module-scope `const fn`
21111 // wrapper `port_via_const_fn`: a body that calls
21112 // [`Entrada::port`] under a `const fn` signature is well-formed
21113 // only when the callee is itself `const fn`, side-stepping the
21114 // destructor-in-const restriction that would otherwise block a
21115 // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
21116 // `String` / `Vec<String>` carriers.
21117 //
21118 // The runtime body sweeps a representative port set spanning
21119 // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
21120 // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
21121 // ceiling — the const-fn-wrapped call must agree with a direct
21122 // call on every fixture (a violation trips the test) and every
21123 // returned scalar must byte-equal the input `port` (a violation
21124 // means the accessor stopped being a raw field-return copy).
21125 const fn port_via_const_fn(e: &Entrada) -> u16 {
21126 e.port()
21127 }
21128 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
21129 let entrada = Entrada {
21130 host: String::new(),
21131 para: String::new(),
21132 port,
21133 paths: Vec::new(),
21134 };
21135 assert_eq!(
21136 port_via_const_fn(&entrada),
21137 entrada.port(),
21138 "const-fn-wrapped and direct dispatch on Entrada::port \
21139 must agree for port={port}",
21140 );
21141 assert_eq!(
21142 entrada.port(),
21143 port,
21144 "Entrada::port must return the storage-side u16 verbatim \
21145 for port={port}",
21146 );
21147 }
21148 }
21149
21150 #[test]
21151 fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
21152 // Load-bearing cross-slot-partition pin closing the loop between
21153 // the substrate-lifted
21154 // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
21155 // the closed-set typed enum and the actual
21156 // [`AplicacaoSpec::validate_placement`] runtime behavior across
21157 // the paired `:placement :shard-key` axis: every validated
21158 // [`Placement`] past [`AplicacaoSpec::validate_placement`]
21159 // satisfies `placement.shard_key().is_some() ==
21160 // placement.estrategia().requires_shard_key()`. The four-cell
21161 // shape witness sweeps every combination of (variant in the
21162 // closed accept-set, `:shard-key` Some/None) and pins:
21163 //
21164 // * variant.requires_shard_key() && shard_key.is_some() →
21165 // validate() passes; the paired shape is the sole
21166 // `requires_shard_key` arm-family accepted shape.
21167 // * variant.requires_shard_key() && shard_key.is_none() →
21168 // validate() fails with [`AplicacaoError::ShardedWithoutKey`];
21169 // the paired shape is the refused missing-key shape on
21170 // Sharded-family arms.
21171 // * !variant.requires_shard_key() && shard_key.is_some() →
21172 // validate() fails with
21173 // [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
21174 // is the refused declared-but-inert shape on non-Sharded-
21175 // family arms.
21176 // * !variant.requires_shard_key() && shard_key.is_none() →
21177 // validate() passes; the paired shape is the sole
21178 // non-`requires_shard_key` arm-family accepted shape.
21179 //
21180 // The compile-time-exhaustive `match p.estrategia()` dispatch at
21181 // [`AplicacaoSpec::validate_placement`] preserves its structural
21182 // arm-fan (a future arm addition still surfaces a build-time
21183 // exhaustiveness error there); this pin closes the semantic loop
21184 // between the arm-fan's shape-gate cascades and the substrate-
21185 // canonical predicate every downstream consumer of the paired
21186 // shape reads through. Fail-before-pass-after locally verified by
21187 // mutating the predicate's `Sharded => true` arm to `false` — the
21188 // truthy `expects_ok` cell for `Sharded` + `Some` trips the
21189 // `validate() must pass` assertion; restoring passes. Same "close
21190 // the loop between the typed predicate and the runtime behavior"
21191 // discipline as the sibling
21192 // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
21193 // (7b97d26) cross-projection pin on the peer [`WitTarget`]
21194 // per-arm classifier axis.
21195 for variant in [
21196 PlacementStrategy::SingleNode,
21197 PlacementStrategy::Replicated,
21198 PlacementStrategy::Sharded,
21199 ] {
21200 for present in [false, true] {
21201 let mut spec = three_member_spec();
21202 spec.placement.estrategia = variant;
21203 spec.placement.shard_key = present.then(|| "tenantId".into());
21204 let expects_ok = variant.requires_shard_key() == present;
21205 let result = spec.validate();
21206 match (expects_ok, &result) {
21207 (true, Ok(())) => {}
21208 (false, Err(err)) => {
21209 // Cross-check the refusal diagnostic names the
21210 // right cell of the four-cell shape witness — the
21211 // `requires_shard_key && !present` cell must trip
21212 // [`AplicacaoError::ShardedWithoutKey`]; the
21213 // `!requires_shard_key && present` cell must trip
21214 // [`AplicacaoError::ShardKeyOnNonSharded`].
21215 match (variant.requires_shard_key(), present, err) {
21216 (true, false, AplicacaoError::ShardedWithoutKey) => {}
21217 (
21218 false,
21219 true,
21220 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
21221 ) => {
21222 assert_eq!(
21223 *e, variant,
21224 "ShardKeyOnNonSharded.estrategia must byte-equal \
21225 the paired PlacementStrategy",
21226 );
21227 }
21228 _ => panic!(
21229 "unexpected refusal for estrategia={variant:?} \
21230 present={present}: {err:?}"
21231 ),
21232 }
21233 }
21234 (true, Err(err)) => panic!(
21235 "validate() must pass for estrategia={variant:?} \
21236 present={present} (requires_shard_key={} == present={present}), \
21237 got {err:?}",
21238 variant.requires_shard_key(),
21239 ),
21240 (false, Ok(())) => panic!(
21241 "validate() must fail for estrategia={variant:?} \
21242 present={present} (requires_shard_key={} != present={present})",
21243 variant.requires_shard_key(),
21244 ),
21245 }
21246 }
21247 }
21248 }
21249
21250 #[test]
21251 fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
21252 // Pin the M3 diagnostic template routes through the typed
21253 // [`PlacementStrategy`] Display byte-string (rebound from the
21254 // prior `{estrategia:?}` `Debug` route). Pre-lift the two
21255 // routes emitted identical bytes (the `Debug` derive on a
21256 // unit variant emits the variant name verbatim, exactly what
21257 // `as_str` returns), but the two paths were structurally
21258 // independent — a future `#[serde(rename_all = "…")]`
21259 // attribute or variant rename would coordinate the wire /
21260 // `Display` / `as_str` triple through the lifted const but
21261 // leave the `Debug` route on the compiler-derived variant name,
21262 // silently desynchronizing the diagnostic byte-string from the
21263 // wire byte-string. Rebinding the template onto `Display`
21264 // ties the diagnostic to the same lifted
21265 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
21266 // emits — drift becomes structurally impossible. Pin the
21267 // byte-string here so a future edit that reverts the template
21268 // to `{estrategia:?}` is caught at caixa-core test time, not
21269 // at consumer dispatch time.
21270 for (variant, expected_scalar) in [
21271 (
21272 PlacementStrategy::SingleNode,
21273 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
21274 ),
21275 (
21276 PlacementStrategy::Replicated,
21277 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
21278 ),
21279 (
21280 PlacementStrategy::Sharded,
21281 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
21282 ),
21283 ] {
21284 let err = AplicacaoError::PlacementWithoutClusters {
21285 estrategia: variant,
21286 };
21287 let msg = err.to_string();
21288 assert!(
21289 msg.starts_with(&format!(":placement {expected_scalar} requires")),
21290 "PlacementWithoutClusters diagnostic for {variant:?} must open \
21291 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
21292 );
21293 }
21294 }
21295
21296 #[test]
21297 fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
21298 // Peer of
21299 // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
21300 // on the second M3 diagnostic that carries the typed
21301 // [`PlacementStrategy`] in its `#[error(…)]` template. Both
21302 // diagnostics now route the strategy scalar through the same
21303 // [`std::fmt::Display`] surface, tying the diagnostic
21304 // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
21305 // const set the wire format also emits. The two non-Sharded
21306 // arms are exercised here (the diagnostic exists to flag a
21307 // `:shard-key` slot the current strategy will never consume);
21308 // the peer `Sharded` arm never reaches this diagnostic (the
21309 // `Sharded` strategy consumes `:shard-key` — the
21310 // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
21311 // slot instead).
21312 for (variant, expected_scalar) in [
21313 (
21314 PlacementStrategy::SingleNode,
21315 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
21316 ),
21317 (
21318 PlacementStrategy::Replicated,
21319 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
21320 ),
21321 ] {
21322 let err = AplicacaoError::ShardKeyOnNonSharded {
21323 estrategia: variant,
21324 shard_key: "$tenantId".into(),
21325 };
21326 let msg = err.to_string();
21327 assert!(
21328 msg.starts_with(&format!(":placement {expected_scalar} carries")),
21329 "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
21330 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
21331 );
21332 }
21333 }
21334
21335 #[test]
21336 fn placement_strategy_all_enumerates_every_variant_once() {
21337 // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
21338 // exhaustive-iteration surface: every variant appears exactly
21339 // once, and the slice length matches the arm count of the
21340 // closed set. Every consumer that walks the accepted-strategy
21341 // set (a future `feira app placement --list` CLI-side surfacing,
21342 // a future M4 admission-webhook's rejection body naming the
21343 // accepted-strategy list, the [`PlacementStrategy::from_wire`]
21344 // reverse-projection consumers that iterate the accept-set for
21345 // a "did you mean" hint) reads through this slice, so a future
21346 // variant addition (an `Anycast` mesh-anycast arm the
21347 // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
21348 // grows the enum but forgets to grow [`Self::ALL`] silently
21349 // truncates every downstream consumer's accept-set at the same
21350 // pre-addition boundary — this pin fails at caixa-core build
21351 // time on the pairwise-distinct + arm-count invariants.
21352 //
21353 // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
21354 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
21355 // pins on the peer closed-set typed-enum axes.
21356 let all: &[PlacementStrategy] = PlacementStrategy::ALL;
21357 assert_eq!(
21358 all.len(),
21359 3,
21360 "PlacementStrategy::ALL must enumerate every variant of the \
21361 three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
21362 );
21363 for (i, a) in all.iter().enumerate() {
21364 for (j, b) in all.iter().enumerate() {
21365 if i != j {
21366 assert_ne!(
21367 a, b,
21368 "PlacementStrategy::ALL must carry every variant exactly \
21369 once — got duplicate {a:?} at indices {i} and {j}"
21370 );
21371 }
21372 }
21373 }
21374 for variant in [
21375 PlacementStrategy::SingleNode,
21376 PlacementStrategy::Replicated,
21377 PlacementStrategy::Sharded,
21378 ] {
21379 assert!(
21380 all.contains(&variant),
21381 "PlacementStrategy::ALL must contain {variant:?} — a future variant \
21382 addition that grows the enum but forgets to grow the ALL slice \
21383 silently truncates every downstream consumer's accept-set at the \
21384 pre-addition boundary"
21385 );
21386 }
21387 }
21388
21389 #[test]
21390 fn placement_strategy_from_wire_accepts_every_lifted_constant() {
21391 // Fail-before-pass-after pin on the forward accept-set of the
21392 // [`PlacementStrategy::from_wire`] reverse projection: every
21393 // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
21394 // constant the [`PlacementStrategy::as_str`] emitter walks
21395 // parses back to its paired variant. Any future arm addition
21396 // that grows the emitter's `as_str` match but forgets to grow
21397 // the parser's `from_str` match silently splits the two halves
21398 // of the round-trip — the wire byte-string one non-serde
21399 // consumer parses from the one the emitter wrote — with the
21400 // failure surfacing at parse time far from the rebrand commit.
21401 // Pinning the three-arm accept-set here catches the drift at
21402 // caixa-core build time.
21403 //
21404 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
21405 // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
21406 // closed-set typed-enum `str → Self` axes.
21407 for (wire, expected) in [
21408 (
21409 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
21410 PlacementStrategy::SingleNode,
21411 ),
21412 (
21413 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
21414 PlacementStrategy::Replicated,
21415 ),
21416 (
21417 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
21418 PlacementStrategy::Sharded,
21419 ),
21420 ] {
21421 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
21422 panic!(
21423 "PlacementStrategy::from_wire({wire:?}) must accept every \
21424 M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
21425 lifted canonical byte-string that PlacementStrategy::{expected:?} \
21426 serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
21427 )
21428 });
21429 assert_eq!(
21430 parsed, expected,
21431 "PlacementStrategy::from_wire({wire:?}) must return \
21432 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
21433 );
21434 }
21435 }
21436
21437 #[test]
21438 fn placement_strategy_from_wire_round_trips_through_as_str() {
21439 // Fail-before-pass-after pin on the closed round-trip between
21440 // the forward [`PlacementStrategy::as_str`] emitter and the
21441 // reverse [`PlacementStrategy::from_wire`] parser: for every
21442 // variant in [`PlacementStrategy::ALL`], parsing the emitter's
21443 // output must return exactly the same variant. Any per-arm
21444 // divergence — a future arm added to `as_str` but not
21445 // `from_str`, an accidental copy-paste flip in one but not the
21446 // other — silently splits the emit and parse halves and the
21447 // failure surfaces at consumer parse time far from the drift
21448 // site. The `ALL`-iterating shape means a future variant
21449 // addition picks up the coverage by construction.
21450 //
21451 // Peer of the sibling [`crate::kind::tests`] round-trip pin on
21452 // [`crate::CaixaKind::from_wire`] and the
21453 // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
21454 // sibling round-trip pin on [`RateLimitUnit`].
21455 for &variant in PlacementStrategy::ALL {
21456 let wire = variant.as_str();
21457 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
21458 panic!(
21459 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
21460 must be Some({variant:?}) — the two halves of the round-trip \
21461 dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
21462 got None on wire byte-string {wire:?}"
21463 )
21464 });
21465 assert_eq!(
21466 parsed, variant,
21467 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
21468 must round-trip to the same variant; got {parsed:?}"
21469 );
21470 }
21471 }
21472
21473 #[test]
21474 fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
21475 // Fail-before-pass-after pin on the closed-set refusal
21476 // discipline of [`PlacementStrategy::from_wire`]: every
21477 // byte-string outside the three-arm accept-set returns `None`
21478 // rather than silently collapsing onto the [`Default`]
21479 // (`Replicated`) arm or an arbitrary neighbor. The refusal set
21480 // exercised here sweeps the load-bearing drift shapes: the
21481 // empty string (a stripped serde-attribute drift), an all-
21482 // whitespace string (the canonical text-editor accidental
21483 // padding shape), the lowercased kebab-case forms a future
21484 // `#[serde(rename_all = "kebab-case")]` attribute would emit
21485 // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
21486 // coincidentally match the accepted canonical scalars, so only
21487 // `"single-node"` fires as a refusal, but pinning the case-
21488 // sensitivity of the accepted arms via the peer [`SingleNode`]
21489 // assertion in the round-trip pin makes the discipline
21490 // structurally clear), the lowercased single-word forms
21491 // (`"singlenode"`), the padded canonical scalar
21492 // (`" Sharded "`), the trailing-comma / trailing-newline shapes
21493 // (`"Sharded\n"`), and a pointer-different `&'static str` that
21494 // happens to alias a canonical byte-string by content but not
21495 // by identity (validated implicitly by the emitter's routing
21496 // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
21497 // identity a paired [`crate::assert_str_reexport_identity`] pin
21498 // in caixa-core's per-const declaration surface would catch).
21499 //
21500 // Peer of the sibling
21501 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
21502 // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
21503 for bad in [
21504 "",
21505 " ",
21506 "\n",
21507 "\t",
21508 "single-node",
21509 "singlenode",
21510 "SingleNodes",
21511 "single_node",
21512 "single node",
21513 "SINGLENODE",
21514 "SingleNode ",
21515 " SingleNode",
21516 " Sharded ",
21517 "Sharded\n",
21518 "replicated ",
21519 "sharded",
21520 "REPLICATED",
21521 "Anycast",
21522 "Global",
21523 "?",
21524 ] {
21525 assert!(
21526 PlacementStrategy::from_wire(bad).is_none(),
21527 "PlacementStrategy::from_wire({bad:?}) must return None — the \
21528 parser's accept-set is exactly the three PlacementStrategy::as_str \
21529 outputs (SingleNode, Replicated, Sharded), and this byte-string \
21530 is outside that closed set"
21531 );
21532 }
21533 }
21534
21535 #[test]
21536 fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
21537 // Fail-before-pass-after pin on the third path of the four-path
21538 // convergence: `from_str` (the reverse projection) inverts the
21539 // `Serialize` derive's wire byte-string on every variant.
21540 // Together with the pre-existing three-path convergence
21541 // (`Display` + `as_str` + `Serialize` all resolve to the same
21542 // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
21543 // the peer
21544 // [`placement_strategy_display_matches_serialized_wire_byte_string`])
21545 // this closes the round-trip: the wire byte-string the
21546 // `Serialize` derive emits parses back to the same variant
21547 // through `from_str`, so any future serde-attribute or variant-
21548 // rename drift on the emit half now surfaces as a matched drift
21549 // on the parse half at caixa-core build time — the two halves
21550 // migrate as a unit through the lifted consts on any future
21551 // rename, and the round-trip cannot silently split.
21552 //
21553 // Peer of the sibling
21554 // [`placement_strategy_display_matches_serialized_wire_byte_string`]
21555 // wire-format pin — extends the three-path convergence
21556 // (`Display` + `as_str` + `Serialize`) onto the fourth path
21557 // (`from_str`), closing the `str ↔ Self` round-trip on the
21558 // M3 `:placement :estrategia` closed-set axis.
21559 for &variant in PlacementStrategy::ALL {
21560 let wire = serde_json::to_string(&variant).unwrap();
21561 let unquoted = wire
21562 .strip_prefix('"')
21563 .and_then(|s| s.strip_suffix('"'))
21564 .expect("serialized PlacementStrategy is a JSON string");
21565 let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
21566 panic!(
21567 "PlacementStrategy::from_wire({unquoted:?}) must accept the \
21568 Serialize derive's wire byte-string for \
21569 PlacementStrategy::{variant:?} — the four-path convergence \
21570 (Display + as_str + Serialize + from_str) resolves through \
21571 the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
21572 )
21573 });
21574 assert_eq!(
21575 parsed, variant,
21576 "PlacementStrategy::from_wire of the Serialize derive's wire \
21577 byte-string for PlacementStrategy::{variant:?} must round-trip \
21578 to the same variant; got {parsed:?}"
21579 );
21580 }
21581 }
21582
21583 #[test]
21584 fn placement_strategy_try_from_str_routes_through_from_wire_accessor() {
21585 // Fail-before-pass-after byte-parity pin on the newly lifted
21586 // `impl TryFrom<&str> for PlacementStrategy` — asserts the
21587 // standard-library trait impl and the substrate-primitive
21588 // [`PlacementStrategy::from_wire`] `Option<Self>` accessor
21589 // resolve to the same three-arm accept-set across every arm the
21590 // exhaustive [`PlacementStrategy::ALL`] slice enumerates. Any
21591 // future silent detour that routes the trait impl through a
21592 // divergent projection (a per-arm inline `match s { "SingleNode"
21593 // => Ok(Self::SingleNode), … }` re-inlining that opens a
21594 // compile-time link to the un-lifted arm-literal, a stray
21595 // `#[serde(rename_all = "…")]` attribute drift that silently
21596 // splits the wire byte-string from every consumer that reaches
21597 // for this typed dispatch) trips at caixa-core test time under
21598 // `assert_eq!` rather than at a downstream `impl TryFrom<&str>`-
21599 // bound consumer's silent split. Sweeps every one of the three
21600 // arms [`PlacementStrategy::ALL`] carries so no arm's projection
21601 // is covered only by the sibling method-named `from_wire` path.
21602 // Peer of the sibling
21603 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
21604 // (3c83606) and
21605 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
21606 // (bf33136) — extends the trait-idiomatic reverse-projection
21607 // axis onto the first M3-mesh-primitive-defining slot enum on
21608 // the caixa surface.
21609 for &variant in PlacementStrategy::ALL {
21610 let wire = variant.as_str();
21611 assert_eq!(
21612 <PlacementStrategy as TryFrom<&str>>::try_from(wire),
21613 Ok(variant),
21614 "TryFrom<&str> impl on PlacementStrategy must round-trip \
21615 PlacementStrategy::{variant:?}.as_str() = {wire:?} back to \
21616 Ok(PlacementStrategy::{variant:?}) — divergence from \
21617 PlacementStrategy::from_wire signals a silent detour off \
21618 the substrate-primitive accessor"
21619 );
21620 assert_eq!(
21621 <PlacementStrategy as TryFrom<&str>>::try_from(wire).ok(),
21622 PlacementStrategy::from_wire(wire),
21623 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
21624 PlacementStrategy::from_wire on the same input"
21625 );
21626 }
21627 }
21628
21629 #[test]
21630 fn placement_strategy_try_from_str_rejects_unknown_byte_strings() {
21631 // Rejection witness on the `impl TryFrom<&str> for
21632 // PlacementStrategy` — sweeps a candidate set of byte-strings
21633 // outside the three-arm camelCase-schema wire accept-set the
21634 // sibling [`PlacementStrategy::as_str`] emits and asserts every
21635 // one lands on `Err(())`, so a future accidental widening of the
21636 // trait impl's accept-set (a stray additional
21637 // `_ if s.eq_ignore_ascii_case("SingleNode") => Ok(…)` case-
21638 // fold path, a silent inclusion of a kebab-case rebrand of the
21639 // wire byte-string that would collide the two-axis split the
21640 // sibling `placement_strategy_from_wire_rejects_unknown_byte_strings`
21641 // pin makes load-bearing) trips at caixa-core test time. The
21642 // candidate set includes the empty string, whitespace-only
21643 // padding, kebab-case rebrand candidates (`"single-node"`),
21644 // snake_case rebrand candidates (`"single_node"`), uppercase
21645 // rebrand candidates, trailing/leading-whitespace-padded
21646 // canonical scalars, the trailing-newline shape, English-rebrand
21647 // candidates (`"Anycast"`, `"Global"`), and the residual `"?"`
21648 // to trip on any future accidental widening onto the sentinel
21649 // shape sibling enums use for unknown-arm diagnostics.
21650 // Peer of the sibling
21651 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
21652 // (3c83606) rejection witness.
21653 let rejected: &[&str] = &[
21654 "",
21655 " ",
21656 "\n",
21657 "\t",
21658 "single-node",
21659 "singlenode",
21660 "SingleNodes",
21661 "single_node",
21662 "single node",
21663 "SINGLENODE",
21664 "SingleNode ",
21665 " SingleNode",
21666 " Sharded ",
21667 "Sharded\n",
21668 "replicated ",
21669 "sharded",
21670 "REPLICATED",
21671 "Anycast",
21672 "Global",
21673 "?",
21674 "\"Sharded\"",
21675 ];
21676 for &input in rejected {
21677 assert_eq!(
21678 <PlacementStrategy as TryFrom<&str>>::try_from(input),
21679 Err(()),
21680 "TryFrom<&str> impl on PlacementStrategy must reject the \
21681 non-wire byte-string {input:?} — silent acceptance signals \
21682 an accept-set widening off the paired \
21683 PlacementStrategy::from_wire resolver"
21684 );
21685 }
21686 }
21687
21688 #[test]
21689 fn placement_strategy_from_into_static_str_routes_through_as_str_accessor() {
21690 // Fail-before-pass-after byte-parity pin on the newly lifted
21691 // `impl From<PlacementStrategy> for &'static str` — asserts the
21692 // standard-library trait impl and the substrate-primitive
21693 // [`PlacementStrategy::as_str`] `pub const fn` accessor resolve
21694 // to the same three-arm emit-set across every arm the exhaustive
21695 // [`PlacementStrategy::ALL`] slice enumerates. Any future silent
21696 // detour that routes the trait impl through a divergent
21697 // projection (a per-arm inline `match strategy { SingleNode =>
21698 // "SingleNode", … }` re-inlining that opens a compile-time link
21699 // to the un-lifted arm-literal outside the paired
21700 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] lifted constants,
21701 // an accidental swap onto the sibling kebab-case
21702 // [`gen_platform::Discriminant`] catalog identity that would
21703 // collide the wire axis with the dispatcher-catalog axis the
21704 // sibling [`PlacementStrategy::as_str`] doc block makes load-
21705 // bearing) trips at caixa-core test time under `assert_eq!`
21706 // rather than at a downstream `impl Into<&'static str>`-bound
21707 // consumer's silent split. Sweeps every one of the three arms
21708 // [`PlacementStrategy::ALL`] carries so no arm's projection is
21709 // covered only by the sibling method-named `as_str` /
21710 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
21711 // `<&'static str as From<PlacementStrategy>>::from` output in
21712 // three `const`-shape bindings to make the `'static` lifetime
21713 // promise a build-time invariant — a future accidental downgrade
21714 // of any of the three arms'
21715 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants to a
21716 // non-`&'static str` (a `String::leak()`-produced return, a
21717 // `Box::leak`-cast, an intermediate lifetime-erasing helper)
21718 // trips at caixa-core build time rather than at a downstream
21719 // `'static`-bound consumer. Peer of the sibling
21720 // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
21721 // (523157d) /
21722 // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
21723 // (9fb37d0) /
21724 // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
21725 // (edb827b) /
21726 // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
21727 // (c189a6f) pins on the sibling closed-set typed-enum forward-
21728 // projection axes — extends the trait-idiomatic forward-
21729 // projection axis onto the fifth closed-set fieldless typed
21730 // enum on the caixa surface (the M3-mesh-primitive-defining
21731 // `:placement :estrategia` axis, first-of-many on the M3 mesh
21732 // slot family the caixa-mesh renderer keys off end-to-end).
21733 const SINGLE_NODE: &str = PlacementStrategy::SingleNode.as_str();
21734 const REPLICATED: &str = PlacementStrategy::Replicated.as_str();
21735 const SHARDED: &str = PlacementStrategy::Sharded.as_str();
21736 for &variant in PlacementStrategy::ALL {
21737 let via_trait: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
21738 let via_method: &'static str = variant.as_str();
21739 assert_eq!(
21740 via_trait, via_method,
21741 "From<PlacementStrategy> for &'static str impl must \
21742 round-trip PlacementStrategy::{variant:?} to the same \
21743 lifted M3_PLACEMENT_ESTRATEGIA_* const \
21744 PlacementStrategy::as_str returns — divergence signals \
21745 a silent detour off the substrate-primitive accessor"
21746 );
21747 let via_into: &'static str = variant.into();
21748 assert_eq!(
21749 via_into, via_method,
21750 "Into<&'static str>::into on PlacementStrategy::{variant:?} \
21751 must byte-equal PlacementStrategy::as_str on the same \
21752 input — the blanket-derived Into shape must resolve to \
21753 the same as_str dispatch as the explicit From impl"
21754 );
21755 }
21756 assert_eq!(
21757 [SINGLE_NODE, REPLICATED, SHARDED],
21758 [
21759 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
21760 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
21761 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
21762 ],
21763 "const-context PlacementStrategy::as_str must resolve to the \
21764 three lifted M3_PLACEMENT_ESTRATEGIA_* consts — a future \
21765 accidental downgrade of any arm to a non-const or non-static \
21766 byte-string breaks the `&'static str`-lifetime promise the \
21767 paired From<PlacementStrategy> for &'static str impl carries \
21768 by construction"
21769 );
21770 }
21771
21772 #[test]
21773 fn placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
21774 // Cross-axis partition pin: the paired trait-idiomatic
21775 // `From<PlacementStrategy> for &'static str` forward projection
21776 // and the method-named [`PlacementStrategy::as_str`] forward
21777 // projection must resolve identically on *every* arm, not just
21778 // the ones named in the primary byte-parity pin above. Sweeps
21779 // every [`PlacementStrategy::ALL`] arm and asserts the trait's
21780 // `From::from` output byte-equals the method-named accessor's
21781 // return-value on each, locking the two forward-projection paths
21782 // together by construction so any future detour (a stray `From`
21783 // special-case that lands on a divergent per-arm literal outside
21784 // the paired `as_str` dispatch, a hypothetical rebrand touching
21785 // one axis without the other) trips at caixa-core test time.
21786 // Peer of the sibling forward-projection partition pins
21787 // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
21788 // (523157d) /
21789 // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
21790 // (9fb37d0) /
21791 // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
21792 // (edb827b) /
21793 // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
21794 // (c189a6f) — extends the round-trip discipline onto the fifth
21795 // closed-set typed enum on the caixa surface, closing the two-way
21796 // `Self ↔ &'static str` round-trip on the trait-idiomatic pair
21797 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
21798 // well as the pre-existing method-named pair (`as_str` +
21799 // `from_wire`).
21800 for &variant in PlacementStrategy::ALL {
21801 let via_trait: &'static str = <&'static str as From<PlacementStrategy>>::from(variant);
21802 let via_method: &'static str = variant.as_str();
21803 assert_eq!(
21804 via_trait, via_method,
21805 "From<PlacementStrategy> for &'static str and \
21806 PlacementStrategy::as_str must resolve identically on \
21807 PlacementStrategy::{variant:?} — divergence signals the \
21808 two forward-projection paths have drifted onto different \
21809 emit-sets"
21810 );
21811 }
21812 // Round-trip witness: every arm's forward `From` output re-parses
21813 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
21814 // to the original variant. Closes the two-way `PlacementStrategy
21815 // ↔ &'static str` round-trip on the trait-idiomatic axis pair
21816 // directly (no wire-vocab intermediate the peer [`CaixaKind`]
21817 // axis pair requires — the emit-side
21818 // [`PlacementStrategy::as_str`] and the parse-side
21819 // [`PlacementStrategy::from_wire`] dispatch on the same three
21820 // lifted [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`] constants
21821 // by construction), mirroring the pre-existing method-named
21822 // `as_str` + `from_wire` round-trip on the substrate-primitive
21823 // axis pair.
21824 for &variant in PlacementStrategy::ALL {
21825 let emitted: &'static str = variant.into();
21826 let re_parsed: Result<PlacementStrategy, ()> =
21827 <PlacementStrategy as TryFrom<&str>>::try_from(emitted);
21828 assert_eq!(
21829 re_parsed,
21830 Ok(variant),
21831 "trait-idiomatic axis pair must round-trip \
21832 PlacementStrategy::{variant:?} through `.into::<&'static \
21833 str>()` and back through `TryFrom<&str>` — a break \
21834 signals the forward-emit and reverse-parse axes have \
21835 drifted onto different vocabularies"
21836 );
21837 }
21838 }
21839
21840 #[test]
21841 fn rejects_zero_policy_timeout() {
21842 let mut s = three_member_spec();
21843 s.politicas.timeout = Some(Duration::ZERO);
21844 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
21845 }
21846
21847 #[test]
21848 fn rejects_zero_policy_retries() {
21849 let mut s = three_member_spec();
21850 s.politicas.retries = Some(0);
21851 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
21852 }
21853
21854 #[test]
21855 fn rejects_policy_retries_above_cap() {
21856 // The fail-before-pass-after pin: `Some(11)` is structurally
21857 // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
21858 // passed validate on every pre-gate codebase because the
21859 // typed slot's only check was the zero-floor arm. The
21860 // thundering-herd amplification vector only surfaced at the
21861 // runtime substrate (Envoy / Cilium L7 retry overlay)
21862 // far from the source caixa.lisp with no field naming the
21863 // offending policy.
21864 let mut s = three_member_spec();
21865 s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
21866 assert_eq!(
21867 s.validate().unwrap_err(),
21868 AplicacaoError::PolicyRetriesExceedsCap {
21869 retries: POLICY_RETRIES_MAX + 1
21870 }
21871 );
21872 }
21873
21874 #[test]
21875 fn rejects_policy_retries_far_above_cap() {
21876 // The `u32::MAX` worst case — the four-billion-retry policy
21877 // a typo (`(:retries 4294967295)`) or struct-literal
21878 // copy-paste lands in the slot. Pin the cap arm's coverage
21879 // explicitly across the full `u32` overflow so a future
21880 // relaxation that drops the upper bound surfaces here.
21881 let mut s = three_member_spec();
21882 s.politicas.retries = Some(u32::MAX);
21883 assert_eq!(
21884 s.validate().unwrap_err(),
21885 AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
21886 );
21887 }
21888
21889 #[test]
21890 fn accepts_policy_retries_at_cap() {
21891 // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
21892 // must validate. The cap is inclusive on the top edge,
21893 // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
21894 // discipline on the sibling [`crate::LimitsSpec::memory`]
21895 // axis. Pin the boundary explicitly so a future off-by-one
21896 // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
21897 // surfaces here as a test failure rather than a silent
21898 // contract narrowing.
21899 let mut s = three_member_spec();
21900 s.politicas.retries = Some(POLICY_RETRIES_MAX);
21901 s.validate()
21902 .expect("retries == POLICY_RETRIES_MAX must validate");
21903 }
21904
21905 #[test]
21906 fn accepts_policy_retries_typical_values() {
21907 // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
21908 // every value in the validated set must pass. The
21909 // Envoy / Istio production-playbook recommendation band
21910 // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
21911 // (`maxRetries ≤ 10`) both lie within this set.
21912 for r in 1..=POLICY_RETRIES_MAX {
21913 let mut s = three_member_spec();
21914 s.politicas.retries = Some(r);
21915 s.validate()
21916 .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
21917 }
21918 }
21919
21920 #[test]
21921 fn policy_retries_zero_takes_precedence_over_cap() {
21922 // The cross-arm ordering pin: `Some(0)` is structurally
21923 // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
21924 // (cap), but the zero-floor diagnostic is the more
21925 // self-locating one (it directly names the omit-axis
21926 // remediation), so the validate gate must fire on zero
21927 // first. Pin the order so a future refactor that reorders
21928 // the arms surfaces here as a test failure rather than a
21929 // silent diagnostic regression. Same shape every other
21930 // zero-then-shape ordering on this surface uses
21931 // ([`AplicacaoError::PolicyTimeoutZero`] then
21932 // [`AplicacaoError::PolicyTimeoutNotCanonical`];
21933 // [`AplicacaoError::PolicyBreakerZeroWindow`] then
21934 // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
21935 let mut s = three_member_spec();
21936 s.politicas.retries = Some(0);
21937 assert_eq!(
21938 s.validate().unwrap_err(),
21939 AplicacaoError::PolicyRetriesZero,
21940 "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
21941 );
21942 }
21943
21944 #[test]
21945 fn policy_retries_cap_diagnostic_carries_offending_value() {
21946 // The diagnostic-shape pin: the offending `u32` is carried
21947 // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
21948 // variant so the surfaced error message names the value the
21949 // author wrote (`":politicas :retries (47) exceeds the
21950 // mesh-policy ceiling …"`), not just the cap. Same
21951 // self-locating diagnostic shape every other typed-cap arm
21952 // on this surface carries
21953 // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
21954 // offending byte count verbatim).
21955 let mut s = three_member_spec();
21956 s.politicas.retries = Some(47);
21957 let err = s.validate().unwrap_err();
21958 assert!(
21959 matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
21960 "got {err:?}"
21961 );
21962 let msg = err.to_string();
21963 assert!(
21964 msg.contains("47"),
21965 ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
21966 );
21967 }
21968
21969 #[test]
21970 fn policy_retries_cap_is_aws_app_mesh_aligned() {
21971 // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
21972 // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
21973 // schema cap — the only upstream mesh-policy schema that
21974 // documents an explicit hard cap. Pinning the literal value
21975 // here surfaces a future drift (a relaxation to 20, a
21976 // tightening to 5) as a deliberate test edit, not a silent
21977 // contract narrowing.
21978 assert_eq!(POLICY_RETRIES_MAX, 10);
21979 }
21980
21981 #[test]
21982 fn rejects_circuit_breaker_zero_max_failures() {
21983 let mut s = three_member_spec();
21984 s.politicas.circuit_breaker = Some(CircuitBreaker {
21985 max_failures: 0,
21986 window: Duration::from_secs(60),
21987 });
21988 assert_eq!(
21989 s.validate().unwrap_err(),
21990 AplicacaoError::PolicyBreakerZeroFailures
21991 );
21992 }
21993
21994 #[test]
21995 fn rejects_circuit_breaker_max_failures_above_cap() {
21996 // The fail-before-pass-after pin: `1001` is structurally one
21997 // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
21998 // silently passed validate on every pre-gate codebase
21999 // because the typed slot's only check was the zero-floor
22000 // arm. The breaker-no-op vector only surfaced at the runtime
22001 // substrate (Envoy / Cilium L7 outlier-detection overlay)
22002 // far from the source caixa.lisp with no field naming the
22003 // offending policy.
22004 let mut s = three_member_spec();
22005 s.politicas.circuit_breaker = Some(CircuitBreaker {
22006 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
22007 window: Duration::from_secs(60),
22008 });
22009 assert_eq!(
22010 s.validate().unwrap_err(),
22011 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
22012 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
22013 }
22014 );
22015 }
22016
22017 #[test]
22018 fn rejects_circuit_breaker_max_failures_far_above_cap() {
22019 // The `u32::MAX` worst case — the four-billion-failure
22020 // threshold a typo (`(:max-failures 4294967295)`) or a
22021 // struct-literal copy-paste lands in the slot. Pin the cap
22022 // arm's coverage explicitly across the full `u32` overflow
22023 // so a future relaxation that drops the upper bound surfaces
22024 // here.
22025 let mut s = three_member_spec();
22026 s.politicas.circuit_breaker = Some(CircuitBreaker {
22027 max_failures: u32::MAX,
22028 window: Duration::from_secs(60),
22029 });
22030 assert_eq!(
22031 s.validate().unwrap_err(),
22032 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
22033 max_failures: u32::MAX,
22034 }
22035 );
22036 }
22037
22038 #[test]
22039 fn accepts_circuit_breaker_max_failures_at_cap() {
22040 // The boundary value — exactly
22041 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
22042 // cap is inclusive on the top edge, matching the
22043 // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
22044 // discipline on the sibling capped axes. Pin the boundary
22045 // explicitly so a future off-by-one tightening
22046 // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
22047 // surfaces here as a test failure rather than a silent
22048 // contract narrowing.
22049 let mut s = three_member_spec();
22050 s.politicas.circuit_breaker = Some(CircuitBreaker {
22051 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22052 window: Duration::from_secs(60),
22053 });
22054 s.validate()
22055 .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
22056 }
22057
22058 #[test]
22059 fn accepts_circuit_breaker_max_failures_typical_values() {
22060 // The documented production-playbook band positive-control
22061 // sweep — every value Hystrix / Istio / Envoy / Polly /
22062 // Resilience4j recommend (5..=50) must pass, plus a sweep
22063 // through the hyperscale band (100, 500, 1000) the cap
22064 // accepts. Pin the inclusive validated set explicitly so a
22065 // future tightening of the ceiling surfaces here.
22066 //
22067 // Clears the fixture's `:retries` (which is `Some(3)`) so this
22068 // per-axis sweep is pure: the sibling cross-axis
22069 // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
22070 // gate rejects any `max_failures <= retries` pair, so the
22071 // `max_failures = 1` boundary at the head of the sweep would
22072 // otherwise trip on the fixture-inherited retry policy rather
22073 // than the per-axis boundary this test names. Same discipline
22074 // the sibling per-axis `accepts_circuit_breaker_window_*`
22075 // sweeps take against the fixture's `:timeout` for the
22076 // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
22077 // cross-axis arm.
22078 for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
22079 let mut s = three_member_spec();
22080 s.politicas.retries = None;
22081 s.politicas.circuit_breaker = Some(CircuitBreaker {
22082 max_failures: n,
22083 window: Duration::from_secs(60),
22084 });
22085 s.validate()
22086 .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
22087 }
22088 }
22089
22090 #[test]
22091 fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
22092 // The cross-arm ordering pin: `0` is structurally outside
22093 // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
22094 // (cap), but the zero-floor diagnostic is the more
22095 // self-locating one (it directly names the omit-axis
22096 // remediation), so the validate gate must fire on zero
22097 // first. Same shape every other zero-then-shape ordering on
22098 // this surface uses
22099 // ([`AplicacaoError::PolicyRetriesZero`] then
22100 // [`AplicacaoError::PolicyRetriesExceedsCap`];
22101 // [`AplicacaoError::PolicyTimeoutZero`] then
22102 // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
22103 let mut s = three_member_spec();
22104 s.politicas.circuit_breaker = Some(CircuitBreaker {
22105 max_failures: 0,
22106 window: Duration::from_secs(60),
22107 });
22108 assert_eq!(
22109 s.validate().unwrap_err(),
22110 AplicacaoError::PolicyBreakerZeroFailures,
22111 "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
22112 );
22113 }
22114
22115 #[test]
22116 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
22117 // The cross-arm ordering pin between the cap and the
22118 // sibling `:window` gates (zero-window, canonical-window).
22119 // A breaker carrying both an over-cap `max_failures` AND a
22120 // structurally invalid window (zero, sub-ms) must surface
22121 // the cap diagnostic first — the cap arm is wired
22122 // immediately after the zero-failure arm and strictly
22123 // before the window arms, so the offending value the
22124 // diagnostic names matches the order the author would
22125 // discover the gates by reading top-to-bottom through
22126 // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
22127 // future refactor that reorders the arms surfaces here as a
22128 // test failure rather than a silent diagnostic regression.
22129 let mut s = three_member_spec();
22130 s.politicas.circuit_breaker = Some(CircuitBreaker {
22131 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
22132 window: Duration::ZERO,
22133 });
22134 assert_eq!(
22135 s.validate().unwrap_err(),
22136 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
22137 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
22138 },
22139 "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
22140 );
22141 }
22142
22143 #[test]
22144 fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
22145 // The diagnostic-shape pin: the offending `u32` is carried
22146 // verbatim into the
22147 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
22148 // variant so the surfaced error message names the value the
22149 // author wrote (`":politicas :circuit-breaker :max-failures
22150 // (50000) exceeds the mesh-policy ceiling …"`), not just
22151 // the cap. Same self-locating diagnostic shape every other
22152 // typed-cap arm on this surface carries
22153 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
22154 // offending retry count verbatim,
22155 // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
22156 // offending byte count verbatim).
22157 let mut s = three_member_spec();
22158 s.politicas.circuit_breaker = Some(CircuitBreaker {
22159 max_failures: 50_000,
22160 window: Duration::from_secs(60),
22161 });
22162 let err = s.validate().unwrap_err();
22163 assert!(
22164 matches!(
22165 err,
22166 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
22167 max_failures: 50_000
22168 }
22169 ),
22170 "got {err:?}"
22171 );
22172 let msg = err.to_string();
22173 assert!(
22174 msg.contains("50000"),
22175 ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
22176 );
22177 }
22178
22179 #[test]
22180 fn policy_breaker_max_failures_cap_pins_canonical_value() {
22181 // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
22182 // value at 1000 — an order of magnitude above every
22183 // documented production-playbook recommendation band
22184 // (Hystrix `requestVolumeThreshold` default 20, Istio
22185 // `outlierDetection.consecutive5xxErrors` default 5, Envoy
22186 // `outlier_detection.consecutive_5xx` default 5, Polly /
22187 // Resilience4j typical 5..=50) and below the
22188 // clearly-pathological "effectively no protection" floor
22189 // (10_000, 100_000, u32::MAX). Pinning the literal value
22190 // here surfaces a future drift (a relaxation to 10_000, a
22191 // tightening to 100) as a deliberate test edit, not a
22192 // silent contract narrowing.
22193 assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
22194 }
22195
22196 #[test]
22197 fn rejects_circuit_breaker_zero_window() {
22198 let mut s = three_member_spec();
22199 s.politicas.circuit_breaker = Some(CircuitBreaker {
22200 max_failures: 5,
22201 window: Duration::ZERO,
22202 });
22203 assert_eq!(
22204 s.validate().unwrap_err(),
22205 AplicacaoError::PolicyBreakerZeroWindow
22206 );
22207 }
22208
22209 #[test]
22210 fn rejects_zero_rate_limit() {
22211 let mut s = three_member_spec();
22212 s.politicas.rate_limit = Some(RateLimit {
22213 rate: 0,
22214 window: Duration::from_secs(1),
22215 });
22216 assert_eq!(
22217 s.validate().unwrap_err(),
22218 AplicacaoError::PolicyRateLimitZero
22219 );
22220 }
22221
22222 #[test]
22223 fn rejects_rate_limit_zero_window() {
22224 // `RateLimit { rate: 100, window: Duration::ZERO }` is
22225 // constructible programmatically (the typed `Duration` field
22226 // imposes no nonzero invariant) but renders through
22227 // `rate_limit_codec::render` as `"100/0s"` — a fragment the
22228 // codec's `parse` rejects as `unknown rate-limit window unit
22229 // "0s"`. Until this validate-time gate landed the typed slot
22230 // accepted the value silently and the round-trip break only
22231 // surfaced at deserialize time (potentially in a downstream
22232 // consumer that never re-validates). Pin the rejection at
22233 // `AplicacaoSpec::validate` so the typed slot's valid set
22234 // matches the codec's round-trippable set structurally.
22235 let mut s = three_member_spec();
22236 s.politicas.rate_limit = Some(RateLimit {
22237 rate: 100,
22238 window: Duration::ZERO,
22239 });
22240 assert_eq!(
22241 s.validate().unwrap_err(),
22242 AplicacaoError::PolicyRateLimitWindowNotCanonical {
22243 window: Duration::ZERO
22244 }
22245 );
22246 }
22247
22248 #[test]
22249 fn rejects_rate_limit_arbitrary_seconds_window() {
22250 // 45 seconds is a valid `Duration` but not one of the three
22251 // canonical rate-limit windows the codec round-trips
22252 // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
22253 // refuses on round-trip — same round-trip-break shape the
22254 // zero-window arm above pins, with a non-zero magnitude to
22255 // guard against a future "reject only zero" half-measure.
22256 let mut s = three_member_spec();
22257 let window = Duration::from_secs(45);
22258 s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
22259 assert_eq!(
22260 s.validate().unwrap_err(),
22261 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
22262 );
22263 }
22264
22265 #[test]
22266 fn rejects_rate_limit_two_minute_window() {
22267 // 120 seconds = 2 minutes is a "looks-canonical" but
22268 // not-canonical window: it's a clean integer multiple of the
22269 // minute unit, but the codec only round-trips the
22270 // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
22271 // A `Duration::from_secs(120)` window renders as `"100/120s"`
22272 // which the parser rejects. Pinning this case rules out a
22273 // future "accept any clean multiple of s/m/h" relaxation
22274 // that would silently break the codec contract.
22275 let mut s = three_member_spec();
22276 let window = Duration::from_secs(120);
22277 s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
22278 assert_eq!(
22279 s.validate().unwrap_err(),
22280 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
22281 );
22282 }
22283
22284 #[test]
22285 fn rejects_rate_limit_subsecond_window() {
22286 // A sub-second window (e.g. 500ms) is a valid `Duration` but
22287 // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
22288 // Pin the rejection so a future relaxation can't silently
22289 // admit fractional-second windows that the codec can't
22290 // round-trip.
22291 let mut s = three_member_spec();
22292 let window = Duration::from_millis(500);
22293 s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
22294 assert_eq!(
22295 s.validate().unwrap_err(),
22296 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
22297 );
22298 }
22299
22300 #[test]
22301 fn rejects_policy_rate_limit_above_cap() {
22302 // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
22303 // is structurally one past the cap and silently passed
22304 // validate on every pre-gate codebase because the typed slot's
22305 // only `rate` check was the zero-floor arm. The no-op-limiter
22306 // shape only surfaced at the runtime substrate (Envoy's
22307 // `local_rate_limit.token_bucket.max_tokens`, the future
22308 // Cilium L7 rate-limit overlay) far from the source caixa.lisp
22309 // with no field naming the offending policy.
22310 let mut s = three_member_spec();
22311 s.politicas.rate_limit = Some(RateLimit {
22312 rate: POLICY_RATE_LIMIT_MAX + 1,
22313 window: Duration::from_secs(1),
22314 });
22315 assert_eq!(
22316 s.validate().unwrap_err(),
22317 AplicacaoError::PolicyRateLimitExceedsCap {
22318 rate: POLICY_RATE_LIMIT_MAX + 1
22319 }
22320 );
22321 }
22322
22323 #[test]
22324 fn rejects_policy_rate_limit_far_above_cap() {
22325 // The `u32::MAX` worst case — the four-billion-token rate-limit
22326 // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
22327 // copy-paste lands in the slot. Pin the cap arm's coverage
22328 // explicitly across the full `u32` overflow so a future
22329 // relaxation that drops the upper bound surfaces here. Peer to
22330 // `rejects_policy_retries_far_above_cap` on the sibling
22331 // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
22332 // on the sibling `:max-failures` axis.
22333 let mut s = three_member_spec();
22334 s.politicas.rate_limit = Some(RateLimit {
22335 rate: u32::MAX,
22336 window: Duration::from_secs(1),
22337 });
22338 assert_eq!(
22339 s.validate().unwrap_err(),
22340 AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
22341 );
22342 }
22343
22344 #[test]
22345 fn accepts_policy_rate_limit_at_cap() {
22346 // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
22347 // must validate. The cap is inclusive on the top edge, matching
22348 // every other typed upper bound in this crate
22349 // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
22350 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
22351 // across all three canonical windows so a future off-by-one
22352 // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
22353 // window-conditional cap surfaces here as a test failure rather
22354 // than a silent contract narrowing.
22355 for secs in [1u64, 60, 3600] {
22356 let mut s = three_member_spec();
22357 s.politicas.rate_limit = Some(RateLimit {
22358 rate: POLICY_RATE_LIMIT_MAX,
22359 window: Duration::from_secs(secs),
22360 });
22361 s.validate().unwrap_or_else(|e| {
22362 panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
22363 });
22364 }
22365 }
22366
22367 #[test]
22368 fn accepts_policy_rate_limit_typical_values() {
22369 // The documented production-playbook recommendation band —
22370 // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
22371 // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
22372 // Enterprise ~1M per-hour. Every value in the validated set
22373 // must pass; pin the band explicitly so a future tightening
22374 // surfaces here.
22375 //
22376 // Clears the fixture's `:retries` (which is `Some(3)`) so this
22377 // per-axis sweep is pure: the sibling cross-axis
22378 // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
22379 // rejects any `rate <= retries` pair, so the `rate = 1`
22380 // boundary at the head of the sweep would otherwise trip on the
22381 // fixture-inherited retry policy rather than the per-axis
22382 // boundary this test names. Same discipline the sibling per-axis
22383 // `accepts_circuit_breaker_max_failures_typical_values` sweep
22384 // takes against the fixture's `:retries` for the peer cross-axis
22385 // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
22386 // arm.
22387 for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
22388 for secs in [1u64, 60, 3600] {
22389 let mut s = three_member_spec();
22390 s.politicas.retries = None;
22391 s.politicas.rate_limit = Some(RateLimit {
22392 rate,
22393 window: Duration::from_secs(secs),
22394 });
22395 s.validate().unwrap_or_else(|e| {
22396 panic!("rate={rate} window={secs}s must validate; got {e:?}")
22397 });
22398 }
22399 }
22400 }
22401
22402 #[test]
22403 fn policy_rate_limit_zero_takes_precedence_over_cap() {
22404 // The cross-arm ordering pin: `rate == 0` is structurally
22405 // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
22406 // (cap), but the zero-floor diagnostic is the more
22407 // self-locating one (it directly names the omit-axis
22408 // remediation). Pin the order so a future refactor that
22409 // reorders the arms surfaces here as a test failure rather
22410 // than a silent diagnostic regression. Same shape every other
22411 // zero-then-cap ordering on this surface uses
22412 // ([`AplicacaoError::PolicyRetriesZero`] then
22413 // [`AplicacaoError::PolicyRetriesExceedsCap`];
22414 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
22415 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
22416 let mut s = three_member_spec();
22417 s.politicas.rate_limit = Some(RateLimit {
22418 rate: 0,
22419 window: Duration::from_secs(1),
22420 });
22421 assert_eq!(
22422 s.validate().unwrap_err(),
22423 AplicacaoError::PolicyRateLimitZero,
22424 "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
22425 );
22426 }
22427
22428 #[test]
22429 fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
22430 // Two-axis-bad pin: rate above cap *and* window non-canonical.
22431 // The validate gate must fire on the rate cap first — the
22432 // amplification-shape (no-op limiter) diagnostic is the more
22433 // fundamental one; the window-canonical diagnostic is the
22434 // narrower codec-round-trip shape. Pin the ordering so a future
22435 // refactor that reorders the rate-then-window check arms
22436 // surfaces here as a test failure rather than a silent
22437 // diagnostic regression.
22438 let mut s = three_member_spec();
22439 s.politicas.rate_limit = Some(RateLimit {
22440 rate: POLICY_RATE_LIMIT_MAX + 1,
22441 window: Duration::from_secs(45),
22442 });
22443 assert_eq!(
22444 s.validate().unwrap_err(),
22445 AplicacaoError::PolicyRateLimitExceedsCap {
22446 rate: POLICY_RATE_LIMIT_MAX + 1
22447 },
22448 "above-cap rate must surface the cap diagnostic, not the window diagnostic"
22449 );
22450 }
22451
22452 #[test]
22453 fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
22454 // The diagnostic-shape pin: the offending `u32` is carried
22455 // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
22456 // variant so the surfaced error message names the value the
22457 // author wrote (`":politicas :rate-limit rate (5000000) exceeds
22458 // the mesh-policy ceiling …"`), not just the cap. Same
22459 // self-locating diagnostic shape every other typed-cap arm on
22460 // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
22461 // carries the offending retries count verbatim,
22462 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
22463 // the offending failure count verbatim).
22464 let mut s = three_member_spec();
22465 s.politicas.rate_limit = Some(RateLimit {
22466 rate: 5_000_000,
22467 window: Duration::from_secs(1),
22468 });
22469 let err = s.validate().unwrap_err();
22470 assert!(
22471 matches!(
22472 err,
22473 AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
22474 ),
22475 "got {err:?}"
22476 );
22477 let msg = err.to_string();
22478 assert!(
22479 msg.contains("5000000"),
22480 ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
22481 );
22482 }
22483
22484 #[test]
22485 fn policy_rate_limit_cap_pins_canonical_value() {
22486 // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
22487 // 1_000_000 — two-to-three orders of magnitude above every
22488 // documented production-playbook recommendation band (Envoy /
22489 // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
22490 // Gateway 10_000..=100_000 per-minute) and below the
22491 // clearly-pathological "paste-from-binary blob" floor
22492 // (100_000_000, u32::MAX). Pinning the literal value here
22493 // surfaces a future drift (a relaxation to 10_000_000, a
22494 // tightening to 100_000) as a deliberate test edit, not a
22495 // silent contract narrowing.
22496 assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
22497 }
22498
22499 #[test]
22500 fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
22501 // Both axes are invalid here: rate == 0 *and* window is
22502 // non-canonical. The validate gate must fire on rate first
22503 // (matching the existing `rejects_zero_rate_limit` ordering),
22504 // so the existing diagnostic continues to lead with the
22505 // simpler "zero rate" framing. Pinning the order of checks
22506 // so a future refactor that reorders the arms surfaces here
22507 // as a test failure rather than a silent diagnostic
22508 // regression.
22509 let mut s = three_member_spec();
22510 s.politicas.rate_limit = Some(RateLimit {
22511 rate: 0,
22512 window: Duration::from_secs(45),
22513 });
22514 assert_eq!(
22515 s.validate().unwrap_err(),
22516 AplicacaoError::PolicyRateLimitZero
22517 );
22518 }
22519
22520 #[test]
22521 fn rate_limit_canonical_windows_validate() {
22522 // The three canonical windows the codec round-trips
22523 // losslessly — 1s / 60s / 3600s — must all pass `validate()`
22524 // unchanged. Pin the full canonical set as a positive case
22525 // (the existing `rate_limit_round_trip_seconds` /
22526 // `rate_limit_round_trip_minutes` tests pin the
22527 // serialize-then-deserialize property at the codec layer; this
22528 // test pins the validate-side complement so a future tightening
22529 // of the canonical set — e.g. dropping `:hour` — surfaces here
22530 // as a test failure rather than a silent contract narrowing).
22531 for secs in [1u64, 60, 3600] {
22532 let mut s = three_member_spec();
22533 s.politicas.rate_limit = Some(RateLimit {
22534 rate: 100,
22535 window: Duration::from_secs(secs),
22536 });
22537 s.validate().expect("canonical window must validate");
22538 }
22539 }
22540
22541 #[test]
22542 fn rate_limit_validated_value_round_trips_through_codec() {
22543 // The structural property the validate gate enforces:
22544 // every `RateLimit` past `AplicacaoSpec::validate` round-trips
22545 // losslessly through the `rate_limit_codec` (serialize → string
22546 // → deserialize → equal value). Pin this end-to-end so a future
22547 // change to either side (the validate gate's accepted window
22548 // set, the codec's parse/render unit set) that breaks the
22549 // alignment surfaces here. The previous-state shape (typed
22550 // slot accepts arbitrary `Duration`, codec only round-trips
22551 // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
22552 // window — the validate gate now forecloses that.
22553 for secs in [1u64, 60, 3600] {
22554 let mut s = three_member_spec();
22555 s.politicas.rate_limit = Some(RateLimit {
22556 rate: 250,
22557 window: Duration::from_secs(secs),
22558 });
22559 s.validate().unwrap();
22560 let json = serde_json::to_string(&s.politicas).unwrap();
22561 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
22562 assert_eq!(
22563 back.rate_limit, s.politicas.rate_limit,
22564 "every validated :rate-limit must round-trip losslessly through the codec"
22565 );
22566 }
22567 }
22568
22569 #[test]
22570 fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
22571 // The hour-window canonical form (`"<n>/h"`) was missing from
22572 // the prior `rate_limit_round_trip_seconds` / `_minutes` test
22573 // pair. Now that the validate gate pins 3600s as part of the
22574 // canonical set, pin its serialize-side render shape too so
22575 // the third leg of the s/m/h tripod is explicitly tested.
22576 let policy = MeshPolicy {
22577 rate_limit: Some(RateLimit {
22578 rate: 10000,
22579 window: Duration::from_secs(3600),
22580 }),
22581 ..Default::default()
22582 };
22583 let json = serde_json::to_string(&policy).unwrap();
22584 assert!(
22585 json.contains("\"10000/h\""),
22586 "hour-window canonical form must render with `h` suffix (got: {json})"
22587 );
22588 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
22589 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
22590 }
22591
22592 #[test]
22593 fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
22594 // Pin the substrate-primitive [`RateLimit::canonical_unit`]
22595 // typed accessor's accepted-window set against the codec's
22596 // accepted set explicitly. A future addition to the codec
22597 // (e.g. accepting `:day`/`:week` as authoring units) must be
22598 // accompanied by a parallel addition here, and a regression
22599 // that drops one of the three canonical units from either
22600 // side surfaces as a test failure. The accessor is the
22601 // single source of truth for the canonical-window set —
22602 // [`AplicacaoSpec::validate_politicas`]'s canonical-window
22603 // gate and [`rate_limit_codec::render`]'s canonical arm both
22604 // read through it — this test enshrines that its
22605 // `Duration → Option<RateLimitUnit>` projection matches the
22606 // codec's parse / render arms' accepted-window set exactly.
22607 //
22608 // Predecessor: this pin previously read the module-private
22609 // free helper `is_canonical_rate_limit_window` — a delegate
22610 // that composed [`RateLimitUnit::from_window`] with `.is_some()`
22611 // — but the helper had no production consumers left after the
22612 // validate-gate migration onto [`RateLimit::canonical_unit`]
22613 // and was deleted; the closed-set arm-window bijection now
22614 // lives on exactly one typed dispatch on the substrate
22615 // primitive.
22616 let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
22617 RateLimit { rate: 1, window }.canonical_unit()
22618 };
22619 assert!(canonical_unit(Duration::from_secs(1)).is_some());
22620 assert!(canonical_unit(Duration::from_secs(60)).is_some());
22621 assert!(canonical_unit(Duration::from_secs(3600)).is_some());
22622 // Non-canonical windows the accessor rejects.
22623 assert!(canonical_unit(Duration::ZERO).is_none());
22624 assert!(canonical_unit(Duration::from_secs(2)).is_none());
22625 assert!(canonical_unit(Duration::from_secs(30)).is_none());
22626 assert!(canonical_unit(Duration::from_secs(120)).is_none());
22627 assert!(canonical_unit(Duration::from_secs(86400)).is_none());
22628 // Sub-second windows: even `Duration::from_millis(1000)` is
22629 // exactly 1s and accepted; `Duration::from_millis(500)` is
22630 // sub-second and rejected.
22631 assert!(canonical_unit(Duration::from_millis(1000)).is_some());
22632 assert!(canonical_unit(Duration::from_millis(500)).is_none());
22633 assert!(canonical_unit(Duration::from_millis(1500)).is_none());
22634 }
22635
22636 #[test]
22637 fn rate_limit_unit_table_projections_are_mutual_inverses() {
22638 // Bidirection pin against the closed-set typed enum
22639 // [`RateLimitUnit`] arm-table (the canonical
22640 // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
22641 // of the rate-limit unit surface reads from). The two
22642 // projection directions [`RateLimitUnit::from_suffix`] /
22643 // [`RateLimitUnit::window`] (str → Duration, exposed as one
22644 // typed dispatch through [`RateLimitUnit::window_from_suffix`])
22645 // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
22646 // (Duration → str, exposed as one typed dispatch through
22647 // [`RateLimit::canonical_unit`] composed with
22648 // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
22649 // codec's parse arm ([`rate_limit_codec::parse`] via
22650 // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
22651 // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
22652 // and the validate gate ([`AplicacaoSpec::validate_politicas`]
22653 // via [`RateLimit::canonical_unit`]) all key off. A future
22654 // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
22655 // sub-second window) is one variant + one arm per method on the
22656 // closed-set enum; the compiler-enforced exhaustiveness on
22657 // every consumer's `match self` arms picks it up by
22658 // construction. This pin enshrines that both projection
22659 // directions agree on every canonical arm row and neither
22660 // leaks a spurious entry the other doesn't recognize.
22661 //
22662 // Predecessor: this test previously read the two vestigial
22663 // module-private free helpers `rate_limit_window_unit` and
22664 // `rate_limit_window_from_unit` on the `Duration → &str` and
22665 // `&str → Duration` axes; the former was deleted after its
22666 // sole production consumer ([`rate_limit_codec::render`])
22667 // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
22668 // the latter is folded here into the substrate primitive
22669 // [`RateLimitUnit::window_from_suffix`] so both projection
22670 // directions live on the closed-set enum's arm-table.
22671 for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
22672 let window = super::RateLimitUnit::window_from_suffix(unit)
22673 .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
22674 assert_eq!(
22675 window,
22676 Duration::from_secs(secs),
22677 "unit {unit:?} must resolve to {secs}s"
22678 );
22679 let projected_suffix = RateLimit { rate: 1, window }
22680 .canonical_unit()
22681 .map(super::RateLimitUnit::as_suffix);
22682 assert_eq!(
22683 projected_suffix,
22684 Some(unit),
22685 "Duration({secs}s) must render as {unit:?} \
22686 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
22687 );
22688 }
22689 // Non-table units yield None on the `unit → Duration`
22690 // projection — a future `"d"` addition to the table would
22691 // flip this arm; today it pins the current three-row table's
22692 // rejection semantics.
22693 assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
22694 assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
22695 assert!(super::RateLimitUnit::window_from_suffix("").is_none());
22696 // Non-table Durations yield None on the `Duration → unit`
22697 // projection — pins that the two projections agree on the
22698 // "not in the table" semantic too, so a drift where the
22699 // parse-side accepts a value the render-side can't emit is
22700 // a build error at the two-arm pair, not a silent codec
22701 // round-trip break.
22702 let projected_suffix = |window: Duration| -> Option<&'static str> {
22703 RateLimit { rate: 1, window }
22704 .canonical_unit()
22705 .map(super::RateLimitUnit::as_suffix)
22706 };
22707 assert!(projected_suffix(Duration::from_secs(2)).is_none());
22708 assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
22709 assert!(projected_suffix(Duration::from_millis(1500)).is_none());
22710 }
22711
22712 #[test]
22713 fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
22714 // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
22715 // substrate-primitive `&str → Duration` associated method the
22716 // codec's parse arm ([`rate_limit_codec::parse`]) now routes
22717 // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
22718 // to the same [`Duration`] the two-step composition
22719 // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
22720 // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
22721 // `"MIN"`) must project to [`None`] on both paths. A future
22722 // implementation of `window_from_suffix` that took a shortcut
22723 // through a per-suffix `match` table (bypassing the arm-table's
22724 // `Self::from_suffix` scan and the arm-table's `Self::window`
22725 // dispatch) would silently split the accept-set — the parse
22726 // arm would accept a suffix the enum's arm-table doesn't know,
22727 // or reject a suffix the enum's arm-table does; this pin
22728 // surfaces that drift at caixa-core build time rather than at a
22729 // downstream serde round-trip audit on a live `MeshPolicy`.
22730 //
22731 // Same byte-parity discipline the sibling
22732 // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
22733 // pin carries on the peer `Duration → RateLimitUnit` axis via
22734 // [`RateLimit::canonical_unit`], and the peer
22735 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
22736 // carries on the bidirectional arm-table axis — extended here
22737 // onto the fifth (and last unlifted) projection axis on the
22738 // closed-set enum's arm-table.
22739 let composition = |suffix: &str| -> Option<Duration> {
22740 super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
22741 };
22742 for suffix in ["s", "m", "h"] {
22743 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
22744 let via_composition = composition(suffix);
22745 assert_eq!(
22746 via_method, via_composition,
22747 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
22748 from_suffix({suffix:?}).map(window) — the substrate-primitive \
22749 method must delegate to the arm-table's two typed dispatches, \
22750 not shortcut through a per-suffix match table"
22751 );
22752 assert!(
22753 via_method.is_some(),
22754 "canonical suffix {suffix:?} must resolve to Some(Duration) via \
22755 RateLimitUnit::window_from_suffix"
22756 );
22757 }
22758 for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
22759 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
22760 let via_composition = composition(suffix);
22761 assert_eq!(
22762 via_method, via_composition,
22763 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
22764 from_suffix({suffix:?}).map(window) on the non-arm rejection \
22765 axis too"
22766 );
22767 assert!(
22768 via_method.is_none(),
22769 "non-arm suffix {suffix:?} must project to None via \
22770 RateLimitUnit::window_from_suffix — a future extension that \
22771 accepted this suffix without a corresponding arm on the enum \
22772 would split the codec's parse-accepted set from the enum's \
22773 arm-table"
22774 );
22775 }
22776 // And the codec's parse arm now reads through this method: a
22777 // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
22778 // the same `Duration` the method returns for its unit, closing
22779 // the two-consumer drift surface (the codec's parse arm and the
22780 // enum's arm-table) with one typed dispatch on the substrate
22781 // primitive.
22782 for suffix in ["s", "m", "h"] {
22783 let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
22784 let mp: MeshPolicy = serde_json::from_str(&wire)
22785 .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
22786 let parsed = mp.rate_limit().expect("rate_limit payload present");
22787 let via_method = super::RateLimitUnit::window_from_suffix(suffix)
22788 .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
22789 assert_eq!(
22790 parsed.window(),
22791 via_method,
22792 "codec parse arm on {wire:?} must resolve the window through \
22793 RateLimitUnit::window_from_suffix, not a divergent path"
22794 );
22795 }
22796 }
22797
22798 #[test]
22799 fn rate_limit_unit_all_enumerates_every_arm_once() {
22800 // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
22801 // enumerate every arm of the closed-set enum exactly once, in
22802 // the canonical shortest-to-longest window order (Second before
22803 // Minute before Hour) — the same order the sibling
22804 // [`crate::supervisor::RestartStrategy`] /
22805 // [`crate::supervisor::RestartPolicy`] /
22806 // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
22807 // typed enums carry (the arm declared first is the arm listed
22808 // first). A future variant addition that extends the enum
22809 // without appending to [`RateLimitUnit::ALL`] leaves the
22810 // exhaustive iteration surface silently short one arm — the
22811 // codec's parse arm would then reject the new suffix even
22812 // though the enum knows it. This pin closes the drift.
22813 assert_eq!(
22814 super::RateLimitUnit::ALL,
22815 &[
22816 super::RateLimitUnit::Second,
22817 super::RateLimitUnit::Minute,
22818 super::RateLimitUnit::Hour,
22819 ],
22820 "RateLimitUnit::ALL must enumerate every arm exactly once, \
22821 in canonical shortest-to-longest window order"
22822 );
22823 }
22824
22825 #[test]
22826 fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
22827 // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
22828 // every arm's [`RateLimitUnit::as_suffix`] output must parse
22829 // back through [`RateLimitUnit::from_suffix`] to the same
22830 // variant. A future arm addition that lands `as_suffix` but
22831 // forgets `from_suffix` (`from_suffix` iterates
22832 // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
22833 // is the load-bearing carrier of the round-trip; the sibling
22834 // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
22835 // the `ALL` half) trips here at caixa-core build time rather
22836 // than surfacing as a codec round-trip miss (a `render` emit
22837 // that lands a suffix the paired `parse` cannot decode).
22838 for unit in super::RateLimitUnit::ALL {
22839 let suffix = unit.as_suffix();
22840 let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
22841 panic!(
22842 "RateLimitUnit::from_suffix({suffix:?}) must accept every \
22843 RateLimitUnit::as_suffix output — got None for {unit:?}"
22844 )
22845 });
22846 assert_eq!(
22847 parsed, *unit,
22848 "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
22849 must return RateLimitUnit::{unit:?}"
22850 );
22851 }
22852 }
22853
22854 #[test]
22855 fn rate_limit_unit_from_window_and_window_round_trip() {
22856 // Total round-trip pin on the `(from_window, window)` pair:
22857 // every arm's [`RateLimitUnit::window`] output must parse back
22858 // through [`RateLimitUnit::from_window`] to the same variant.
22859 // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
22860 // on the peer `Duration` axis — the two round-trip pins
22861 // together enshrine that both projections of the typed
22862 // canonical-unit bijection are total on the arm-set.
22863 for unit in super::RateLimitUnit::ALL {
22864 let window = unit.window();
22865 let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
22866 panic!(
22867 "RateLimitUnit::from_window({window:?}) must accept every \
22868 RateLimitUnit::window output — got None for {unit:?}"
22869 )
22870 });
22871 assert_eq!(
22872 parsed, *unit,
22873 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
22874 must return RateLimitUnit::{unit:?}"
22875 );
22876 }
22877 }
22878
22879 #[test]
22880 fn rate_limit_unit_from_window_accessor_is_const_fn() {
22881 // Fail-before-pass-after pin: witnesses the
22882 // [`RateLimitUnit::from_window`] `const`-eval posture via a
22883 // `const fn` wrapper `from_window_via_const_fn(window: Duration)
22884 // -> Option<RateLimitUnit>` whose body calls
22885 // `RateLimitUnit::from_window(window)`, well-formed only when
22886 // the callee is itself `const fn` (any future downgrade to
22887 // non-`const` fails at caixa-core build time with E0015 `cannot
22888 // call non-const function`, strictly stronger than a runtime
22889 // `assert!`, side-stepping the destructor-in-const restriction
22890 // that blocks direct `const _: Option<RateLimitUnit> =
22891 // RateLimitUnit::from_window(...)` items on `Duration`'s
22892 // carrier). The runtime body sweeps every closed-set
22893 // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
22894 // rejection sample (`Duration::from_millis(500)` sub-second
22895 // residue) and asserts the wrapped and direct dispatches agree
22896 // — a violation means the wrapper stopped compiling under a
22897 // future `const`-posture downgrade, or the reverse resolver's
22898 // arm-set silently split from the peer `Self::window` emitter's
22899 // arm-set. Peer of the sibling
22900 // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
22901 // (152c868) /
22902 // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
22903 // (152c868) /
22904 // [`entrada_port_accessor_is_const_fn`] (bafa004) /
22905 // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
22906 // `const`-eval-surface pins on the peer M2 / M3 substrate-
22907 // primitive `Copy`-return accessor axes, extended onto the
22908 // reverse `Duration → RateLimitUnit` projection axis on the
22909 // M3 mesh-slot rate-limit closed-set typed enum.
22910 const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
22911 super::RateLimitUnit::from_window(window)
22912 }
22913 for unit in super::RateLimitUnit::ALL {
22914 let window = unit.window();
22915 let via_wrapper = from_window_via_const_fn(window);
22916 let direct = super::RateLimitUnit::from_window(window);
22917 assert_eq!(
22918 via_wrapper, direct,
22919 "RateLimitUnit::from_window({window:?}) via const fn \
22920 wrapper must agree with direct dispatch for {unit:?}"
22921 );
22922 assert_eq!(
22923 via_wrapper,
22924 Some(*unit),
22925 "RateLimitUnit::from_window({window:?}) via const fn \
22926 wrapper must return Some({unit:?}) for the peer \
22927 window() output"
22928 );
22929 }
22930 assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
22931 assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
22932 }
22933
22934 #[test]
22935 fn rate_limit_unit_from_window_composes_through_window_accessor() {
22936 // Composition-witness pin on the routing-through-peer discipline:
22937 // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
22938 // through the peer `pub const fn` [`RateLimitUnit::window`]
22939 // canonical-`Duration` projection rather than a hand-authored
22940 // per-arm second-magnitude literal — a future arm-magnitude edit
22941 // on the sibling `window()` accessor (a `Second → 2s` typo, a
22942 // `Hour → 3599s` off-by-one) must therefore reach this reverse
22943 // resolver by construction. A pin that hard-coded the three
22944 // second-magnitudes here would silently split from the peer
22945 // emitter on any such edit; instead, this pin asserts the
22946 // composition invariant `from_window(u.window()) == Some(u)`
22947 // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
22948 // arm — a violation means either the peer `Self::window`
22949 // accessor drifted (breaking every downstream consumer that
22950 // reads through it), or the reverse resolver stopped routing
22951 // through the peer (introducing a hand-authored literal that
22952 // silently disagrees with the emitter). Either failure is a
22953 // caixa-core-build-time surface, not a downstream renderer
22954 // round-trip regression.
22955 //
22956 // Peer of the sibling
22957 // [`crate::render::assert_str_reexport_identity`] discipline on
22958 // the substrate-primitive `&'static str` re-export axis and the
22959 // [`rate_limit_unit_from_window_and_window_round_trip`]
22960 // round-trip pin on the peer projection direction; extends the
22961 // one-canonical-dispatch-per-projection discipline onto the
22962 // reverse-resolver's per-arm probe axis.
22963 for unit in super::RateLimitUnit::ALL {
22964 let window_via_peer = unit.window();
22965 let resolved = super::RateLimitUnit::from_window(window_via_peer);
22966 assert_eq!(
22967 resolved,
22968 Some(*unit),
22969 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
22970 must return Some({unit:?}) — the reverse resolver's per-arm \
22971 probes must route through the peer `Self::window` accessor \
22972 so any future arm-magnitude edit reaches both projection \
22973 directions by construction"
22974 );
22975 }
22976 }
22977
22978 #[test]
22979 fn rate_limit_canonical_unit_accessor_is_const_fn() {
22980 // Fail-before-pass-after pin: witnesses the
22981 // [`RateLimit::canonical_unit`] `const`-eval posture via a
22982 // `const fn` wrapper
22983 // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
22984 // whose body calls `rl.canonical_unit()`, well-formed only when
22985 // the callee is itself `const fn` (any future downgrade to
22986 // non-`const` fails at caixa-core build time with E0015 `cannot
22987 // call non-const method`). The runtime body sweeps every
22988 // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
22989 // constructs a typed [`RateLimit`] with the peer `Self::window`
22990 // canonical `Duration`, then asserts both the wrapper and the
22991 // direct dispatch agree and both return `Some(unit)`. Composes
22992 // with the sibling
22993 // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
22994 // typed [`RateLimit`] projection layer's `const`-posture is
22995 // load-bearing on the reverse resolver's `const`-posture, and
22996 // both must migrate together (a downgrade of either surface
22997 // splits the paired `const`-eval-surface pass on the M3
22998 // mesh-slot rate-limit `Duration ↔ Self` bijection).
22999 const fn canonical_unit_via_const_fn(
23000 rl: &super::RateLimit,
23001 ) -> Option<super::RateLimitUnit> {
23002 rl.canonical_unit()
23003 }
23004 for unit in super::RateLimitUnit::ALL {
23005 let rl = super::RateLimit {
23006 rate: 1,
23007 window: unit.window(),
23008 };
23009 let via_wrapper = canonical_unit_via_const_fn(&rl);
23010 let direct = rl.canonical_unit();
23011 assert_eq!(
23012 via_wrapper, direct,
23013 "RateLimit::canonical_unit() via const fn wrapper must \
23014 agree with direct dispatch for {unit:?}"
23015 );
23016 assert_eq!(
23017 via_wrapper,
23018 Some(*unit),
23019 "RateLimit::canonical_unit() via const fn wrapper must \
23020 return Some({unit:?}) for a RateLimit whose window is \
23021 the peer RateLimitUnit::{unit:?}.window() output"
23022 );
23023 }
23024 }
23025
23026 #[test]
23027 fn rate_limit_unit_projections_are_pairwise_distinct() {
23028 // Distinctness pin: [`RateLimitUnit::as_suffix`] and
23029 // [`RateLimitUnit::window`] outputs must be pairwise distinct
23030 // across every arm — an accidental copy-paste flip that
23031 // reroutes one arm's suffix or window to also match another
23032 // silently collapses two arms onto one, so
23033 // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
23034 // (both using `find` on `Self::ALL`) would return whichever
23035 // arm the linear scan lands on first — a match-arm-ordering-
23036 // dependent outcome the closed-set typed-enum shape is meant
23037 // to rule out structurally. Peer of the sibling
23038 // `caixa_kind_wire_consts_are_pairwise_distinct` /
23039 // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
23040 // other closed-set typed-enum discriminator axes.
23041 let all = super::RateLimitUnit::ALL;
23042 for (i, a) in all.iter().enumerate() {
23043 for (j, b) in all.iter().enumerate() {
23044 if i != j {
23045 assert_ne!(
23046 a.as_suffix(),
23047 b.as_suffix(),
23048 "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
23049 must be distinct — a collision silently collapses two \
23050 arms onto one under from_suffix's linear scan"
23051 );
23052 assert_ne!(
23053 a.window(),
23054 b.window(),
23055 "RateLimitUnit::{a:?}.window() and {b:?}.window() \
23056 must be distinct — a collision silently collapses two \
23057 arms onto one under from_window's linear scan"
23058 );
23059 }
23060 }
23061 }
23062 }
23063
23064 #[test]
23065 fn rate_limit_unit_display_routes_through_as_suffix() {
23066 // Route pin: [`std::fmt::Display`] must byte-equal
23067 // [`RateLimitUnit::as_suffix`] on every arm — the single
23068 // source of truth for the canonical suffix. A future
23069 // reimplementation that hand-rolls the arms instead of
23070 // delegating to [`RateLimitUnit::as_suffix`] would silently
23071 // desynchronize `format!("{u}")` from the codec's parse arm
23072 // (which uses `as_suffix` to compare suffixes). Peer of the
23073 // sibling `caixa_kind_display_routes_through_as_str_helper` /
23074 // `placement_strategy_display_routes_through_as_str_helper`
23075 // pins on the peer closed-set typed-enum Display axes.
23076 for unit in super::RateLimitUnit::ALL {
23077 assert_eq!(
23078 unit.to_string(),
23079 unit.as_suffix(),
23080 "RateLimitUnit::{unit:?} Display must route through \
23081 as_suffix (single source of truth: the canonical suffix \
23082 the codec parses and renders)"
23083 );
23084 }
23085 }
23086
23087 #[test]
23088 fn rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor() {
23089 // Fail-before-pass-after byte-parity pin on the lifted
23090 // `impl AsRef<str> for RateLimitUnit` — asserts the standard-
23091 // library trait impl and the substrate-primitive
23092 // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
23093 // resolve to the same `&str` per instance across the three-arm
23094 // closed set, so any future silent detour that routes the impl
23095 // through a divergent projection (a per-arm inline
23096 // `match self { RateLimitUnit::Second => "s", … }` re-inlining
23097 // that opens a compile-time link to the un-lifted arm-literal,
23098 // a swap onto the second-magnitude
23099 // [`super::RateLimitUnit::window`] axis that would collide the
23100 // canonical-suffix / token-bucket-refill two-axis split) trips
23101 // at caixa-core test time under `PartialEq` rather than at a
23102 // downstream `impl AsRef<str>`-bound consumer's silent split.
23103 // Sweeps every one of the three arms
23104 // [`super::RateLimitUnit::ALL`] carries so no arm's projection
23105 // is covered only by the sibling `Display` path. Peer of the
23106 // sibling
23107 // `placement_strategy_as_ref_str_routes_through_as_str_accessor`
23108 // (d86edd2) on the M3 mesh-placement closed-set typed enum,
23109 // and the peer
23110 // [`crate::kind::tests::caixa_kind_as_ref_str_routes_through_as_str_accessor`]
23111 // (cd2091f) pin on the top-level closed-set typed
23112 // discriminator — the pins together close the substrate
23113 // primitive's `AsRef<str>` projection axis on every closed-set
23114 // typed enum with a `fmt::Display` surface across the M2 / M3
23115 // typed slots plus the top-level `:kind` + `:versao`
23116 // primitives.
23117 for &unit in super::RateLimitUnit::ALL {
23118 assert_eq!(
23119 <super::RateLimitUnit as AsRef<str>>::as_ref(&unit),
23120 unit.as_suffix(),
23121 "AsRef<str> impl on RateLimitUnit::{unit:?} must \
23122 byte-equal RateLimitUnit::as_suffix on the same \
23123 instance — divergence signals a silent detour off the \
23124 substrate-primitive accessor"
23125 );
23126 }
23127 }
23128
23129 #[test]
23130 fn rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor() {
23131 // Fail-before-pass-after byte-parity pin on the three-path
23132 // convergence discipline the M3 `:politicas :rate-limit`
23133 // canonical-unit primitive now carries on the `&str`-projection
23134 // axis: `<RateLimitUnit as AsRef<str>>::as_ref(&v)` (the newly
23135 // lifted impl), `format!("{v}")` (the pre-existing
23136 // [`fmt::Display`] impl), and `v.as_suffix()` (the substrate-
23137 // primitive `pub const fn` accessor both trait impls delegate
23138 // through) must resolve to the same byte-string on every
23139 // instance across the three-arm closed set. Refuses any future
23140 // divergence between the two trait impls (a stray
23141 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
23142 // rather than delegating through the shared accessor; a
23143 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
23144 // literal cascade) that would silently split the two
23145 // projection paths of the same closed-set typed enum. Mirrors
23146 // the sibling three-path-convergence discipline the peer
23147 // [`super::PlacementStrategy`] typed enum carries
23148 // (`placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
23149 // d86edd2), the peer [`crate::CaixaKind`] triple
23150 // (`caixa_kind_as_ref_str_routes_through_display_via_shared_accessor`,
23151 // cd2091f), and the [`crate::CaixaVersion`] typed newtype
23152 // triple (`caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
23153 // 16d5c7e).
23154 for &unit in super::RateLimitUnit::ALL {
23155 let via_as_ref: &str = <super::RateLimitUnit as AsRef<str>>::as_ref(&unit);
23156 let via_display: String = format!("{unit}");
23157 let via_accessor: &str = unit.as_suffix();
23158 assert_eq!(via_as_ref, via_accessor);
23159 assert_eq!(via_display, via_accessor);
23160 assert_eq!(via_as_ref, via_display.as_str());
23161 }
23162 }
23163
23164 #[test]
23165 fn rate_limit_unit_from_window_rejects_non_canonical() {
23166 // Rejection pin on the parser's accept-set: any Duration
23167 // outside the three-arm [`RateLimitUnit::window`] output set
23168 // (sub-second residue, or a second-magnitude outside `{1, 60,
23169 // 3600}`) must return `None`. A future accidental widening of
23170 // the accept-set (rounding down sub-second residue to the
23171 // nearest arm, admitting `Duration::from_secs(30)` as a
23172 // half-minute unit) would silently drift the parser's accept-
23173 // set from the emitter's — a validated slot with a
23174 // non-canonical window would then round-trip through the
23175 // codec to a canonical form the author never wrote.
23176 assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
23177 assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
23178 assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
23179 assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
23180 assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
23181 assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
23182 assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
23183 }
23184
23185 #[test]
23186 fn rate_limit_unit_from_suffix_rejects_unknown() {
23187 // Rejection pin on the suffix parser's accept-set: any string
23188 // outside the three-arm [`RateLimitUnit::as_suffix`] output
23189 // set must return `None`. Peer of the sibling
23190 // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
23191 // the [`crate::CaixaKind`] `from_wire` accept-set.
23192 for bad in [
23193 "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
23194 " s",
23195 ] {
23196 assert!(
23197 super::RateLimitUnit::from_suffix(bad).is_none(),
23198 "RateLimitUnit::from_suffix({bad:?}) must return None — the \
23199 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
23200 outputs"
23201 );
23202 }
23203 }
23204
23205 #[test]
23206 fn rate_limit_unit_try_from_str_routes_through_from_suffix_accessor() {
23207 // Fail-before-pass-after byte-parity pin on the newly lifted
23208 // `impl TryFrom<&str> for RateLimitUnit` — asserts the standard-
23209 // library trait impl and the substrate-primitive
23210 // [`super::RateLimitUnit::from_suffix`] `Option<Self>` accessor
23211 // resolve to the same three-arm accept-set across every arm the
23212 // exhaustive [`super::RateLimitUnit::ALL`] slice enumerates. Any
23213 // future silent detour that routes the trait impl through a
23214 // divergent projection (a per-arm inline
23215 // `match s { "s" => Ok(Self::Second), … }` re-inlining that
23216 // opens a compile-time link to the un-lifted arm-literal, a
23217 // silent case-fold that admits `"S"` / `"M"` / `"H"` and would
23218 // collide the canonical-suffix accept-set the codec's parse arm
23219 // dispatches on) trips at caixa-core test time under
23220 // `assert_eq!` rather than at a downstream `impl TryFrom<&str>`-
23221 // bound consumer's silent split. Sweeps every one of the three
23222 // arms [`super::RateLimitUnit::ALL`] carries so no arm's
23223 // projection is covered only by the sibling method-named
23224 // `from_suffix` path. Peer of the sibling
23225 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
23226 // (3c83606),
23227 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
23228 // (bf33136), and
23229 // `placement_strategy_try_from_str_routes_through_from_wire_accessor`
23230 // (6fd00cd) — extends the trait-idiomatic reverse-projection
23231 // axis onto the third M3-mesh-primitive-defining slot enum on
23232 // the caixa surface (the `:politicas :rate-limit` unit-suffix
23233 // closed set the caixa-mesh renderer keys off end-to-end).
23234 for &unit in super::RateLimitUnit::ALL {
23235 let suffix = unit.as_suffix();
23236 assert_eq!(
23237 <super::RateLimitUnit as TryFrom<&str>>::try_from(suffix),
23238 Ok(unit),
23239 "TryFrom<&str> impl on RateLimitUnit must round-trip \
23240 RateLimitUnit::{unit:?}.as_suffix() = {suffix:?} back to \
23241 Ok(RateLimitUnit::{unit:?}) — divergence from \
23242 RateLimitUnit::from_suffix signals a silent detour off \
23243 the substrate-primitive accessor"
23244 );
23245 assert_eq!(
23246 <super::RateLimitUnit as TryFrom<&str>>::try_from(suffix).ok(),
23247 super::RateLimitUnit::from_suffix(suffix),
23248 "TryFrom<&str> ok()-projection on {suffix:?} must \
23249 byte-equal RateLimitUnit::from_suffix on the same input"
23250 );
23251 }
23252 }
23253
23254 #[test]
23255 fn rate_limit_unit_try_from_str_rejects_unknown_byte_strings() {
23256 // Rejection witness on the `impl TryFrom<&str> for RateLimitUnit`
23257 // — sweeps a candidate set of byte-strings outside the three-arm
23258 // canonical-suffix wire accept-set the sibling
23259 // [`super::RateLimitUnit::as_suffix`] emits and asserts every
23260 // one lands on `Err(())`, so a future accidental widening of the
23261 // trait impl's accept-set (a stray additional
23262 // `_ if s.eq_ignore_ascii_case("s") => Ok(…)` case-fold path, a
23263 // silent inclusion of a long-form English rebrand of the
23264 // canonical suffix like `"second"` / `"minute"` / `"hour"` that
23265 // would collide the one-letter-suffix discipline the sibling
23266 // [`super::RateLimitUnit::from_suffix`] carries, a silent
23267 // acceptance of the `"1s"` / `"1m"` / `"1h"` full-rate-limit
23268 // shape that would collide the codec-composed `<n>/<unit>` axis
23269 // onto the unit-suffix axis) trips at caixa-core test time. The
23270 // candidate set includes the empty string, whitespace-only
23271 // padding, uppercase rebrand candidates, long-form English
23272 // rebrand candidates (`"second"`, `"minute"`, `"hour"`),
23273 // trailing/leading-whitespace-padded canonical suffixes,
23274 // sub-second and multi-day trajectory-item candidates
23275 // (`"ms"`, `"d"`, `"week"`), digits-prefixed shapes that would
23276 // collide with the `<n>/<unit>` parent codec, the quoted-shape
23277 // (`"\"s\""`) that would signal a stray serde-quote survival,
23278 // and the `"?"` sentinel. Peer of the sibling
23279 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
23280 // (3c83606) rejection witness, and
23281 // `placement_strategy_try_from_str_rejects_unknown_byte_strings`
23282 // (6fd00cd).
23283 let rejected: &[&str] = &[
23284 "", " ", "\n", "\t", "S", "M", "H", "s ", " s", "m ", " h", "s\n", "second", "minute",
23285 "hour", "sec", "min", "hr", "d", "ms", "ns", "us", "week", "1s", "1m", "1h", "100/s",
23286 "s/", "?", "\"s\"",
23287 ];
23288 for &input in rejected {
23289 assert_eq!(
23290 <super::RateLimitUnit as TryFrom<&str>>::try_from(input),
23291 Err(()),
23292 "TryFrom<&str> impl on RateLimitUnit must reject the \
23293 non-suffix byte-string {input:?} — silent acceptance \
23294 signals an accept-set widening off the paired \
23295 RateLimitUnit::from_suffix resolver"
23296 );
23297 }
23298 }
23299
23300 #[test]
23301 fn rate_limit_unit_try_from_str_and_from_suffix_partition_the_accept_set() {
23302 // Cross-axis partition pin on the two `str → Option<Self>` /
23303 // `str → Result<Self, ()>` projections on
23304 // [`super::RateLimitUnit`]: the trait-idiomatic
23305 // [`TryFrom<&str>`] axis (newly lifted) and the method-named
23306 // [`super::RateLimitUnit::from_suffix`] axis (pre-existing) must
23307 // partition every input into the same accept-set / reject-set
23308 // — a `TryFrom<&str>` `Ok(v)` outcome iff `from_suffix` returns
23309 // `Some(v)`, and a `TryFrom<&str>` `Err(())` outcome iff
23310 // `from_suffix` returns `None`. Sweeps a mixed input set of
23311 // canonical accepts + rejections so any future divergence
23312 // between the two projection paths (a hand-rolled `try_from`
23313 // rewrite that no longer routes through `from_suffix`, a
23314 // hypothetical `from_suffix` widening that admits a byte-string
23315 // the trait impl still rejects) surfaces here at caixa-core
23316 // test time rather than at a downstream consumer's silent
23317 // split. Peer of the sibling
23318 // `wit_shape_try_from_str_and_from_wire_partition_the_accept_set`
23319 // (5472902) cross-axis partition pin on the sibling M3-mesh-
23320 // primitive closed-set typed enum.
23321 let inputs: &[&str] = &[
23322 "s", "m", "h", "", " ", "S", "second", "d", "ms", "1s", "?", "\"s\"", "sec",
23323 ];
23324 for &input in inputs {
23325 let via_try_from: Option<super::RateLimitUnit> =
23326 <super::RateLimitUnit as TryFrom<&str>>::try_from(input).ok();
23327 let via_from_suffix: Option<super::RateLimitUnit> =
23328 super::RateLimitUnit::from_suffix(input);
23329 assert_eq!(
23330 via_try_from, via_from_suffix,
23331 "TryFrom<&str> and from_suffix must partition the \
23332 accept-set identically on input {input:?} — got \
23333 TryFrom = {via_try_from:?}, from_suffix = {via_from_suffix:?}"
23334 );
23335 }
23336 }
23337
23338 #[test]
23339 fn rate_limit_unit_from_into_static_str_routes_through_as_suffix_accessor() {
23340 // Fail-before-pass-after byte-parity pin on the newly lifted
23341 // `impl From<RateLimitUnit> for &'static str` — asserts the
23342 // standard-library trait impl and the substrate-primitive
23343 // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
23344 // resolve to the same three-arm canonical-suffix emit-set across
23345 // every arm the exhaustive [`super::RateLimitUnit::ALL`] slice
23346 // enumerates. Any future silent detour that routes the trait
23347 // impl through a divergent projection (a per-arm inline
23348 // `match unit { Second => "s", … }` re-inlining that opens a
23349 // compile-time link to the un-lifted arm-literal outside the
23350 // paired [`super::RateLimitUnit::as_suffix`] dispatch, a swap
23351 // onto the second-magnitude [`super::RateLimitUnit::window`]
23352 // axis that would collide the canonical-suffix /
23353 // token-bucket-refill two-axis split) trips at caixa-core test
23354 // time under `assert_eq!` rather than at a downstream
23355 // `impl Into<&'static str>`-bound consumer's silent split.
23356 // Sweeps every one of the three arms
23357 // [`super::RateLimitUnit::ALL`] carries so no arm's projection
23358 // is covered only by the sibling method-named `as_suffix` /
23359 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
23360 // `<&'static str as From<RateLimitUnit>>::from` output in three
23361 // `const`-shape bindings against the paired
23362 // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor to
23363 // make the `'static` lifetime promise a build-time invariant —
23364 // a future accidental downgrade of any of the three arms'
23365 // inline canonical-suffix byte-strings to a non-`&'static str`
23366 // (a `String::leak()`-produced return, a `Box::leak`-cast, an
23367 // intermediate lifetime-erasing helper) trips at caixa-core
23368 // build time rather than at a downstream `'static`-bound
23369 // consumer.
23370 //
23371 // Peer of the sibling
23372 // [`crate::supervisor::tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
23373 // (523157d),
23374 // [`crate::supervisor::tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
23375 // (9fb37d0),
23376 // [`crate::kind::tests::caixa_kind_from_into_static_str_routes_through_as_str_accessor`]
23377 // (edb827b),
23378 // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_routes_through_as_str_accessor`]
23379 // (c189a6f),
23380 // [`tests::placement_strategy_from_into_static_str_routes_through_as_str_accessor`]
23381 // (afa3562), and
23382 // [`tests::wit_shape_from_into_static_str_routes_through_as_str_accessor`]
23383 // (56998ec) pins on the sibling closed-set typed-enum forward-
23384 // projection axes — extends the trait-idiomatic forward-
23385 // projection axis onto the seventh closed-set fieldless typed
23386 // enum on the caixa surface (the third M3-mesh-primitive-
23387 // defining slot enum, the `:politicas :rate-limit`
23388 // canonical-suffix axis the caixa-mesh renderer keys off end-
23389 // to-end for per-Aplicacao Envoy
23390 // `local_rate_limit.token_bucket.fill_interval` overlay
23391 // emission).
23392 const SECOND: &str = super::RateLimitUnit::Second.as_suffix();
23393 const MINUTE: &str = super::RateLimitUnit::Minute.as_suffix();
23394 const HOUR: &str = super::RateLimitUnit::Hour.as_suffix();
23395 for &unit in super::RateLimitUnit::ALL {
23396 let via_trait: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
23397 let via_method: &'static str = unit.as_suffix();
23398 assert_eq!(
23399 via_trait, via_method,
23400 "From<RateLimitUnit> for &'static str impl must \
23401 round-trip RateLimitUnit::{unit:?} to the same \
23402 canonical-suffix byte-string RateLimitUnit::as_suffix \
23403 returns — divergence signals a silent detour off the \
23404 substrate-primitive accessor"
23405 );
23406 let via_into: &'static str = unit.into();
23407 assert_eq!(
23408 via_into, via_method,
23409 "Into<&'static str>::into on RateLimitUnit::{unit:?} \
23410 must byte-equal RateLimitUnit::as_suffix on the same \
23411 input — the blanket-derived Into shape must resolve to \
23412 the same as_suffix dispatch as the explicit From impl"
23413 );
23414 }
23415 assert_eq!(
23416 [SECOND, MINUTE, HOUR],
23417 ["s", "m", "h"],
23418 "const-context RateLimitUnit::as_suffix must resolve to the \
23419 three canonical-suffix byte-strings — a future accidental \
23420 downgrade of any arm to a non-const or non-static \
23421 byte-string breaks the `&'static str`-lifetime promise the \
23422 paired From<RateLimitUnit> for &'static str impl carries \
23423 by construction"
23424 );
23425 }
23426
23427 #[test]
23428 fn rate_limit_unit_from_into_static_str_and_as_suffix_partition_the_emit_set() {
23429 // Cross-axis partition pin: the paired trait-idiomatic
23430 // `From<RateLimitUnit> for &'static str` forward projection and
23431 // the method-named [`super::RateLimitUnit::as_suffix`] forward
23432 // projection must resolve identically on *every* arm, not just
23433 // the ones named in the primary byte-parity pin above. Sweeps
23434 // every [`super::RateLimitUnit::ALL`] arm and asserts the
23435 // trait's `From::from` output byte-equals the method-named
23436 // accessor's return-value on each, locking the two forward-
23437 // projection paths together by construction so any future
23438 // detour (a stray `From` special-case that lands on a divergent
23439 // per-arm literal outside the paired `as_suffix` dispatch, a
23440 // hypothetical rebrand touching one axis without the other)
23441 // trips at caixa-core test time.
23442 //
23443 // Peer of the sibling forward-projection partition pins
23444 // [`crate::supervisor::tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
23445 // (523157d),
23446 // [`crate::supervisor::tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
23447 // (9fb37d0),
23448 // [`crate::kind::tests::caixa_kind_from_into_static_str_and_as_str_partition_the_emit_set`]
23449 // (edb827b),
23450 // [`crate::dialeto::tests::caixa_dialeto_from_into_static_str_and_as_str_partition_the_emit_set`]
23451 // (c189a6f),
23452 // [`tests::placement_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
23453 // (afa3562), and
23454 // [`tests::wit_shape_from_into_static_str_and_as_str_partition_the_emit_set`]
23455 // (56998ec) — extends the round-trip discipline onto the seventh
23456 // closed-set typed enum on the caixa surface, closing the two-
23457 // way `Self ↔ &'static str` round-trip on the trait-idiomatic
23458 // pair (`From<Self> for &'static str` + `TryFrom<&str> for
23459 // Self`) as well as the pre-existing method-named pair
23460 // (`as_suffix` + `from_suffix`).
23461 for &unit in super::RateLimitUnit::ALL {
23462 let via_trait: &'static str = <&'static str as From<super::RateLimitUnit>>::from(unit);
23463 let via_method: &'static str = unit.as_suffix();
23464 assert_eq!(
23465 via_trait, via_method,
23466 "From<RateLimitUnit> for &'static str and \
23467 RateLimitUnit::as_suffix must resolve identically on \
23468 RateLimitUnit::{unit:?} — divergence signals the two \
23469 forward-projection paths have drifted onto different \
23470 emit-sets"
23471 );
23472 }
23473 // Round-trip witness: every arm's forward `From` output re-parses
23474 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
23475 // to the original variant. Closes the two-way `RateLimitUnit ↔
23476 // &'static str` round-trip on the trait-idiomatic axis pair
23477 // directly (no wire-vocab intermediate the peer [`CaixaKind`]
23478 // axis pair requires — the emit-side
23479 // [`super::RateLimitUnit::as_suffix`] and the parse-side
23480 // [`super::RateLimitUnit::from_suffix`] dispatch on the same
23481 // three inline canonical-suffix byte-strings by construction),
23482 // mirroring the pre-existing method-named `as_suffix` +
23483 // `from_suffix` round-trip on the substrate-primitive axis pair
23484 // and the peer [`super::WitShape`] round-trip (56998ec) on the
23485 // sibling M3-mesh-primitive-defining slot enum.
23486 for &unit in super::RateLimitUnit::ALL {
23487 let emitted: &'static str = unit.into();
23488 let re_parsed: Result<super::RateLimitUnit, ()> =
23489 <super::RateLimitUnit as TryFrom<&str>>::try_from(emitted);
23490 assert_eq!(
23491 re_parsed,
23492 Ok(unit),
23493 "trait-idiomatic axis pair must round-trip \
23494 RateLimitUnit::{unit:?} through `.into::<&'static \
23495 str>()` and back through `TryFrom<&str>` — a break \
23496 signals the forward-emit and reverse-parse axes have \
23497 drifted onto different vocabularies"
23498 );
23499 }
23500 }
23501
23502 #[test]
23503 fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
23504 // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
23505 // every canonical `:window` magnitude the validate gate
23506 // accepts must map to the paired [`RateLimitUnit`] arm through
23507 // this accessor. A future validate-gate rebrand that widened
23508 // the accepted-window set without extending [`RateLimitUnit`]
23509 // would silently split the accessor's `Some`-return set from
23510 // the validate gate's accept-set — a slot that satisfies
23511 // validate would land at the accessor with `None`, so a
23512 // consumer past validate that pattern-matches on the returned
23513 // `Some` would silently miss the newly-accepted magnitude.
23514 for (window_secs, expected) in [
23515 (1u64, super::RateLimitUnit::Second),
23516 (60, super::RateLimitUnit::Minute),
23517 (3600, super::RateLimitUnit::Hour),
23518 ] {
23519 let rl = RateLimit {
23520 rate: 100,
23521 window: Duration::from_secs(window_secs),
23522 };
23523 assert_eq!(
23524 rl.canonical_unit(),
23525 Some(expected),
23526 "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
23527 must return Some({expected:?})"
23528 );
23529 }
23530 // Non-canonical windows the validate gate rejects also return
23531 // None here — the accessor is the typed-enum projection of
23532 // the sibling `is_canonical_rate_limit_window` predicate.
23533 let bad = RateLimit {
23534 rate: 100,
23535 window: Duration::from_secs(30),
23536 };
23537 assert!(
23538 bad.canonical_unit().is_none(),
23539 "RateLimit with a non-canonical window must return None from \
23540 canonical_unit — the validate gate rejects the same set"
23541 );
23542 }
23543
23544 #[test]
23545 fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
23546 // Fail-before-pass-after byte-parity pin: for every canonical
23547 // window the [`rate_limit_codec::render`] arm's emitted string
23548 // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
23549 // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
23550 // the vestigial free helper [`rate_limit_window_unit`] (a
23551 // `find_map`-walked `Duration → &'static str` delegate) onto the
23552 // substrate primitive [`RateLimit::canonical_unit`] typed method
23553 // (a closed-set `match self.window` arm on
23554 // [`RateLimitUnit::from_window`], projected through
23555 // [`RateLimitUnit::as_suffix`] via the enum's
23556 // [`std::fmt::Display`] impl). A future re-routing of the render
23557 // arm through a differently-computed unit projection would break
23558 // this pin at build time rather than as a silent per-consumer
23559 // codec round-trip drift far from the substrate primitive edit.
23560 //
23561 // Sibling to the peer
23562 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
23563 // on the free-helper axis: that pin locks the two projections
23564 // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
23565 // on the closed-set arm table; this pin locks the codec's render
23566 // arm reads through the typed accessor rather than the free
23567 // helper. Two production consumers of the canonical-unit axis
23568 // now key off one typed dispatch on the substrate primitive.
23569 for (window_secs, unit) in [
23570 (1u64, super::RateLimitUnit::Second),
23571 (60, super::RateLimitUnit::Minute),
23572 (3600, super::RateLimitUnit::Hour),
23573 ] {
23574 let rl = RateLimit {
23575 rate: 42,
23576 window: Duration::from_secs(window_secs),
23577 };
23578 let policy = MeshPolicy {
23579 rate_limit: Some(rl),
23580 ..Default::default()
23581 };
23582 let json = serde_json::to_string(&policy).unwrap();
23583 let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
23584 assert!(
23585 json.contains(&expected),
23586 "rate_limit_codec::render must emit {expected} (via \
23587 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
23588 for a {window_secs}s window; serialized MeshPolicy was: {json}"
23589 );
23590 // And the accessor route resolves to the same typed unit
23591 // the render arm's Display formatting is asked to produce —
23592 // so a future edit that split the two paths (one through
23593 // the accessor, one through a re-introduced free helper)
23594 // trips this pin.
23595 assert_eq!(
23596 rl.canonical_unit(),
23597 Some(unit),
23598 "RateLimit::canonical_unit must return Some({unit:?}) for a \
23599 {window_secs}s window; the codec render arm reads the same \
23600 typed unit through this accessor"
23601 );
23602 }
23603 }
23604
23605 #[test]
23606 fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
23607 // Fail-before-pass-after byte-parity pin on the validate gate's
23608 // canonical-window shape probe: every non-canonical `:window`
23609 // the free-helper predicate [`is_canonical_rate_limit_window`]
23610 // rejects is also rejected by the substrate primitive
23611 // [`RateLimit::canonical_unit`] `.is_none()` route the validate
23612 // gate now reads through, and vice versa on the accepted set
23613 // (the three canonical windows). Locks the migration from the
23614 // free helper onto the substrate primitive: a future re-routing
23615 // of one of the two paths through a differently-computed unit
23616 // projection would silently split the codec's accepted set from
23617 // the validate gate's accepted set — a two-consumer drift the
23618 // codec-round-trip pin
23619 // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
23620 // above closes on the render arm and this pin closes on the
23621 // validate arm.
23622 for canonical_window_secs in [1u64, 60, 3600] {
23623 let mut s = three_member_spec();
23624 let rl = RateLimit {
23625 rate: 100,
23626 window: Duration::from_secs(canonical_window_secs),
23627 };
23628 s.politicas.rate_limit = Some(rl);
23629 assert!(
23630 s.validate().is_ok(),
23631 "canonical {canonical_window_secs}s window must pass \
23632 validate_politicas — the validate gate now reads \
23633 RateLimit::canonical_unit().is_none() and the accessor \
23634 returns Some on every canonical arm"
23635 );
23636 assert!(
23637 rl.canonical_unit().is_some(),
23638 "canonical {canonical_window_secs}s window must resolve to \
23639 Some on RateLimit::canonical_unit — the validate gate reads \
23640 this accessor directly"
23641 );
23642 }
23643 for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
23644 let mut s = three_member_spec();
23645 let rl = RateLimit {
23646 rate: 100,
23647 window: Duration::from_secs(non_canonical_window_secs),
23648 };
23649 s.politicas.rate_limit = Some(rl);
23650 assert_eq!(
23651 s.validate().unwrap_err(),
23652 AplicacaoError::PolicyRateLimitWindowNotCanonical {
23653 window: rl.window(),
23654 },
23655 "non-canonical {non_canonical_window_secs}s window must be \
23656 rejected by validate_politicas — the validate gate now \
23657 keys off RateLimit::canonical_unit().is_none()"
23658 );
23659 assert!(
23660 rl.canonical_unit().is_none(),
23661 "non-canonical {non_canonical_window_secs}s window must \
23662 resolve to None on RateLimit::canonical_unit — the two \
23663 paths (the free helper the validate gate previously read \
23664 and the substrate primitive the validate gate now reads) \
23665 must agree on the same rejected set"
23666 );
23667 }
23668 // And the substrate-primitive [`RateLimit::canonical_unit`]
23669 // accessor's accepted-window set matches the codec's parse arm's
23670 // accepted-suffix set on every canonical / non-canonical shape,
23671 // so a future silent drift between the codec's accepted set and
23672 // the validate gate's accepted set is a build error at test time
23673 // (both consumers key off the same closed-set enum's `match self`
23674 // arms). The predecessor free helper `is_canonical_rate_limit_window`
23675 // — a delegate that composed [`RateLimitUnit::from_window`] with
23676 // `.is_some()` — was deleted after this migration; the
23677 // canonical-window set now lives on exactly one typed dispatch
23678 // on the substrate primitive.
23679 for (secs, expected) in [
23680 (1u64, true),
23681 (60, true),
23682 (3600, true),
23683 (2, false),
23684 (30, false),
23685 (86_400, false),
23686 ] {
23687 let window = Duration::from_secs(secs);
23688 let rl = RateLimit { rate: 1, window };
23689 assert_eq!(
23690 rl.canonical_unit().is_some(),
23691 expected,
23692 "RateLimit::canonical_unit().is_some() must agree with the \
23693 codec-accepted canonical-window set on {secs}s"
23694 );
23695 let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
23696 1 => "s",
23697 60 => "m",
23698 3600 => "h",
23699 _ => return,
23700 })
23701 .is_some_and(|d| d == window);
23702 if expected {
23703 assert!(
23704 suffix_from_axis,
23705 "the codec's `&str → Duration` axis \
23706 ({secs}s) must round-trip to the same Duration the \
23707 substrate primitive's accessor returns Some on"
23708 );
23709 }
23710 }
23711 }
23712
23713 #[test]
23714 fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
23715 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
23716 // derive: for each of the three variants, exactly one of the
23717 // generated `is_second` / `is_minute` / `is_hour` predicates
23718 // returns `true` and the other two return `false`. Peer of
23719 // the sibling
23720 // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
23721 // sibling `IsVariant`-derived closed-set typed-enum pins.
23722 let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
23723 (super::RateLimitUnit::Second, [true, false, false]),
23724 (super::RateLimitUnit::Minute, [false, true, false]),
23725 (super::RateLimitUnit::Hour, [false, false, true]),
23726 ];
23727 for (variant, expected) in rows {
23728 let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
23729 assert_eq!(
23730 observed, expected,
23731 "RateLimitUnit::{variant:?} is_* predicates must partition \
23732 the arm set (second, minute, hour); got {observed:?}"
23733 );
23734 }
23735 }
23736
23737 #[test]
23738 fn rejects_policy_timeout_sub_millisecond() {
23739 // A purely sub-millisecond `Duration` (`from_micros(500)` =
23740 // 500_000 ns) is not the zero `Duration` — the `is_zero()`
23741 // arm passes — but `as_millis() == 0`, so the shared codec's
23742 // `render` arm returns the literal `"0s"`, which the
23743 // codec's `parse` arm then deserializes as `Duration::ZERO`
23744 // and the `PolicyTimeoutZero` zero-floor gate would reject
23745 // on re-validate. Pin the rejection at the typed slot's
23746 // canonical-floor gate so the round-trip break surfaces at
23747 // validate time, naming the offending `Duration`, rather
23748 // than at the next serialize → deserialize round-trip far
23749 // from the source `caixa.lisp`.
23750 let mut s = three_member_spec();
23751 let timeout = Duration::from_micros(500);
23752 s.politicas.timeout = Some(timeout);
23753 assert_eq!(
23754 s.validate().unwrap_err(),
23755 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
23756 );
23757 }
23758
23759 #[test]
23760 fn rejects_policy_timeout_non_integer_millisecond() {
23761 // A `Duration` with non-integer-millisecond residue
23762 // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
23763 // through the shared codec's `render` arm as `"1ms"` (the
23764 // `as_millis()` floor truncates), which the codec's `parse`
23765 // arm then deserializes as `Duration::from_millis(1)` =
23766 // 1_000_000 ns — silently *different* from the original.
23767 // Pin the rejection so this round-trip break surfaces at
23768 // validate time, where the offending `Duration` is named,
23769 // rather than as a silent value-laundered round-trip on the
23770 // next codec round-trip.
23771 let mut s = three_member_spec();
23772 let timeout = Duration::from_micros(1500);
23773 s.politicas.timeout = Some(timeout);
23774 assert_eq!(
23775 s.validate().unwrap_err(),
23776 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
23777 );
23778 }
23779
23780 #[test]
23781 fn accepts_policy_timeout_integer_millisecond_forms() {
23782 // The codec's accepted set — integer multiples of 1ms — is
23783 // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
23784 // `1h` all pass the canonical gate. Pin the canonical-forms
23785 // sweep so a future tightening of the codec's grammar (e.g.
23786 // dropping `:ms`) surfaces here as a test failure rather
23787 // than a silent contract narrowing on the typed slot.
23788 for timeout in [
23789 Duration::from_millis(1),
23790 Duration::from_millis(500),
23791 Duration::from_millis(1500),
23792 Duration::from_secs(30),
23793 Duration::from_secs(120),
23794 Duration::from_secs(3600),
23795 ] {
23796 let mut s = three_member_spec();
23797 s.politicas.timeout = Some(timeout);
23798 s.validate()
23799 .expect("integer-millisecond :timeout must validate");
23800 }
23801 }
23802
23803 #[test]
23804 fn policy_timeout_zero_takes_precedence_over_canonical() {
23805 // `Duration::ZERO` carries `subsec_nanos() == 0` and would
23806 // pass the canonical-millisecond gate; the more self-locating
23807 // `PolicyTimeoutZero` arm (which names the omit-axis
23808 // remediation directly) must fire first. Pin the ordering so
23809 // a future refactor that reorders the arms surfaces here as a
23810 // test failure rather than a silent diagnostic regression.
23811 let mut s = three_member_spec();
23812 s.politicas.timeout = Some(Duration::ZERO);
23813 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
23814 }
23815
23816 #[test]
23817 fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
23818 // The diagnostic envelope carries the offending `Duration`
23819 // verbatim so the author can grep their `caixa.lisp` for
23820 // `:timeout "<value>"` and fix it in one edit. Same
23821 // diagnostic shape every other typed-slot canonical-form
23822 // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
23823 // peer `:rate-limit :window` axis.
23824 let mut s = three_member_spec();
23825 let timeout = Duration::from_nanos(1_000_001);
23826 s.politicas.timeout = Some(timeout);
23827 match s.validate().unwrap_err() {
23828 AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
23829 assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
23830 }
23831 other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
23832 }
23833 }
23834
23835 #[test]
23836 fn rejects_policy_timeout_above_cap() {
23837 // The fail-before-pass-after pin: 3601s = 1h + 1s is
23838 // structurally one canonical-tick past the
23839 // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
23840 // integer-millisecond magnitude the canonical-form arm above
23841 // accepts cleanly, that the codec round-trips losslessly as
23842 // `"3601s"`, and that silently passed validate on every
23843 // pre-gate codebase because the typed slot's only checks were
23844 // the zero-floor and canonical-form arms. The mesh-level
23845 // deadline degenerates only at the runtime substrate (Envoy
23846 // / Cilium L7 timeout overlay) far from the source
23847 // `caixa.lisp` with no field naming the offending policy.
23848 let mut s = three_member_spec();
23849 let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
23850 s.politicas.timeout = Some(timeout);
23851 assert_eq!(
23852 s.validate().unwrap_err(),
23853 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
23854 );
23855 }
23856
23857 #[test]
23858 fn rejects_policy_timeout_one_millisecond_above_cap() {
23859 // Boundary case: exactly 1ms past the cap (the granularity
23860 // the canonical-form gate enforces). Catches a future
23861 // "strictly less than" half-measure and pins the diagnostic
23862 // to name the offending `Duration` verbatim. Peer of
23863 // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
23864 // boundary pin on the sibling `:limits :memory` top edge.
23865 let mut s = three_member_spec();
23866 let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
23867 s.politicas.timeout = Some(timeout);
23868 assert_eq!(
23869 s.validate().unwrap_err(),
23870 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
23871 );
23872 }
23873
23874 #[test]
23875 fn rejects_policy_timeout_far_above_cap() {
23876 // The "obvious authoring footgun" case: a `(:timeout "24h")`
23877 // or `(:timeout "86400s")` — values the canonical-form arm
23878 // accepts as integer-millisecond magnitudes, the codec
23879 // round-trips losslessly through serde, but the mesh-level
23880 // policy cannot honor (a 24-hour synchronous-`:contratos`
23881 // deadline is operationally indistinguishable from
23882 // omit-the-axis). Until this gate landed validate accepted
23883 // it. Pin both common above-cap values (24h, 7d) so a future
23884 // relaxation that drops the upper bound surfaces here.
23885 for timeout in [
23886 Duration::from_secs(86_400), // 24h
23887 Duration::from_secs(604_800), // 7d
23888 Duration::from_secs(1_000_000), // ~11.5 days
23889 ] {
23890 let mut s = three_member_spec();
23891 s.politicas.timeout = Some(timeout);
23892 assert_eq!(
23893 s.validate().unwrap_err(),
23894 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
23895 );
23896 }
23897 }
23898
23899 #[test]
23900 fn accepts_policy_timeout_at_cap() {
23901 // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
23902 // must validate. The cap is inclusive on the top edge,
23903 // matching the [`POLICY_RETRIES_MAX`] /
23904 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
23905 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
23906 // sibling capped axes. Pin the boundary explicitly so a
23907 // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
23908 // instead of `>`) surfaces here as a test failure rather
23909 // than a silent contract narrowing.
23910 let mut s = three_member_spec();
23911 s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
23912 s.validate()
23913 .expect("timeout == POLICY_TIMEOUT_MAX must validate");
23914 }
23915
23916 #[test]
23917 fn accepts_policy_timeout_typical_values() {
23918 // The documented production-playbook band positive-control
23919 // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
23920 // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
23921 // plus a sweep through the long-running-workflow band
23922 // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
23923 // validated set explicitly so a future tightening of the
23924 // ceiling surfaces here as a deliberate test edit, not a
23925 // silent contract narrowing.
23926 for timeout in [
23927 Duration::from_millis(1),
23928 Duration::from_millis(500),
23929 Duration::from_secs(1),
23930 Duration::from_secs(10),
23931 Duration::from_secs(15), // Envoy default
23932 Duration::from_secs(30),
23933 Duration::from_secs(60), // AWS App Mesh typical
23934 Duration::from_secs(300),
23935 Duration::from_secs(900),
23936 Duration::from_secs(1800),
23937 Duration::from_secs(3600), // exactly 1h, the cap
23938 ] {
23939 let mut s = three_member_spec();
23940 s.politicas.timeout = Some(timeout);
23941 s.validate()
23942 .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
23943 }
23944 }
23945
23946 #[test]
23947 fn policy_timeout_zero_takes_precedence_over_cap() {
23948 // The cross-arm ordering pin: `Duration::ZERO` is
23949 // structurally outside both `>= 1ms` (zero-floor) and
23950 // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
23951 // diagnostic is the more self-locating one (it directly
23952 // names the omit-axis remediation), so the validate gate
23953 // must fire on zero first. Same shape every other
23954 // zero-then-shape ordering on this surface uses
23955 // ([`AplicacaoError::PolicyRetriesZero`] then
23956 // [`AplicacaoError::PolicyRetriesExceedsCap`];
23957 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
23958 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
23959 let mut s = three_member_spec();
23960 s.politicas.timeout = Some(Duration::ZERO);
23961 assert_eq!(
23962 s.validate().unwrap_err(),
23963 AplicacaoError::PolicyTimeoutZero,
23964 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
23965 );
23966 }
23967
23968 #[test]
23969 fn policy_timeout_canonical_takes_precedence_over_cap() {
23970 // The cross-arm ordering pin: a `Duration` that is *both*
23971 // sub-millisecond (non-canonical-form) and structurally
23972 // above the cap surfaces the canonical-form diagnostic
23973 // first, because the round-trip-shape break is the more
23974 // fundamental issue (the value can't even round-trip
23975 // through the codec, so the cap diagnostic naming
23976 // `1ms..=1h` would be misleading — there's no integer-ms
23977 // form of the offending value). Pin the order so a future
23978 // refactor that reorders the arms surfaces here as a test
23979 // failure rather than a silent diagnostic regression.
23980 let mut s = three_member_spec();
23981 // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
23982 // *and* total magnitude above the 1h cap.
23983 let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
23984 s.politicas.timeout = Some(timeout);
23985 assert_eq!(
23986 s.validate().unwrap_err(),
23987 AplicacaoError::PolicyTimeoutNotCanonical { timeout },
23988 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
23989 );
23990 }
23991
23992 #[test]
23993 fn policy_timeout_cap_diagnostic_carries_offending_value() {
23994 // The diagnostic-shape pin: the offending `Duration` is
23995 // carried verbatim into the
23996 // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
23997 // surfaced error message names the value the author wrote
23998 // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
23999 // exceeds the mesh-policy ceiling …"`), not just the cap.
24000 // Same self-locating diagnostic shape every other typed-cap
24001 // arm on this surface carries
24002 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
24003 // offending retry count verbatim).
24004 let mut s = three_member_spec();
24005 let timeout = Duration::from_secs(7200); // 2h
24006 s.politicas.timeout = Some(timeout);
24007 let err = s.validate().unwrap_err();
24008 assert!(
24009 matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
24010 "got {err:?}"
24011 );
24012 let msg = err.to_string();
24013 assert!(
24014 msg.contains("7200"),
24015 ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
24016 );
24017 }
24018
24019 #[test]
24020 fn policy_timeout_cap_pins_canonical_value() {
24021 // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
24022 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
24023 // the shared duration codec emits as a clean canonical
24024 // string (`"<n>h"`). Pinning the literal value here surfaces
24025 // a future drift (a relaxation to 24h, a tightening to 5m)
24026 // as a deliberate test edit, not a silent contract
24027 // narrowing. Same shape every other typed-cap value pin on
24028 // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
24029 assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
24030 assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
24031 }
24032
24033 #[test]
24034 fn policy_timeout_cap_value_round_trips_through_codec() {
24035 // The codec round-trip property the cap arm preserves: the
24036 // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
24037 // the shared duration codec — every value at the cap renders
24038 // to a clean canonical string (`"1h"`) and parses back to
24039 // the same `Duration`. Pin this so a future drift between
24040 // the cap constant and the codec's largest emitted unit
24041 // surfaces here. Same shape every other typed boundary pin
24042 // on this surface uses
24043 // (`wasm32_memory_cap_matches_parsed_4_gib`).
24044 let policy = MeshPolicy {
24045 timeout: Some(POLICY_TIMEOUT_MAX),
24046 ..Default::default()
24047 };
24048 let json = serde_json::to_string(&policy).unwrap();
24049 // The codec emits `"1h"` for the canonical 1-hour magnitude.
24050 assert!(
24051 json.contains("\"1h\""),
24052 "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
24053 );
24054 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
24055 assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
24056 }
24057
24058 #[test]
24059 fn rejects_circuit_breaker_window_sub_millisecond() {
24060 // Peer of the `:timeout` sub-millisecond arm on the second
24061 // typed-`Duration` `:politicas` axis: a purely sub-ms
24062 // `Duration` (`from_micros(500)`) renders through the shared
24063 // codec as `"0s"`, which the codec parses back to
24064 // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
24065 // zero-floor gate then rejects on re-validate.
24066 let mut s = three_member_spec();
24067 let window = Duration::from_micros(500);
24068 s.politicas.circuit_breaker = Some(CircuitBreaker {
24069 max_failures: 5,
24070 window,
24071 });
24072 assert_eq!(
24073 s.validate().unwrap_err(),
24074 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
24075 );
24076 }
24077
24078 #[test]
24079 fn rejects_circuit_breaker_window_non_integer_millisecond() {
24080 // Peer of the `:timeout` non-integer-ms arm: a `Duration`
24081 // with non-integer-millisecond residue renders through the
24082 // shared codec as the truncated `"<n>ms"` form, parsing back
24083 // to a *different* `Duration` on the next round-trip.
24084 let mut s = three_member_spec();
24085 let window = Duration::from_micros(1500);
24086 s.politicas.circuit_breaker = Some(CircuitBreaker {
24087 max_failures: 5,
24088 window,
24089 });
24090 assert_eq!(
24091 s.validate().unwrap_err(),
24092 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
24093 );
24094 }
24095
24096 #[test]
24097 fn accepts_circuit_breaker_window_integer_millisecond_forms() {
24098 // The canonical-forms sweep on the breaker axis: every
24099 // integer-ms multiple the codec round-trips losslessly
24100 // passes the canonical gate.
24101 //
24102 // Clears `:timeout` from the fixture so this per-axis sweep
24103 // covers windows shorter than the fixture's 30s timeout
24104 // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
24105 // structurally-inert breaker
24106 // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
24107 // the cross-axis gate at the end of
24108 // [`AplicacaoSpec::validate_politicas`] rejects on the paired
24109 // `(:timeout, :window)` shape, not on the per-axis
24110 // integer-millisecond canonical-form shape this test pins.
24111 // The paired shape is covered by
24112 // `rejects_circuit_breaker_window_below_timeout`.
24113 for window in [
24114 Duration::from_millis(1),
24115 Duration::from_millis(500),
24116 Duration::from_millis(1500),
24117 Duration::from_secs(30),
24118 Duration::from_secs(60),
24119 Duration::from_secs(3600),
24120 ] {
24121 let mut s = three_member_spec();
24122 s.politicas.timeout = None;
24123 s.politicas.circuit_breaker = Some(CircuitBreaker {
24124 max_failures: 5,
24125 window,
24126 });
24127 s.validate()
24128 .expect("integer-millisecond :circuit-breaker :window must validate");
24129 }
24130 }
24131
24132 #[test]
24133 fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
24134 // `Duration::ZERO` would pass the canonical-ms gate (the
24135 // sub-ns residue is zero) but must surface the narrower
24136 // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
24137 // remediation.
24138 let mut s = three_member_spec();
24139 s.politicas.circuit_breaker = Some(CircuitBreaker {
24140 max_failures: 5,
24141 window: Duration::ZERO,
24142 });
24143 assert_eq!(
24144 s.validate().unwrap_err(),
24145 AplicacaoError::PolicyBreakerZeroWindow
24146 );
24147 }
24148
24149 #[test]
24150 fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
24151 // Both axes invalid: max_failures == 0 *and* window is
24152 // sub-ms. The validate gate must fire on max_failures first
24153 // (matching the existing ordering pin
24154 // `rejects_circuit_breaker_zero_max_failures` enshrines), so
24155 // the existing diagnostic continues to lead with the simpler
24156 // "zero threshold" framing.
24157 let mut s = three_member_spec();
24158 s.politicas.circuit_breaker = Some(CircuitBreaker {
24159 max_failures: 0,
24160 window: Duration::from_micros(500),
24161 });
24162 assert_eq!(
24163 s.validate().unwrap_err(),
24164 AplicacaoError::PolicyBreakerZeroFailures
24165 );
24166 }
24167
24168 #[test]
24169 fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
24170 let mut s = three_member_spec();
24171 let window = Duration::from_nanos(60_000_000_001);
24172 s.politicas.circuit_breaker = Some(CircuitBreaker {
24173 max_failures: 5,
24174 window,
24175 });
24176 match s.validate().unwrap_err() {
24177 AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
24178 assert_eq!(w, window, "diagnostic must carry the offending Duration");
24179 }
24180 other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
24181 }
24182 }
24183
24184 #[test]
24185 fn rejects_circuit_breaker_window_above_cap() {
24186 // The fail-before-pass-after pin: 3601s = 1h + 1s is
24187 // structurally one canonical-tick past the
24188 // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
24189 // integer-millisecond magnitude the canonical-form arm above
24190 // accepts cleanly, that the codec round-trips losslessly as
24191 // `"3601s"`, and that silently passed validate on every
24192 // pre-gate codebase because the typed slot's only checks were
24193 // the zero-floor and canonical-form arms. The
24194 // rolling-window-to-lifetime-counter degeneration surfaces
24195 // only at the runtime substrate (Envoy's outlier_detection
24196 // interval, the future CiliumClusterwideEnvoyConfig overlay)
24197 // far from the source `caixa.lisp` with no field naming the
24198 // offending policy.
24199 let mut s = three_member_spec();
24200 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
24201 s.politicas.circuit_breaker = Some(CircuitBreaker {
24202 max_failures: 5,
24203 window,
24204 });
24205 assert_eq!(
24206 s.validate().unwrap_err(),
24207 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
24208 );
24209 }
24210
24211 #[test]
24212 fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
24213 // Boundary case: exactly 1ms past the cap (the granularity the
24214 // canonical-form gate enforces). Catches a future "strictly
24215 // less than" half-measure and pins the diagnostic to name the
24216 // offending `Duration` verbatim. Peer of
24217 // `rejects_policy_timeout_one_millisecond_above_cap` on the
24218 // sibling duration-typed `:politicas :timeout` top edge.
24219 let mut s = three_member_spec();
24220 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
24221 s.politicas.circuit_breaker = Some(CircuitBreaker {
24222 max_failures: 5,
24223 window,
24224 });
24225 assert_eq!(
24226 s.validate().unwrap_err(),
24227 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
24228 );
24229 }
24230
24231 #[test]
24232 fn rejects_circuit_breaker_window_far_above_cap() {
24233 // The "obvious authoring footgun" case: a `(:window "24h")` or
24234 // `(:window "86400s")` — values the canonical-form arm
24235 // accepts as integer-millisecond magnitudes, the codec
24236 // round-trips losslessly through serde, but the
24237 // rolling-window breaker contract cannot honor (a 24-hour
24238 // rolling failure window is operationally a lifetime counter).
24239 // Until this gate landed validate accepted it. Pin both common
24240 // above-cap values (24h, 7d) so a future relaxation that
24241 // drops the upper bound surfaces here.
24242 for window in [
24243 Duration::from_secs(86_400), // 24h
24244 Duration::from_secs(604_800), // 7d
24245 Duration::from_secs(1_000_000), // ~11.5 days
24246 ] {
24247 let mut s = three_member_spec();
24248 s.politicas.circuit_breaker = Some(CircuitBreaker {
24249 max_failures: 5,
24250 window,
24251 });
24252 assert_eq!(
24253 s.validate().unwrap_err(),
24254 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
24255 );
24256 }
24257 }
24258
24259 #[test]
24260 fn accepts_circuit_breaker_window_at_cap() {
24261 // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
24262 // (1h) — must validate. The cap is inclusive on the top edge,
24263 // matching the [`POLICY_TIMEOUT_MAX`] /
24264 // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
24265 // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
24266 // sibling capped axes. Pin the boundary explicitly so a
24267 // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
24268 // instead of `>`) surfaces here as a test failure rather than
24269 // a silent contract narrowing.
24270 let mut s = three_member_spec();
24271 s.politicas.circuit_breaker = Some(CircuitBreaker {
24272 max_failures: 5,
24273 window: POLICY_BREAKER_WINDOW_MAX,
24274 });
24275 s.validate()
24276 .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
24277 }
24278
24279 #[test]
24280 fn accepts_circuit_breaker_window_typical_values() {
24281 // The documented production-playbook band positive-control
24282 // sweep — every value Hystrix / resilience4j / Istio / Envoy
24283 // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
24284 // through the long-tail failure-detection band (15m, 30m, 1h)
24285 // the cap accepts. Pin the inclusive validated set explicitly
24286 // so a future tightening of the ceiling surfaces here as a
24287 // deliberate test edit, not a silent contract narrowing.
24288 //
24289 // Clears `:timeout` from the fixture so this per-axis sweep
24290 // covers windows shorter than the fixture's 30s timeout
24291 // (Hystrix's 10s default, resilience4j's 30s, and the
24292 // sub-second warm-up band) — every such value is a
24293 // structurally-inert breaker under the cross-axis gate at the
24294 // end of [`AplicacaoSpec::validate_politicas`]
24295 // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
24296 // the paired `(:timeout, :window)` shape is covered by
24297 // `rejects_circuit_breaker_window_below_timeout`; this
24298 // per-axis pin ranges only over the per-axis-bracket accept set.
24299 for window in [
24300 Duration::from_millis(1),
24301 Duration::from_millis(500),
24302 Duration::from_secs(1),
24303 Duration::from_secs(10), // Hystrix / Istio / Envoy default
24304 Duration::from_secs(30),
24305 Duration::from_secs(60), // resilience4j typical
24306 Duration::from_secs(300), // AWS App Mesh typical
24307 Duration::from_secs(900),
24308 Duration::from_secs(1800),
24309 Duration::from_secs(3600), // exactly 1h, the cap
24310 ] {
24311 let mut s = three_member_spec();
24312 s.politicas.timeout = None;
24313 s.politicas.circuit_breaker = Some(CircuitBreaker {
24314 max_failures: 5,
24315 window,
24316 });
24317 s.validate()
24318 .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
24319 }
24320 }
24321
24322 #[test]
24323 fn circuit_breaker_zero_window_takes_precedence_over_cap() {
24324 // The cross-arm ordering pin: `Duration::ZERO` is structurally
24325 // outside both `>= 1ms` (zero-floor) and
24326 // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
24327 // diagnostic is the more self-locating one (it directly names
24328 // the omit-axis remediation), so the validate gate must fire
24329 // on zero first. Same shape every other zero-then-cap
24330 // ordering on this surface uses
24331 // ([`AplicacaoError::PolicyTimeoutZero`] then
24332 // [`AplicacaoError::PolicyTimeoutExceedsCap`];
24333 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
24334 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
24335 let mut s = three_member_spec();
24336 s.politicas.circuit_breaker = Some(CircuitBreaker {
24337 max_failures: 5,
24338 window: Duration::ZERO,
24339 });
24340 assert_eq!(
24341 s.validate().unwrap_err(),
24342 AplicacaoError::PolicyBreakerZeroWindow,
24343 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
24344 );
24345 }
24346
24347 #[test]
24348 fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
24349 // The cross-arm ordering pin: a `Duration` that is *both*
24350 // sub-millisecond (non-canonical-form) and structurally above
24351 // the cap surfaces the canonical-form diagnostic first,
24352 // because the round-trip-shape break is the more fundamental
24353 // issue (the value can't even round-trip through the codec, so
24354 // the cap diagnostic naming `1ms..=1h` would be misleading —
24355 // there's no integer-ms form of the offending value). Pin the
24356 // order so a future refactor that reorders the arms surfaces
24357 // here as a test failure rather than a silent diagnostic
24358 // regression. Peer of
24359 // `policy_timeout_canonical_takes_precedence_over_cap` on the
24360 // sibling duration-typed `:politicas :timeout` axis.
24361 let mut s = three_member_spec();
24362 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
24363 s.politicas.circuit_breaker = Some(CircuitBreaker {
24364 max_failures: 5,
24365 window,
24366 });
24367 assert_eq!(
24368 s.validate().unwrap_err(),
24369 AplicacaoError::PolicyBreakerWindowNotCanonical { window },
24370 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
24371 );
24372 }
24373
24374 #[test]
24375 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
24376 // The cross-arm ordering pin between the two breaker axes: a
24377 // `CircuitBreaker` whose *both* `max_failures` is above its
24378 // cap *and* `window` is above its cap surfaces the
24379 // max-failures cap diagnostic first, because the validate
24380 // gate visits the failures arm before the window arm. Pin the
24381 // order so a future refactor that reorders the breaker arms
24382 // surfaces here.
24383 let mut s = three_member_spec();
24384 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
24385 s.politicas.circuit_breaker = Some(CircuitBreaker {
24386 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
24387 window,
24388 });
24389 assert_eq!(
24390 s.validate().unwrap_err(),
24391 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
24392 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
24393 },
24394 "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
24395 );
24396 }
24397
24398 #[test]
24399 fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
24400 // The diagnostic-shape pin: the offending `Duration` is
24401 // carried verbatim into the
24402 // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
24403 // the surfaced error message names the value the author wrote
24404 // (`":politicas :circuit-breaker :window (Duration { secs:
24405 // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
24406 // just the cap. Same self-locating diagnostic shape every
24407 // other typed-cap arm on this surface carries
24408 // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
24409 // offending `Duration` verbatim).
24410 let mut s = three_member_spec();
24411 let window = Duration::from_secs(7200); // 2h
24412 s.politicas.circuit_breaker = Some(CircuitBreaker {
24413 max_failures: 5,
24414 window,
24415 });
24416 let err = s.validate().unwrap_err();
24417 assert!(
24418 matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
24419 "got {err:?}"
24420 );
24421 let msg = err.to_string();
24422 assert!(
24423 msg.contains("7200"),
24424 ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
24425 );
24426 }
24427
24428 #[test]
24429 fn circuit_breaker_window_cap_pins_canonical_value() {
24430 // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
24431 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
24432 // shared duration codec emits as a clean canonical string
24433 // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
24434 // the sibling duration-typed `:politicas :timeout` axis (the
24435 // two duration-typed `:politicas` axes share a uniform top
24436 // edge). Pinning the literal value here surfaces a future
24437 // drift (a relaxation to 24h, a tightening to 5m) as a
24438 // deliberate test edit, not a silent contract narrowing. Same
24439 // shape every other typed-cap value pin on this surface uses
24440 // (`policy_timeout_cap_pins_canonical_value`).
24441 assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
24442 assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
24443 assert_eq!(
24444 POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
24445 "the two duration-typed `:politicas` caps share the same top edge"
24446 );
24447 }
24448
24449 #[test]
24450 fn circuit_breaker_window_cap_value_round_trips_through_codec() {
24451 // The codec round-trip property the cap arm preserves: the
24452 // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
24453 // through the shared duration codec — every value at the cap
24454 // renders to a clean canonical string (`"1h"`) and parses back
24455 // to the same `Duration`. Pin this so a future drift between
24456 // the cap constant and the codec's largest emitted unit
24457 // surfaces here. Same shape every other typed boundary pin on
24458 // this surface uses
24459 // (`policy_timeout_cap_value_round_trips_through_codec`).
24460 let policy = MeshPolicy {
24461 circuit_breaker: Some(CircuitBreaker {
24462 max_failures: 5,
24463 window: POLICY_BREAKER_WINDOW_MAX,
24464 }),
24465 ..Default::default()
24466 };
24467 let json = serde_json::to_string(&policy).unwrap();
24468 // The codec emits `"1h"` for the canonical 1-hour magnitude.
24469 assert!(
24470 json.contains("\"1h\""),
24471 "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
24472 );
24473 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
24474 assert_eq!(
24475 back.circuit_breaker.unwrap().window,
24476 POLICY_BREAKER_WINDOW_MAX
24477 );
24478 }
24479
24480 #[test]
24481 fn is_integer_millisecond_duration_predicate_tracks_codec() {
24482 // Pin the predicate's accepted set against the codec's
24483 // accepted set explicitly. The codec parses
24484 // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
24485 // accepted value is an integer-millisecond multiple — so the
24486 // predicate must accept exactly that set. Same shape every
24487 // other predicate-on-the-typed-slot helper carries
24488 // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
24489 // Read directly from the codec-owned predicate — the crate's
24490 // single source of truth every typed-`Duration` axis now routes
24491 // through via
24492 // [`crate::render::require_positive_canonical_bounded_duration`].
24493 use super::supervisor::duration_codec::is_integer_millisecond_duration;
24494 assert!(is_integer_millisecond_duration(Duration::ZERO));
24495 assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
24496 assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
24497 assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
24498 assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
24499 assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
24500 // Non-integer-millisecond residue: rejected.
24501 assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
24502 assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
24503 assert!(!is_integer_millisecond_duration(Duration::from_micros(
24504 1500
24505 )));
24506 assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
24507 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
24508 999_999
24509 )));
24510 // The 1-ns-past-1ms boundary: rejected (no longer a clean
24511 // integer-millisecond multiple).
24512 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
24513 1_000_001
24514 )));
24515 }
24516
24517 #[test]
24518 fn policy_timeout_validated_value_round_trips_through_codec() {
24519 // The structural property the canonical-ms gate enforces:
24520 // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
24521 // round-trips losslessly through the shared `duration_codec`
24522 // (serialize → string → deserialize → equal value). Pin this
24523 // end-to-end so a future change to either side (the validate
24524 // gate's accepted granularity, the codec's parse/render unit
24525 // set) that breaks the alignment surfaces here. The
24526 // previous-state shape (typed slot accepts arbitrary
24527 // `Duration`, codec only round-trips integer-ms) would fail
24528 // this test for any `Duration::from_micros(1500)` timeout —
24529 // the validate gate now forecloses that.
24530 for timeout in [
24531 Duration::from_millis(1),
24532 Duration::from_millis(1500),
24533 Duration::from_secs(30),
24534 Duration::from_secs(3600),
24535 ] {
24536 let mut s = three_member_spec();
24537 s.politicas.timeout = Some(timeout);
24538 s.validate().unwrap();
24539 let json = serde_json::to_string(&s.politicas).unwrap();
24540 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
24541 assert_eq!(
24542 back.timeout, s.politicas.timeout,
24543 "every validated :timeout must round-trip losslessly through the codec"
24544 );
24545 }
24546 }
24547
24548 #[test]
24549 fn circuit_breaker_window_validated_value_round_trips_through_codec() {
24550 // Peer of the `:timeout` round-trip property on the breaker
24551 // axis.
24552 //
24553 // Clears `:timeout` from the fixture so the round-trip pin
24554 // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
24555 // cross-axis gate would otherwise reject as structurally-inert
24556 // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
24557 // the paired `(:timeout, :window)` cross-axis relation is
24558 // pinned separately by
24559 // `rejects_circuit_breaker_window_below_timeout`, and this
24560 // property is a pure serde-codec round-trip on the per-axis
24561 // slot.
24562 for window in [
24563 Duration::from_millis(1),
24564 Duration::from_millis(1500),
24565 Duration::from_secs(30),
24566 Duration::from_secs(3600),
24567 ] {
24568 let mut s = three_member_spec();
24569 s.politicas.timeout = None;
24570 s.politicas.circuit_breaker = Some(CircuitBreaker {
24571 max_failures: 5,
24572 window,
24573 });
24574 s.validate().unwrap();
24575 let json = serde_json::to_string(&s.politicas).unwrap();
24576 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
24577 assert_eq!(
24578 back.circuit_breaker.unwrap().window,
24579 window,
24580 "every validated :circuit-breaker :window must round-trip losslessly"
24581 );
24582 }
24583 }
24584
24585 #[test]
24586 fn rejects_circuit_breaker_window_below_timeout() {
24587 // The fail-before-pass-after pin on the cross-axis
24588 // `(:timeout, :circuit-breaker :window)` invariant. Each axis
24589 // is individually well-formed under its own per-axis bracket
24590 // (both integer-millisecond, both above the zero floor, both
24591 // below the cap), but the pair is a structurally-inert
24592 // breaker: a call dispatched at t=0 is declared failed at
24593 // t=30s, by which point the 10s rolling window open at
24594 // dispatch has already rolled twice, so no window can hold
24595 // a timeout-derived failure however high the call volume.
24596 //
24597 // Envoy's `outlier_detection.interval` against the per-route
24598 // request timeout carries the identical relation; Hystrix
24599 // ships the canonical ratio in its defaults (10s window
24600 // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
24601 //
24602 // Pin both the diagnostic arm and the payload values so a
24603 // future re-shape of the arm surfaces here as a deliberate
24604 // test edit.
24605 let mut s = three_member_spec();
24606 s.politicas.timeout = Some(Duration::from_secs(30));
24607 s.politicas.circuit_breaker = Some(CircuitBreaker {
24608 max_failures: 5,
24609 window: Duration::from_secs(10),
24610 });
24611 assert_eq!(
24612 s.validate().unwrap_err(),
24613 AplicacaoError::PolicyBreakerWindowBelowTimeout {
24614 window: Duration::from_secs(10),
24615 timeout: Duration::from_secs(30),
24616 }
24617 );
24618 }
24619
24620 #[test]
24621 fn accepts_circuit_breaker_window_equal_to_timeout() {
24622 // Boundary pin: `:window == :timeout` is the smallest window
24623 // that structurally admits at least one full timeout-derived
24624 // failure before the rolling interval closes (the invariant
24625 // is `:window >= :timeout`, not strict inequality). Catches
24626 // a future off-by-one tightening that would drift the accept
24627 // set away from the codified [`MeshPolicy::breaker_window_
24628 // observes_timeout`] predicate.
24629 let mut s = three_member_spec();
24630 s.politicas.timeout = Some(Duration::from_secs(30));
24631 s.politicas.circuit_breaker = Some(CircuitBreaker {
24632 max_failures: 5,
24633 window: Duration::from_secs(30),
24634 });
24635 s.validate()
24636 .expect("window == timeout is the boundary accept case");
24637 }
24638
24639 #[test]
24640 fn accepts_circuit_breaker_window_above_timeout() {
24641 // Positive-control sweep across the production-playbook band —
24642 // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
24643 // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
24644 // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
24645 // playbook recommends must validate under the cross-axis gate.
24646 for (timeout, window) in [
24647 (Duration::from_secs(1), Duration::from_secs(10)),
24648 (Duration::from_secs(5), Duration::from_secs(30)),
24649 (Duration::from_secs(10), Duration::from_secs(60)),
24650 (Duration::from_secs(30), Duration::from_secs(300)),
24651 (Duration::from_secs(60), Duration::from_secs(300)),
24652 ] {
24653 let mut s = three_member_spec();
24654 s.politicas.timeout = Some(timeout);
24655 s.politicas.circuit_breaker = Some(CircuitBreaker {
24656 max_failures: 5,
24657 window,
24658 });
24659 s.validate().unwrap_or_else(|e| {
24660 panic!(
24661 "production-playbook pair timeout={timeout:?}/window={window:?} must \
24662 validate; got {e:?}"
24663 )
24664 });
24665 }
24666 }
24667
24668 #[test]
24669 fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
24670 // Off-by-one boundary pin: a window exactly 1ms shy of the
24671 // timeout is still structurally inert under the invariant
24672 // (the dispatch-to-report lag is `timeout`, so the window
24673 // must span at least one such lag). Catches a future
24674 // strict-inequality relaxation that would silently drift
24675 // the accept boundary.
24676 let timeout = Duration::from_secs(30);
24677 let window = Duration::from_millis(29_999);
24678 let mut s = three_member_spec();
24679 s.politicas.timeout = Some(timeout);
24680 s.politicas.circuit_breaker = Some(CircuitBreaker {
24681 max_failures: 5,
24682 window,
24683 });
24684 assert_eq!(
24685 s.validate().unwrap_err(),
24686 AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
24687 );
24688 }
24689
24690 #[test]
24691 fn cross_axis_gate_vacuous_when_timeout_absent() {
24692 // The predicate is vacuously `true` when `:timeout` is None —
24693 // a `:circuit-breaker` alone declares no relation to a
24694 // substrate-imposed deadline (the failure signal reaches the
24695 // breaker from the transport's own error surface, so no
24696 // dispatch-to-report lag is knowable at author time). Pin so
24697 // a future tightening that made the gate opinionated on
24698 // half-declared pairs surfaces here.
24699 let mut s = three_member_spec();
24700 s.politicas.timeout = None;
24701 s.politicas.circuit_breaker = Some(CircuitBreaker {
24702 max_failures: 5,
24703 window: Duration::from_millis(1),
24704 });
24705 s.validate().expect(
24706 "cross-axis gate must be vacuous when :timeout is None, however small :window is",
24707 );
24708 }
24709
24710 #[test]
24711 fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
24712 // Peer of the sibling `:timeout`-absent case: a `:timeout`
24713 // without a `:circuit-breaker` declares a per-call deadline
24714 // without any rolling-window failure accounting, so the pair
24715 // is undeclared and the cross-axis gate has nothing to check.
24716 let mut s = three_member_spec();
24717 s.politicas.timeout = Some(Duration::from_secs(3600));
24718 s.politicas.circuit_breaker = None;
24719 s.validate().expect(
24720 "cross-axis gate must be vacuous when :circuit-breaker is None, \
24721 however large :timeout is",
24722 );
24723 }
24724
24725 #[test]
24726 fn cross_axis_gate_runs_after_per_axis_brackets() {
24727 // Ordering pin: a pair whose window is *both* zero-floor-
24728 // violating and structurally below the timeout must surface
24729 // the per-axis zero-floor arm first — the zero-floor
24730 // diagnostic is more self-locating (its omit-axis remediation
24731 // is directly named), where the cross-axis arm would send the
24732 // author to reconcile two values one of which is not a
24733 // meaningful window at all. Same ordering discipline every
24734 // per-axis bracket carries internally (zero-floor before
24735 // canonical-form before cap).
24736 let mut s = three_member_spec();
24737 s.politicas.timeout = Some(Duration::from_secs(30));
24738 s.politicas.circuit_breaker = Some(CircuitBreaker {
24739 max_failures: 5,
24740 window: Duration::ZERO,
24741 });
24742 assert_eq!(
24743 s.validate().unwrap_err(),
24744 AplicacaoError::PolicyBreakerZeroWindow,
24745 "per-axis zero-floor arm must fire before the cross-axis gate"
24746 );
24747 }
24748
24749 #[test]
24750 fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
24751 // Equivalence pin: the substrate-canonical
24752 // [`MeshPolicy::breaker_window_observes_timeout`] predicate
24753 // and the [`AplicacaoSpec::validate_politicas`] cross-axis
24754 // arm must discriminate the same set on every pair covered
24755 // by their shared invariant. A future refactor of either
24756 // side that breaks the equivalence trips here rather than as
24757 // a divergence between the predicate's Boolean answer and
24758 // the validate gate's Ok/Err arm — the same
24759 // predicate-vs-gate coherence discipline the peer
24760 // [`PlacementStrategy::is_shard_keyed`] predicate carries
24761 // against `AplicacaoSpec::validate_placement`. The sweep
24762 // covers both arms of the invariant (below, equal, above)
24763 // and both vacuous arms (None `:timeout`, None
24764 // `:circuit-breaker`), so the equivalence holds
24765 // exhaustively over the axis-covered accept and reject sets.
24766 let cases: &[(Option<Duration>, Option<Duration>)] = &[
24767 (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
24768 (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
24769 (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
24770 (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
24771 (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
24772 (None, Some(Duration::from_secs(1))),
24773 (Some(Duration::from_secs(30)), None),
24774 (None, None),
24775 ];
24776 for (timeout, window) in cases.iter().copied() {
24777 let politicas = MeshPolicy {
24778 timeout,
24779 circuit_breaker: window.map(|w| CircuitBreaker {
24780 max_failures: 5,
24781 window: w,
24782 }),
24783 ..Default::default()
24784 };
24785 let predicate = politicas.breaker_window_observes_timeout();
24786
24787 let mut s = three_member_spec();
24788 s.politicas = politicas.clone();
24789 let gate_ok = !matches!(
24790 s.validate(),
24791 Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
24792 );
24793
24794 assert_eq!(
24795 predicate, gate_ok,
24796 "predicate must agree with validate arm on pair \
24797 (timeout={timeout:?}, window={window:?})"
24798 );
24799 }
24800 }
24801
24802 #[test]
24803 fn rejects_rate_limit_starves_circuit_breaker() {
24804 // The fail-before-pass-after pin on the cross-axis
24805 // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
24806 // individually well-formed under its own per-axis bracket
24807 // (both above the zero floor, both below the cap, rate-limit
24808 // window canonical), but the pair is a structurally-inert
24809 // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
24810 // calls per rolling breaker window, so no window can
24811 // accumulate five failures however catastrophic the upstream
24812 // failure rate.
24813 //
24814 // Envoy's `outlier_detection.consecutive_5xx` paired against
24815 // `local_rate_limit.token_bucket.max_tokens` /
24816 // `fill_interval` carries the identical relation; every
24817 // production playbook that pairs the two axes (Envoy, Istio,
24818 // AWS App Mesh, Kong) sizes the rate at or above the
24819 // breaker's minimum-request-volume threshold for exactly this
24820 // reason.
24821 //
24822 // Pin both the diagnostic arm and the payload values so a
24823 // future re-shape of the arm surfaces here as a deliberate
24824 // test edit. Clears `:timeout` so the sibling
24825 // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
24826 // does not fire first on the ordering-precedent it holds
24827 // over this arm.
24828 let mut s = three_member_spec();
24829 s.politicas.timeout = None;
24830 s.politicas.circuit_breaker = Some(CircuitBreaker {
24831 max_failures: 5,
24832 window: Duration::from_secs(10),
24833 });
24834 s.politicas.rate_limit = Some(RateLimit {
24835 rate: 1,
24836 window: Duration::from_secs(3600),
24837 });
24838 assert_eq!(
24839 s.validate().unwrap_err(),
24840 AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
24841 rate: 1,
24842 rl_window: Duration::from_secs(3600),
24843 max_failures: 5,
24844 cb_window: Duration::from_secs(10),
24845 }
24846 );
24847 }
24848
24849 #[test]
24850 fn accepts_rate_limit_can_trip_circuit_breaker() {
24851 // Positive-control sweep across the production-playbook band
24852 // — every pair a real playbook recommends where the rate
24853 // clearly admits enough calls per breaker window to reach
24854 // `:max-failures` must validate. Envoy default 5 failures
24855 // in 10s with 100/s (1000 calls / window, 200× the threshold),
24856 // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
24857 // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
24858 // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
24859 // the sibling cross-axis arm is vacuous on this sweep.
24860 for (rate, rl_window, max_failures, cb_window) in [
24861 (
24862 100u32,
24863 Duration::from_secs(1),
24864 5u32,
24865 Duration::from_secs(10),
24866 ),
24867 (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
24868 (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
24869 (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
24870 (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
24871 ] {
24872 let mut s = three_member_spec();
24873 s.politicas.timeout = None;
24874 s.politicas.circuit_breaker = Some(CircuitBreaker {
24875 max_failures,
24876 window: cb_window,
24877 });
24878 s.politicas.rate_limit = Some(RateLimit {
24879 rate,
24880 window: rl_window,
24881 });
24882 s.validate().unwrap_or_else(|e| {
24883 panic!(
24884 "production-playbook pair rate={rate}/{rl_window:?} \
24885 max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
24886 )
24887 });
24888 }
24889 }
24890
24891 #[test]
24892 fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
24893 // Boundary pin: `rate × cb_window == max_failures × rl_window`
24894 // is the smallest bucket capacity that structurally admits
24895 // exactly `max_failures` calls per rolling breaker window
24896 // (the invariant is `≥`, not strict inequality). Catches a
24897 // future off-by-one tightening to strict inequality that
24898 // would drift the accept set away from the codified
24899 // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
24900 // 5 calls/s over a 1s breaker window == 5 max_failures.
24901 let mut s = three_member_spec();
24902 s.politicas.timeout = None;
24903 s.politicas.circuit_breaker = Some(CircuitBreaker {
24904 max_failures: 5,
24905 window: Duration::from_secs(1),
24906 });
24907 s.politicas.rate_limit = Some(RateLimit {
24908 rate: 5,
24909 window: Duration::from_secs(1),
24910 });
24911 s.validate()
24912 .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
24913 }
24914
24915 #[test]
24916 fn rejects_rate_limit_one_call_short_per_cb_window() {
24917 // Off-by-one boundary pin: exactly one call short of the trip
24918 // threshold per breaker window is still structurally inert
24919 // (the invariant is `≥`, so `<` refuses even a one-call
24920 // shortfall). 4 calls/s over a 1s window == 4 admissible
24921 // failures, one shy of the 5-`max_failures` threshold.
24922 // Catches a future strict-inequality relaxation that would
24923 // silently drift the accept boundary.
24924 let mut s = three_member_spec();
24925 s.politicas.timeout = None;
24926 s.politicas.circuit_breaker = Some(CircuitBreaker {
24927 max_failures: 5,
24928 window: Duration::from_secs(1),
24929 });
24930 s.politicas.rate_limit = Some(RateLimit {
24931 rate: 4,
24932 window: Duration::from_secs(1),
24933 });
24934 assert_eq!(
24935 s.validate().unwrap_err(),
24936 AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
24937 rate: 4,
24938 rl_window: Duration::from_secs(1),
24939 max_failures: 5,
24940 cb_window: Duration::from_secs(1),
24941 }
24942 );
24943 }
24944
24945 #[test]
24946 fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
24947 // The predicate is vacuously `true` when `:rate-limit` is
24948 // None — a `:circuit-breaker` alone declares no relation to
24949 // a substrate-imposed call rate (the failure signal reaches
24950 // the breaker from the transport's own error surface, at
24951 // whatever rate upstream callers push traffic). Pin so a
24952 // future tightening that made the gate opinionated on
24953 // half-declared pairs surfaces here.
24954 let mut s = three_member_spec();
24955 s.politicas.timeout = None;
24956 s.politicas.circuit_breaker = Some(CircuitBreaker {
24957 max_failures: 1000,
24958 window: Duration::from_millis(1),
24959 });
24960 s.politicas.rate_limit = None;
24961 s.validate().expect(
24962 "cross-axis starve gate must be vacuous when :rate-limit is None, \
24963 however high :max-failures and however small :window are",
24964 );
24965 }
24966
24967 #[test]
24968 fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
24969 // Peer of the sibling `:rate-limit`-absent case: a
24970 // `:rate-limit` without a `:circuit-breaker` declares a
24971 // per-edge token-bucket rate without any failure counter to
24972 // starve, so the pair is undeclared and the cross-axis gate
24973 // has nothing to check.
24974 //
24975 // Also clears the fixture's `:retries` (which is `Some(3)`) so
24976 // the sibling cross-axis
24977 // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
24978 // (which reasons across the paired `(:retries, :rate-limit)`
24979 // pair independent of `:circuit-breaker`) is vacuous on this
24980 // pin — this test names the *starve* arm's vacuity on the
24981 // `:circuit-breaker`-absent case, not the burst arm's.
24982 let mut s = three_member_spec();
24983 s.politicas.timeout = None;
24984 s.politicas.retries = None;
24985 s.politicas.circuit_breaker = None;
24986 s.politicas.rate_limit = Some(RateLimit {
24987 rate: 1,
24988 window: Duration::from_secs(3600),
24989 });
24990 s.validate().expect(
24991 "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
24992 however low :rate is",
24993 );
24994 }
24995
24996 #[test]
24997 fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
24998 // Ordering pin: a pair whose rate is *both* zero-floor-
24999 // violating and structurally below the trip threshold must
25000 // surface the per-axis zero-floor arm first — the zero-floor
25001 // diagnostic is more self-locating (its omit-axis remediation
25002 // is directly named), where the cross-axis arm would send the
25003 // author to reconcile four values one of which is not a
25004 // meaningful rate at all. Same ordering discipline every
25005 // per-axis bracket carries internally (zero-floor before
25006 // canonical-form before cap), and the sibling cross-axis
25007 // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
25008 // ordering pins on the `(:timeout, :window)` pair.
25009 let mut s = three_member_spec();
25010 s.politicas.timeout = None;
25011 s.politicas.circuit_breaker = Some(CircuitBreaker {
25012 max_failures: 5,
25013 window: Duration::from_secs(10),
25014 });
25015 s.politicas.rate_limit = Some(RateLimit {
25016 rate: 0,
25017 window: Duration::from_secs(1),
25018 });
25019 assert_eq!(
25020 s.validate().unwrap_err(),
25021 AplicacaoError::PolicyRateLimitZero,
25022 "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
25023 );
25024 }
25025
25026 #[test]
25027 fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
25028 // Cross-axis ordering pin: a `:politicas` whose axes trip
25029 // BOTH cross-axis arms — `:window < :timeout` (the sibling
25030 // `PolicyBreakerWindowBelowTimeout` invariant) AND
25031 // `:rate-limit` starves the breaker within `:window` (this
25032 // arm) — must surface the timeout-relation diagnostic first.
25033 // The timeout arm is the per-call-deadline invariant every
25034 // synchronous edge carries whether or not `:rate-limit` is
25035 // declared, so its diagnostic is more self-locating; the
25036 // starve arm needs the reader to reason across three axes,
25037 // where the timeout arm names only two.
25038 //
25039 // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
25040 // pair trips both: the window is below the timeout, and the
25041 // rate (1 call/hour) admits far fewer than 5 calls per 10s
25042 // breaker window.
25043 let mut s = three_member_spec();
25044 s.politicas.timeout = Some(Duration::from_secs(30));
25045 s.politicas.circuit_breaker = Some(CircuitBreaker {
25046 max_failures: 5,
25047 window: Duration::from_secs(10),
25048 });
25049 s.politicas.rate_limit = Some(RateLimit {
25050 rate: 1,
25051 window: Duration::from_secs(3600),
25052 });
25053 assert_eq!(
25054 s.validate().unwrap_err(),
25055 AplicacaoError::PolicyBreakerWindowBelowTimeout {
25056 window: Duration::from_secs(10),
25057 timeout: Duration::from_secs(30),
25058 },
25059 "sibling :window<:timeout cross-axis arm must fire before the \
25060 starve arm when both apply"
25061 );
25062 }
25063
25064 #[test]
25065 fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
25066 // Equivalence pin: the substrate-canonical
25067 // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
25068 // and the [`AplicacaoSpec::validate_politicas`] cross-axis
25069 // arm must discriminate the same set on every pair covered
25070 // by their shared invariant. A future refactor of either
25071 // side that breaks the equivalence trips here rather than as
25072 // a divergence between the predicate's Boolean answer and
25073 // the validate gate's Ok/Err arm — the same
25074 // predicate-vs-gate coherence discipline the sibling
25075 // [`MeshPolicy::breaker_window_observes_timeout`] predicate
25076 // carries against `AplicacaoSpec::validate_politicas`. The
25077 // sweep covers both arms of the invariant (strictly below,
25078 // exactly at, strictly above) and both vacuous arms (None
25079 // `:rate-limit`, None `:circuit-breaker`), so the
25080 // equivalence holds exhaustively over the axis-covered
25081 // accept and reject sets. Clears `:timeout` throughout so
25082 // the sibling `:window<:timeout` gate is vacuous on every
25083 // input.
25084 let rl = |rate: u32, secs: u64| {
25085 Some(RateLimit {
25086 rate,
25087 window: Duration::from_secs(secs),
25088 })
25089 };
25090 let cb = |max_failures: u32, secs: u64| {
25091 Some(CircuitBreaker {
25092 max_failures,
25093 window: Duration::from_secs(secs),
25094 })
25095 };
25096 let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
25097 // starving pairs (predicate = false, gate = Err)
25098 (rl(1, 3600), cb(5, 10)),
25099 (rl(4, 1), cb(5, 1)),
25100 // boundary + coherent pairs (predicate = true, gate = Ok)
25101 (rl(5, 1), cb(5, 1)),
25102 (rl(100, 1), cb(5, 10)),
25103 // vacuous arms
25104 (None, cb(5, 10)),
25105 (rl(1, 3600), None),
25106 (None, None),
25107 ];
25108 for (rate_limit, circuit_breaker) in cases.iter().copied() {
25109 let politicas = MeshPolicy {
25110 circuit_breaker,
25111 rate_limit,
25112 ..Default::default()
25113 };
25114 let predicate = politicas.breaker_can_trip_under_rate_limit();
25115
25116 let mut s = three_member_spec();
25117 s.politicas = politicas.clone();
25118 s.politicas.timeout = None;
25119 let gate_ok = !matches!(
25120 s.validate(),
25121 Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
25122 );
25123
25124 assert_eq!(
25125 predicate, gate_ok,
25126 "predicate must agree with validate arm on pair \
25127 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
25128 );
25129 }
25130 }
25131
25132 #[test]
25133 fn rejects_retries_saturate_breaker_trip_threshold() {
25134 // The fail-before-pass-after pin on the cross-axis
25135 // `(:retries, :circuit-breaker :max-failures)` invariant. Each
25136 // axis is individually well-formed under its own per-axis
25137 // bracket (both above the zero floor, both below the cap), but
25138 // the pair is a structurally-truncated retry policy: one
25139 // client's `retries + 1 = 4` failing attempts hit the trip
25140 // threshold on the third attempt, the breaker opens, and the
25141 // fourth attempt (the last declared retry) is blocked by the
25142 // open breaker — the substrate declared four attempts and
25143 // structurally allows three.
25144 //
25145 // Envoy's `retry_policy.num_retries` paired against
25146 // `outlier_detection.consecutive_5xx` carries the identical
25147 // relation; every production playbook that pairs the two axes
25148 // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
25149 // trip threshold strictly above any single client's retry
25150 // budget so the breaker distinguishes one persistently-failing
25151 // client from sustained multi-client failure.
25152 //
25153 // Pin both the diagnostic arm and the payload values so a
25154 // future re-shape of the arm surfaces here as a deliberate
25155 // test edit. Clears `:timeout` and `:rate-limit` so the
25156 // sibling cross-axis
25157 // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
25158 // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
25159 // arms do not fire first on the ordering-precedent they hold
25160 // over this arm.
25161 let mut s = three_member_spec();
25162 s.politicas.timeout = None;
25163 s.politicas.retries = Some(3);
25164 s.politicas.circuit_breaker = Some(CircuitBreaker {
25165 max_failures: 3,
25166 window: Duration::from_secs(1),
25167 });
25168 s.politicas.rate_limit = None;
25169 assert_eq!(
25170 s.validate().unwrap_err(),
25171 AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
25172 retries: 3,
25173 max_failures: 3,
25174 }
25175 );
25176 }
25177
25178 #[test]
25179 fn accepts_retries_below_breaker_trip_threshold() {
25180 // Positive-control sweep across the production-playbook band
25181 // — every pair a real playbook recommends where the breaker's
25182 // trip threshold is strictly above the client's retry budget
25183 // must validate. Envoy default `num_retries: 3` with
25184 // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
25185 // opens on multi-client failures beyond that); Istio
25186 // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
25187 // `execution.isolation.thread.timeoutInMilliseconds` + 3
25188 // retries with `requestVolumeThreshold: 20`; AWS App Mesh
25189 // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
25190 // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
25191 // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
25192 // arms are vacuous on this sweep.
25193 for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
25194 {
25195 let mut s = three_member_spec();
25196 s.politicas.timeout = None;
25197 s.politicas.retries = Some(retries);
25198 s.politicas.circuit_breaker = Some(CircuitBreaker {
25199 max_failures,
25200 window: Duration::from_secs(60),
25201 });
25202 s.politicas.rate_limit = None;
25203 s.validate().unwrap_or_else(|e| {
25204 panic!(
25205 "production-playbook pair retries={retries} \
25206 max_failures={max_failures} must validate; got {e:?}"
25207 )
25208 });
25209 }
25210 }
25211
25212 #[test]
25213 fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
25214 // Boundary pin: `max_failures == retries + 1` is the smallest
25215 // trip threshold that admits one client's exhausted retries
25216 // through completion (the R+1th failure — the last declared
25217 // retry — trips the breaker exactly as it completes, so
25218 // retries fully executed). The invariant is `>`, not `>=`,
25219 // stated in the coherent direction `max_failures > retries`.
25220 // Catches a future off-by-one tightening to
25221 // `max_failures > retries + 1` that would drift the accept set
25222 // away from the codified
25223 // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
25224 // predicate.
25225 let mut s = three_member_spec();
25226 s.politicas.timeout = None;
25227 s.politicas.retries = Some(3);
25228 s.politicas.circuit_breaker = Some(CircuitBreaker {
25229 max_failures: 4,
25230 window: Duration::from_secs(60),
25231 });
25232 s.politicas.rate_limit = None;
25233 s.validate()
25234 .expect("max_failures == retries + 1 is the boundary accept case");
25235 }
25236
25237 #[test]
25238 fn rejects_retries_equal_to_breaker_trip_threshold() {
25239 // Off-by-one boundary pin: exactly at the trip threshold is
25240 // still structurally truncating (the invariant is `>`, so `<=`
25241 // refuses even the tight boundary). `retries = 3` with
25242 // `max_failures = 3` means the breaker trips on the third
25243 // failure — the last declared retry attempt is blocked.
25244 // Catches a future relaxation to `>=` that would silently
25245 // drift the accept boundary.
25246 let mut s = three_member_spec();
25247 s.politicas.timeout = None;
25248 s.politicas.retries = Some(3);
25249 s.politicas.circuit_breaker = Some(CircuitBreaker {
25250 max_failures: 3,
25251 window: Duration::from_secs(60),
25252 });
25253 s.politicas.rate_limit = None;
25254 assert_eq!(
25255 s.validate().unwrap_err(),
25256 AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
25257 retries: 3,
25258 max_failures: 3,
25259 }
25260 );
25261 }
25262
25263 #[test]
25264 fn cross_axis_retries_gate_vacuous_when_retries_absent() {
25265 // The predicate is vacuously `true` when `:retries` is None —
25266 // a `:circuit-breaker` alone declares a failure counter whose
25267 // per-client attempt count is unconstrained by the substrate,
25268 // so no per-client saturation bound on failures-per-client-call
25269 // is knowable at author time. The substrate takes no position
25270 // on whether an omitted `:retries` axis means zero retries or
25271 // "the client picks its own retry policy" — either way, the
25272 // pair is undeclared and the cross-axis gate has nothing to
25273 // check. Pin so a future tightening that made the gate
25274 // opinionated on half-declared pairs surfaces here.
25275 let mut s = three_member_spec();
25276 s.politicas.timeout = None;
25277 s.politicas.retries = None;
25278 s.politicas.circuit_breaker = Some(CircuitBreaker {
25279 max_failures: 1,
25280 window: Duration::from_secs(60),
25281 });
25282 s.politicas.rate_limit = None;
25283 s.validate().expect(
25284 "cross-axis retries gate must be vacuous when :retries is None, \
25285 however low :max-failures is",
25286 );
25287 }
25288
25289 #[test]
25290 fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
25291 // Peer of the sibling `:retries`-absent case: a `:retries`
25292 // without a `:circuit-breaker` declares a client-retry policy
25293 // with no failure counter to trip, so the pair is undeclared
25294 // and the cross-axis gate has nothing to check.
25295 let mut s = three_member_spec();
25296 s.politicas.timeout = None;
25297 s.politicas.retries = Some(POLICY_RETRIES_MAX);
25298 s.politicas.circuit_breaker = None;
25299 s.politicas.rate_limit = None;
25300 s.validate().expect(
25301 "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
25302 however high :retries is",
25303 );
25304 }
25305
25306 #[test]
25307 fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
25308 // Ordering pin: a pair whose retries is *both* zero-floor-
25309 // violating and structurally at-or-below the trip threshold
25310 // must surface the per-axis zero-floor arm first — the
25311 // zero-floor diagnostic is more self-locating (its omit-axis
25312 // remediation is directly named), where the cross-axis arm
25313 // would send the author to reconcile two values one of which
25314 // is not a meaningful retry count at all. Same ordering
25315 // discipline every per-axis bracket carries internally
25316 // (zero-floor before canonical-form before cap), and the
25317 // sibling cross-axis
25318 // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
25319 // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
25320 let mut s = three_member_spec();
25321 s.politicas.timeout = None;
25322 s.politicas.retries = Some(0);
25323 s.politicas.circuit_breaker = Some(CircuitBreaker {
25324 max_failures: 3,
25325 window: Duration::from_secs(60),
25326 });
25327 s.politicas.rate_limit = None;
25328 assert_eq!(
25329 s.validate().unwrap_err(),
25330 AplicacaoError::PolicyRetriesZero,
25331 "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
25332 );
25333 }
25334
25335 #[test]
25336 fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
25337 // Cross-axis ordering pin: a `:politicas` whose axes trip
25338 // BOTH cross-axis arms — `:rate-limit` starves the breaker
25339 // within `:window` (the sibling
25340 // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
25341 // `:retries + 1` saturates `:max-failures` (this arm) — must
25342 // surface the rate-limit-starve diagnostic first. The
25343 // rate-limit-starve arm reasons across the token-bucket
25344 // admission axis every rate-limited edge carries whether or
25345 // not `:retries` is declared, so its diagnostic is more
25346 // self-locating; the retries-saturate arm reasons across a
25347 // per-client retry-policy budget the starve arm does not
25348 // touch.
25349 //
25350 // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
25351 // pair trips both: the rate structurally cannot deliver 5
25352 // failures per 10s breaker window, and simultaneously
25353 // one client's `retries + 1 = 6` attempts alone would
25354 // saturate the 5-`max_failures` threshold.
25355 let mut s = three_member_spec();
25356 s.politicas.timeout = None;
25357 s.politicas.retries = Some(5);
25358 s.politicas.circuit_breaker = Some(CircuitBreaker {
25359 max_failures: 5,
25360 window: Duration::from_secs(10),
25361 });
25362 s.politicas.rate_limit = Some(RateLimit {
25363 rate: 1,
25364 window: Duration::from_secs(3600),
25365 });
25366 assert_eq!(
25367 s.validate().unwrap_err(),
25368 AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
25369 rate: 1,
25370 rl_window: Duration::from_secs(3600),
25371 max_failures: 5,
25372 cb_window: Duration::from_secs(10),
25373 },
25374 "sibling :rate-limit-starve cross-axis arm must fire before the \
25375 retries-saturate arm when both apply"
25376 );
25377 }
25378
25379 #[test]
25380 fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
25381 // Equivalence pin: the substrate-canonical
25382 // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
25383 // predicate and the [`AplicacaoSpec::validate_politicas`]
25384 // cross-axis arm must discriminate the same set on every pair
25385 // covered by their shared invariant. A future refactor of
25386 // either side that breaks the equivalence trips here rather
25387 // than as a divergence between the predicate's Boolean answer
25388 // and the validate gate's Ok/Err arm — the same
25389 // predicate-vs-gate coherence discipline the sibling
25390 // [`MeshPolicy::breaker_window_observes_timeout`] and
25391 // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
25392 // carry against `AplicacaoSpec::validate_politicas`. The
25393 // sweep covers both arms of the invariant (strictly below,
25394 // exactly at the boundary, strictly above) and both vacuous
25395 // arms (None `:retries`, None `:circuit-breaker`), so the
25396 // equivalence holds exhaustively over the axis-covered accept
25397 // and reject sets. Clears `:timeout` and `:rate-limit`
25398 // throughout so the sibling cross-axis arms are vacuous on
25399 // every input.
25400 let cb = |max_failures: u32| {
25401 Some(CircuitBreaker {
25402 max_failures,
25403 window: Duration::from_secs(60),
25404 })
25405 };
25406 let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
25407 // saturating pairs (predicate = false, gate = Err)
25408 (Some(3), cb(3)),
25409 (Some(3), cb(1)),
25410 (Some(10), cb(5)),
25411 // boundary + coherent pairs (predicate = true, gate = Ok)
25412 (Some(3), cb(4)),
25413 (Some(1), cb(5)),
25414 (Some(3), cb(20)),
25415 // vacuous arms
25416 (None, cb(1)),
25417 (Some(10), None),
25418 (None, None),
25419 ];
25420 for (retries, circuit_breaker) in cases.iter().copied() {
25421 let politicas = MeshPolicy {
25422 retries,
25423 circuit_breaker,
25424 ..Default::default()
25425 };
25426 let predicate = politicas.retries_fit_under_breaker_trip_threshold();
25427
25428 let mut s = three_member_spec();
25429 s.politicas = politicas.clone();
25430 let gate_ok = !matches!(
25431 s.validate(),
25432 Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
25433 );
25434
25435 assert_eq!(
25436 predicate, gate_ok,
25437 "predicate must agree with validate arm on pair \
25438 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
25439 );
25440 }
25441 }
25442
25443 #[test]
25444 fn rejects_rate_limit_cannot_admit_retry_burst() {
25445 // The fail-before-pass-after pin on the cross-axis
25446 // `(:retries, :rate-limit)` invariant. Each axis is
25447 // individually well-formed under its own per-axis bracket (both
25448 // above the zero floor, both below the cap), but the pair is a
25449 // structurally-truncated retry policy: one client's
25450 // `retries + 1 = 6` failing attempts consume 6 tokens from a
25451 // bucket that admits at most 3 per refill window, so the fourth
25452 // attempt onward is 429ed by the local rate limiter and the
25453 // declared retry policy is silently truncated by the same rate
25454 // limiter it feeds through — the substrate declared six
25455 // attempts and structurally allows three.
25456 //
25457 // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
25458 // against `retry_policy.num_retries` carries the identical
25459 // relation; every production playbook that pairs the two axes
25460 // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
25461 // capacity strictly above any single client's retry budget so
25462 // the limiter distinguishes one client's declared retries from
25463 // sustained multi-client load.
25464 //
25465 // Pin both the diagnostic arm and the payload values so a
25466 // future re-shape of the arm surfaces here as a deliberate
25467 // test edit. Clears `:timeout` and `:circuit-breaker` so the
25468 // sibling cross-axis
25469 // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
25470 // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
25471 // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
25472 // arms do not fire first on the ordering-precedent they hold
25473 // over this arm.
25474 let mut s = three_member_spec();
25475 s.politicas.timeout = None;
25476 s.politicas.retries = Some(5);
25477 s.politicas.circuit_breaker = None;
25478 s.politicas.rate_limit = Some(RateLimit {
25479 rate: 3,
25480 window: Duration::from_secs(1),
25481 });
25482 assert_eq!(
25483 s.validate().unwrap_err(),
25484 AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
25485 retries: 5,
25486 rate: 3,
25487 }
25488 );
25489 }
25490
25491 #[test]
25492 fn accepts_rate_limit_admits_retry_burst() {
25493 // Positive-control sweep across the production-playbook band
25494 // — every pair a real playbook recommends where the bucket
25495 // capacity is strictly above the client's retry budget must
25496 // validate. Envoy default `num_retries: 3` with 100/s (100
25497 // tokens per window admits 4 attempts per client with 96 to
25498 // spare); Istio `attempts: 3` with 50/s (50 admits 4);
25499 // resilience4j 2 retries with 10/s (10 admits 3); AWS App
25500 // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
25501 // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
25502 // `:timeout` and `:circuit-breaker` so the sibling cross-axis
25503 // arms are vacuous on this sweep.
25504 for (retries, rate, secs) in [
25505 (3u32, 100u32, 1u64),
25506 (3, 50, 1),
25507 (2, 10, 1),
25508 (5, 1000, 1),
25509 (3, 1_000_000, 3600),
25510 (10, POLICY_RATE_LIMIT_MAX, 1),
25511 ] {
25512 let mut s = three_member_spec();
25513 s.politicas.timeout = None;
25514 s.politicas.retries = Some(retries);
25515 s.politicas.circuit_breaker = None;
25516 s.politicas.rate_limit = Some(RateLimit {
25517 rate,
25518 window: Duration::from_secs(secs),
25519 });
25520 s.validate().unwrap_or_else(|e| {
25521 panic!(
25522 "production-playbook pair retries={retries} rate={rate}/{secs}s \
25523 must validate; got {e:?}"
25524 )
25525 });
25526 }
25527 }
25528
25529 #[test]
25530 fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
25531 // Boundary pin: `rate == retries + 1` is the smallest bucket
25532 // capacity that structurally admits one client's exhausted
25533 // retries through completion (each attempt draws exactly one
25534 // token; `retries + 1` tokens available admits `retries + 1`
25535 // attempts, retries fully executed). The invariant is `>=`,
25536 // stated in the coherent direction `rate >= retries + 1`.
25537 // Catches a future off-by-one tightening to `rate > retries + 1`
25538 // that would drift the accept set away from the codified
25539 // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
25540 let mut s = three_member_spec();
25541 s.politicas.timeout = None;
25542 s.politicas.retries = Some(3);
25543 s.politicas.circuit_breaker = None;
25544 s.politicas.rate_limit = Some(RateLimit {
25545 rate: 4,
25546 window: Duration::from_secs(1),
25547 });
25548 s.validate()
25549 .expect("rate == retries + 1 is the boundary accept case");
25550 }
25551
25552 #[test]
25553 fn rejects_rate_one_below_retry_burst() {
25554 // Off-by-one boundary pin: exactly one token short of the
25555 // retry burst is still structurally truncating (the invariant
25556 // is `>=`, so `<` refuses even a one-token shortfall).
25557 // `retries = 3` with `rate = 3` means one client's four
25558 // attempts consume four tokens from a three-token bucket —
25559 // the fourth attempt is 429ed. Catches a future relaxation to
25560 // `>` on the wrong side (`rate > retries`, accepting equal)
25561 // that would silently drift the accept boundary and admit a
25562 // structurally-truncated retry policy at the emit boundary.
25563 let mut s = three_member_spec();
25564 s.politicas.timeout = None;
25565 s.politicas.retries = Some(3);
25566 s.politicas.circuit_breaker = None;
25567 s.politicas.rate_limit = Some(RateLimit {
25568 rate: 3,
25569 window: Duration::from_secs(1),
25570 });
25571 assert_eq!(
25572 s.validate().unwrap_err(),
25573 AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
25574 retries: 3,
25575 rate: 3,
25576 }
25577 );
25578 }
25579
25580 #[test]
25581 fn cross_axis_burst_gate_vacuous_when_retries_absent() {
25582 // The predicate is vacuously `true` when `:retries` is None —
25583 // a `:rate-limit` alone declares a token-bucket rate whose
25584 // per-client attempt count is unconstrained by the substrate,
25585 // so no per-client saturation bound on tokens-per-client-call
25586 // is knowable at author time. The substrate takes no position
25587 // on whether an omitted `:retries` axis means zero retries or
25588 // "the client picks its own retry policy" — either way, the
25589 // pair is undeclared and the cross-axis gate has nothing to
25590 // check. Pin so a future tightening that made the gate
25591 // opinionated on half-declared pairs surfaces here.
25592 let mut s = three_member_spec();
25593 s.politicas.timeout = None;
25594 s.politicas.retries = None;
25595 s.politicas.circuit_breaker = None;
25596 s.politicas.rate_limit = Some(RateLimit {
25597 rate: 1,
25598 window: Duration::from_secs(1),
25599 });
25600 s.validate().expect(
25601 "cross-axis burst gate must be vacuous when :retries is None, \
25602 however low :rate is",
25603 );
25604 }
25605
25606 #[test]
25607 fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
25608 // Peer of the sibling `:retries`-absent case: a `:retries`
25609 // without a `:rate-limit` declares a client-retry policy with
25610 // no rate limiter to saturate, so the pair is undeclared and
25611 // the cross-axis gate has nothing to check. Uses
25612 // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
25613 // authored retry budget the per-axis cap admits — a `:retries
25614 // POLICY_RETRIES_MAX` alone must remain a clean pass whether
25615 // or not `:rate-limit` is declared.
25616 let mut s = three_member_spec();
25617 s.politicas.timeout = None;
25618 s.politicas.retries = Some(POLICY_RETRIES_MAX);
25619 s.politicas.circuit_breaker = None;
25620 s.politicas.rate_limit = None;
25621 s.validate().expect(
25622 "cross-axis burst gate must be vacuous when :rate-limit is None, \
25623 however high :retries is",
25624 );
25625 }
25626
25627 #[test]
25628 fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
25629 // Ordering pin: a pair whose retries is *both* zero-floor-
25630 // violating and structurally below the retry-burst threshold
25631 // must surface the per-axis zero-floor arm first — the
25632 // zero-floor diagnostic is more self-locating (its omit-axis
25633 // remediation is directly named), where the cross-axis arm
25634 // would send the author to reconcile two values one of which
25635 // is not a meaningful retry count at all. Same ordering
25636 // discipline every per-axis bracket carries internally
25637 // (zero-floor before canonical-form before cap), and the
25638 // sibling cross-axis
25639 // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
25640 // ordering pin on the `(:retries, :max-failures)` pair.
25641 let mut s = three_member_spec();
25642 s.politicas.timeout = None;
25643 s.politicas.retries = Some(0);
25644 s.politicas.circuit_breaker = None;
25645 s.politicas.rate_limit = Some(RateLimit {
25646 rate: 1,
25647 window: Duration::from_secs(1),
25648 });
25649 assert_eq!(
25650 s.validate().unwrap_err(),
25651 AplicacaoError::PolicyRetriesZero,
25652 "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
25653 );
25654 }
25655
25656 #[test]
25657 fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
25658 // Cross-axis ordering pin: a `:politicas` whose axes trip
25659 // BOTH cross-axis arms — `:rate-limit` starves the breaker
25660 // within `:window` (the sibling
25661 // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
25662 // `:retries + 1` exceeds the bucket capacity (this arm) —
25663 // must surface the rate-limit-starve diagnostic first. The
25664 // starve arm is the token-bucket admission invariant every
25665 // rate-limited edge carries against the breaker whether or
25666 // not `:retries` is declared, so its diagnostic is more
25667 // self-locating; the burst arm reasons across a per-client
25668 // retry-policy budget the starve arm does not touch. Same
25669 // "more foundational cross-axis first" ordering discipline the
25670 // sibling
25671 // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
25672 // pin on the peer pair carries.
25673 //
25674 // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
25675 // pair trips both: the rate structurally cannot deliver 5
25676 // failures per 10s breaker window (starve arm), and
25677 // simultaneously one client's `retries + 1 = 6` attempts alone
25678 // would exhaust the 1-token bucket (burst arm).
25679 let mut s = three_member_spec();
25680 s.politicas.timeout = None;
25681 s.politicas.retries = Some(5);
25682 s.politicas.circuit_breaker = Some(CircuitBreaker {
25683 max_failures: 5,
25684 window: Duration::from_secs(10),
25685 });
25686 s.politicas.rate_limit = Some(RateLimit {
25687 rate: 1,
25688 window: Duration::from_secs(3600),
25689 });
25690 assert_eq!(
25691 s.validate().unwrap_err(),
25692 AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
25693 rate: 1,
25694 rl_window: Duration::from_secs(3600),
25695 max_failures: 5,
25696 cb_window: Duration::from_secs(10),
25697 },
25698 "sibling :rate-limit-starve cross-axis arm must fire before the \
25699 burst arm when both apply"
25700 );
25701 }
25702
25703 #[test]
25704 fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
25705 // Cross-axis ordering pin: a `:politicas` whose axes trip
25706 // BOTH the retries-saturate arm and this burst arm — one
25707 // client's `retries + 1` failures saturate the breaker's trip
25708 // threshold (the sibling
25709 // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
25710 // `retries + 1` exceeds the bucket capacity (this arm) —
25711 // must surface the retries-saturate diagnostic first. The
25712 // saturate arm is the per-client-vs-breaker relation every
25713 // retry-with-breaker pair carries whether or not `:rate-limit`
25714 // is declared, so its diagnostic is more self-locating; the
25715 // burst arm reasons across the rate-limit token-bucket
25716 // admission axis the saturate arm does not touch. Same
25717 // "more foundational cross-axis first" ordering discipline
25718 // carries here.
25719 //
25720 // A `{ retries: 5, max_failures: 3, cb_window: 60s,
25721 // rate: 3/s }` pair trips both: the breaker's `max_failures
25722 // = 3` is `<= retries = 5` (saturate arm), and simultaneously
25723 // one client's `retries + 1 = 6` attempts alone would exhaust
25724 // the 3-token bucket (burst arm). Clears `:timeout` so the
25725 // sibling `:window<:timeout` gate is vacuous, and the
25726 // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
25727 // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
25728 // the arm that fires first.
25729 let mut s = three_member_spec();
25730 s.politicas.timeout = None;
25731 s.politicas.retries = Some(5);
25732 s.politicas.circuit_breaker = Some(CircuitBreaker {
25733 max_failures: 3,
25734 window: Duration::from_secs(60),
25735 });
25736 s.politicas.rate_limit = Some(RateLimit {
25737 rate: 3,
25738 window: Duration::from_secs(1),
25739 });
25740 assert_eq!(
25741 s.validate().unwrap_err(),
25742 AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
25743 retries: 5,
25744 max_failures: 3,
25745 },
25746 "sibling :retries-saturate cross-axis arm must fire before the \
25747 burst arm when both apply"
25748 );
25749 }
25750
25751 #[test]
25752 fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
25753 // Equivalence pin: the substrate-canonical
25754 // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
25755 // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
25756 // must discriminate the same set on every pair covered by
25757 // their shared invariant. A future refactor of either side
25758 // that breaks the equivalence trips here rather than as a
25759 // divergence between the predicate's Boolean answer and the
25760 // validate gate's Ok/Err arm — the same predicate-vs-gate
25761 // coherence discipline the three sibling cross-axis
25762 // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
25763 // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
25764 // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
25765 // carry against `AplicacaoSpec::validate_politicas`. The sweep
25766 // covers both arms of the invariant (strictly below, exactly
25767 // at the boundary, strictly above) and both vacuous arms
25768 // (None `:retries`, None `:rate-limit`), so the equivalence
25769 // holds exhaustively over the axis-covered accept and reject
25770 // sets. Clears `:timeout` and `:circuit-breaker` throughout
25771 // so the three sibling cross-axis arms are vacuous on every
25772 // input.
25773 let rl = |rate: u32, secs: u64| {
25774 Some(RateLimit {
25775 rate,
25776 window: Duration::from_secs(secs),
25777 })
25778 };
25779 let cases: &[(Option<u32>, Option<RateLimit>)] = &[
25780 // burst-exceeding pairs (predicate = false, gate = Err)
25781 (Some(3), rl(3, 1)),
25782 (Some(5), rl(1, 1)),
25783 (Some(10), rl(5, 1)),
25784 // boundary + coherent pairs (predicate = true, gate = Ok)
25785 (Some(3), rl(4, 1)),
25786 (Some(1), rl(5, 1)),
25787 (Some(3), rl(1_000_000, 3600)),
25788 // vacuous arms
25789 (None, rl(1, 1)),
25790 (Some(10), None),
25791 (None, None),
25792 ];
25793 for (retries, rate_limit) in cases.iter().copied() {
25794 let politicas = MeshPolicy {
25795 retries,
25796 rate_limit,
25797 ..Default::default()
25798 };
25799 let predicate = politicas.rate_limit_admits_retry_burst();
25800
25801 let mut s = three_member_spec();
25802 s.politicas = politicas.clone();
25803 let gate_ok = !matches!(
25804 s.validate(),
25805 Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
25806 );
25807
25808 assert_eq!(
25809 predicate, gate_ok,
25810 "predicate must agree with validate arm on pair \
25811 (retries={retries:?}, rate_limit={rate_limit:?})"
25812 );
25813 }
25814 }
25815
25816 /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
25817 /// equivalence pin — assert that on each `(label, politicas,
25818 /// expected)` case the substrate-canonical fold and the validate
25819 /// cascade agree byte-for-byte. Extracted so each pin's own body
25820 /// stays under `clippy::too_many_lines`.
25821 fn assert_first_cross_axis_violation_agrees_with_gate(
25822 cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
25823 ) {
25824 for (label, politicas, expected) in cases {
25825 let fold = politicas.first_cross_axis_violation();
25826 assert_eq!(
25827 fold.as_ref(),
25828 expected.as_ref(),
25829 "fold must return {expected:?} on `{label}`; got {fold:?}"
25830 );
25831
25832 let mut s = three_member_spec();
25833 s.politicas = politicas.clone();
25834 let gate = s.validate();
25835 match expected {
25836 None => {
25837 // No cross-axis violation: validate must pass (the
25838 // per-axis brackets pass by construction on every
25839 // fixture above; every fixture's non-`:politicas`
25840 // slots come from `three_member_spec`).
25841 gate.as_ref()
25842 .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
25843 }
25844 Some(want) => {
25845 let got =
25846 gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
25847 assert_eq!(
25848 &got, want,
25849 "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
25850 );
25851 }
25852 }
25853 }
25854 }
25855
25856 #[test]
25857 fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
25858 // Equivalence pin on the compound cross-axis fold: the
25859 // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
25860 // and the [`AplicacaoSpec::validate_politicas`] cross-axis
25861 // cascade must return identical `AplicacaoError` variants on
25862 // every axis-covered input — the "compound-fold ≡ gate"
25863 // contract that generalizes the four sibling per-arm pins
25864 // onto the compound primitive that folds all four. A future
25865 // refactor of either side that breaks the equivalence trips
25866 // here rather than as a divergence between what the substrate
25867 // primitive answers and what `feira build` accepts.
25868 //
25869 // Half-A of the sweep: every single-arm violation (one arm
25870 // fires with the three sibling arms vacuous), the vacuous
25871 // shape (empty policy — no arm fires), and the fully-coherent
25872 // shape (every axis declared inside the coherence surface —
25873 // no arm fires). Half-B (pairwise-ordering coverage — the
25874 // "which arm wins when two apply" contract) lives in the
25875 // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
25876 // pin; splitting keeps each pin's body under
25877 // `clippy::too_many_lines`.
25878 let cb = |max_failures: u32, secs: u64| CircuitBreaker {
25879 max_failures,
25880 window: Duration::from_secs(secs),
25881 };
25882 let rl = |rate: u32, secs: u64| RateLimit {
25883 rate,
25884 window: Duration::from_secs(secs),
25885 };
25886 let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
25887 (
25888 "window-below-timeout only",
25889 MeshPolicy {
25890 timeout: Some(Duration::from_secs(30)),
25891 circuit_breaker: Some(cb(5, 10)),
25892 ..Default::default()
25893 },
25894 Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
25895 window: Duration::from_secs(10),
25896 timeout: Duration::from_secs(30),
25897 }),
25898 ),
25899 (
25900 "starve only",
25901 MeshPolicy {
25902 rate_limit: Some(rl(1, 3600)),
25903 circuit_breaker: Some(cb(5, 10)),
25904 ..Default::default()
25905 },
25906 Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
25907 rate: 1,
25908 rl_window: Duration::from_secs(3600),
25909 max_failures: 5,
25910 cb_window: Duration::from_secs(10),
25911 }),
25912 ),
25913 (
25914 "retries-saturate only",
25915 MeshPolicy {
25916 retries: Some(3),
25917 circuit_breaker: Some(cb(3, 60)),
25918 ..Default::default()
25919 },
25920 Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
25921 retries: 3,
25922 max_failures: 3,
25923 }),
25924 ),
25925 (
25926 "retries-burst only",
25927 MeshPolicy {
25928 retries: Some(5),
25929 rate_limit: Some(rl(3, 1)),
25930 ..Default::default()
25931 },
25932 Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
25933 retries: 5,
25934 rate: 3,
25935 }),
25936 ),
25937 ("empty policy", MeshPolicy::default(), None),
25938 (
25939 "fully-coherent policy",
25940 MeshPolicy {
25941 timeout: Some(Duration::from_secs(30)),
25942 retries: Some(3),
25943 circuit_breaker: Some(cb(5, 60)),
25944 mtls_required: Some(true),
25945 rate_limit: Some(rl(100, 1)),
25946 },
25947 None,
25948 ),
25949 ];
25950 assert_first_cross_axis_violation_agrees_with_gate(cases);
25951 }
25952
25953 #[test]
25954 fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
25955 // Half-B of the compound-fold ≡ gate equivalence pin: the
25956 // load-bearing pairwise-ordering coverage. Every ordered pair
25957 // of the four cross-axis arms — six combinations — where two
25958 // arms are simultaneously eligible must surface the
25959 // more-foundational arm's diagnostic verbatim. Pins the fold's
25960 // arm-ordering byte-for-byte against the validate cascade's
25961 // arm-ordering, so a future reshuffle of either side that
25962 // silently drifts the ordering trips here rather than as a
25963 // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
25964 // pins cannot catch (they clear every sibling arm, so their
25965 // sweeps are pairwise-ordering-agnostic by construction).
25966 //
25967 // The six pairs the four-arm cascade admits:
25968 // window-before-starve, window-before-saturate,
25969 // window-before-burst, starve-before-saturate,
25970 // starve-before-burst, saturate-before-burst.
25971 let cb = |max_failures: u32, secs: u64| CircuitBreaker {
25972 max_failures,
25973 window: Duration::from_secs(secs),
25974 };
25975 let rl = |rate: u32, secs: u64| RateLimit {
25976 rate,
25977 window: Duration::from_secs(secs),
25978 };
25979 let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
25980 (
25981 "window+starve → window wins",
25982 MeshPolicy {
25983 timeout: Some(Duration::from_secs(30)),
25984 rate_limit: Some(rl(1, 3600)),
25985 circuit_breaker: Some(cb(5, 10)),
25986 ..Default::default()
25987 },
25988 Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
25989 window: Duration::from_secs(10),
25990 timeout: Duration::from_secs(30),
25991 }),
25992 ),
25993 (
25994 "window+retries-saturate → window wins",
25995 MeshPolicy {
25996 timeout: Some(Duration::from_secs(30)),
25997 retries: Some(5),
25998 circuit_breaker: Some(cb(3, 10)),
25999 ..Default::default()
26000 },
26001 Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
26002 window: Duration::from_secs(10),
26003 timeout: Duration::from_secs(30),
26004 }),
26005 ),
26006 (
26007 "window+retries-burst → window wins",
26008 MeshPolicy {
26009 timeout: Some(Duration::from_secs(30)),
26010 retries: Some(5),
26011 rate_limit: Some(rl(3, 1)),
26012 circuit_breaker: Some(cb(5, 10)),
26013 ..Default::default()
26014 },
26015 Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
26016 window: Duration::from_secs(10),
26017 timeout: Duration::from_secs(30),
26018 }),
26019 ),
26020 (
26021 "starve+retries-saturate → starve wins",
26022 MeshPolicy {
26023 retries: Some(5),
26024 rate_limit: Some(rl(1, 3600)),
26025 circuit_breaker: Some(cb(5, 10)),
26026 ..Default::default()
26027 },
26028 Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
26029 rate: 1,
26030 rl_window: Duration::from_secs(3600),
26031 max_failures: 5,
26032 cb_window: Duration::from_secs(10),
26033 }),
26034 ),
26035 (
26036 "starve+retries-burst → starve wins",
26037 MeshPolicy {
26038 retries: Some(5),
26039 rate_limit: Some(rl(1, 3600)),
26040 circuit_breaker: Some(cb(10, 10)),
26041 ..Default::default()
26042 },
26043 Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
26044 rate: 1,
26045 rl_window: Duration::from_secs(3600),
26046 max_failures: 10,
26047 cb_window: Duration::from_secs(10),
26048 }),
26049 ),
26050 (
26051 "retries-saturate+retries-burst → saturate wins",
26052 MeshPolicy {
26053 retries: Some(5),
26054 rate_limit: Some(rl(3, 1)),
26055 circuit_breaker: Some(cb(3, 60)),
26056 ..Default::default()
26057 },
26058 Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
26059 retries: 5,
26060 max_failures: 3,
26061 }),
26062 ),
26063 ];
26064 assert_first_cross_axis_violation_agrees_with_gate(cases);
26065 }
26066
26067 /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
26068 /// equivalence pin — assert that on each `(label, politicas,
26069 /// expected)` case both the substrate primitive
26070 /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
26071 /// cascade (reached through `AplicacaoSpec::validate`, keying off the
26072 /// same `three_member_spec` fixture whose non-`:politicas` slots
26073 /// always validate cleanly) return identical `AplicacaoError` variants.
26074 /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
26075 /// the sibling cross-axis-only surface — extended here onto the
26076 /// compound per-axis + cross-axis entry gate. Extracted so each pin's
26077 /// own body stays under `clippy::too_many_lines`.
26078 fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
26079 for (label, politicas, expected) in cases {
26080 let direct = politicas.validate();
26081 match (expected, &direct) {
26082 (None, Ok(())) => {}
26083 (None, Err(got)) => {
26084 panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
26085 }
26086 (Some(want), Ok(())) => {
26087 panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
26088 }
26089 (Some(want), Err(got)) => assert_eq!(
26090 got, want,
26091 "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
26092 ),
26093 }
26094
26095 let mut s = three_member_spec();
26096 s.politicas = politicas.clone();
26097 let gate = s.validate();
26098 match (expected, &gate) {
26099 (None, Ok(())) => {}
26100 (None, Err(got)) => {
26101 panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
26102 }
26103 (Some(want), Ok(())) => {
26104 panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
26105 }
26106 (Some(want), Err(got)) => assert_eq!(
26107 got, want,
26108 "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
26109 ),
26110 }
26111 }
26112 }
26113
26114 #[test]
26115 fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
26116 // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
26117 // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
26118 // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
26119 // :max-failures`, `:rate-limit` rate) that discriminate the
26120 // "per-axis phase fires" arm of the compound gate, plus one
26121 // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
26122 // ZERO }`) that pins the phase-boundary ordering — the per-axis
26123 // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
26124 // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
26125 // diagnostic wins over the window-below-timeout diagnostic. Peer
26126 // of the sibling
26127 // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
26128 // + `_on_pairwise_orderings` pins on the compound cross-axis
26129 // fold, extended here onto the outer compound entry gate that
26130 // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
26131 // clean-pass surfaces) lives in the sibling
26132 // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
26133 // pin; splitting keeps each pin's body under
26134 // `clippy::too_many_lines`.
26135 let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
26136 (
26137 "per-axis: timeout zero",
26138 MeshPolicy {
26139 timeout: Some(Duration::ZERO),
26140 ..Default::default()
26141 },
26142 Some(AplicacaoError::PolicyTimeoutZero),
26143 ),
26144 (
26145 "per-axis: retries zero",
26146 MeshPolicy {
26147 retries: Some(0),
26148 ..Default::default()
26149 },
26150 Some(AplicacaoError::PolicyRetriesZero),
26151 ),
26152 (
26153 "per-axis: breaker max-failures zero",
26154 MeshPolicy {
26155 circuit_breaker: Some(CircuitBreaker {
26156 max_failures: 0,
26157 window: Duration::from_secs(60),
26158 }),
26159 ..Default::default()
26160 },
26161 Some(AplicacaoError::PolicyBreakerZeroFailures),
26162 ),
26163 (
26164 "per-axis: rate-limit rate zero",
26165 MeshPolicy {
26166 rate_limit: Some(RateLimit {
26167 rate: 0,
26168 window: Duration::from_secs(1),
26169 }),
26170 ..Default::default()
26171 },
26172 Some(AplicacaoError::PolicyRateLimitZero),
26173 ),
26174 (
26175 "per-axis before cross-axis: zero-window wins over window-below-timeout",
26176 MeshPolicy {
26177 timeout: Some(Duration::from_secs(30)),
26178 circuit_breaker: Some(CircuitBreaker {
26179 max_failures: 5,
26180 window: Duration::ZERO,
26181 }),
26182 ..Default::default()
26183 },
26184 Some(AplicacaoError::PolicyBreakerZeroWindow),
26185 ),
26186 ];
26187 assert_validate_matches_gate(cases);
26188 }
26189
26190 #[test]
26191 fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
26192 // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
26193 // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
26194 // arm that discriminates the "cross-axis phase fires" arm of
26195 // the compound gate (window-below-timeout — sibling per-arm
26196 // coverage lives in the two
26197 // `first_cross_axis_violation_matches_gate_on_*` pins above),
26198 // plus the two clean-pass shapes (empty policy — every axis
26199 // absent — and fully-coherent — every axis inside the coherence
26200 // surface) that pin the compound gate's `Ok(())` arm. Half-A
26201 // (per-axis + phase-boundary surfaces) lives in the sibling
26202 // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
26203 // pin; splitting keeps each pin's body under
26204 // `clippy::too_many_lines`.
26205 let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
26206 (
26207 "cross-axis: window-below-timeout",
26208 MeshPolicy {
26209 timeout: Some(Duration::from_secs(30)),
26210 circuit_breaker: Some(CircuitBreaker {
26211 max_failures: 5,
26212 window: Duration::from_secs(10),
26213 }),
26214 ..Default::default()
26215 },
26216 Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
26217 window: Duration::from_secs(10),
26218 timeout: Duration::from_secs(30),
26219 }),
26220 ),
26221 ("clean pass: empty policy", MeshPolicy::default(), None),
26222 (
26223 "clean pass: every axis coherent",
26224 MeshPolicy {
26225 timeout: Some(Duration::from_secs(30)),
26226 retries: Some(3),
26227 circuit_breaker: Some(CircuitBreaker {
26228 max_failures: 5,
26229 window: Duration::from_secs(60),
26230 }),
26231 mtls_required: Some(true),
26232 rate_limit: Some(RateLimit {
26233 rate: 100,
26234 window: Duration::from_secs(1),
26235 }),
26236 },
26237 None,
26238 ),
26239 ];
26240 assert_validate_matches_gate(cases);
26241 }
26242
26243 #[test]
26244 fn empty_politicas_validates() {
26245 // Omitting every policy axis is fine — defaults express "no
26246 // policy on this axis", not "policy = 0". The fixture's typical
26247 // values continue to validate; this test pins that
26248 // MeshPolicy::default() is a clean pass through validate().
26249 let mut s = three_member_spec();
26250 s.politicas = MeshPolicy::default();
26251 s.validate().unwrap();
26252 }
26253
26254 #[test]
26255 fn typical_politicas_validates_with_every_axis_set() {
26256 // The full §III.1 example block (timeout + retries + breaker +
26257 // mtls + rate-limit) — every axis nonzero — must remain a
26258 // clean pass.
26259 let mut s = three_member_spec();
26260 s.politicas = MeshPolicy {
26261 timeout: Some(Duration::from_secs(30)),
26262 retries: Some(3),
26263 circuit_breaker: Some(CircuitBreaker {
26264 max_failures: 5,
26265 window: Duration::from_secs(60),
26266 }),
26267 mtls_required: Some(true),
26268 rate_limit: Some(RateLimit {
26269 rate: 100,
26270 window: Duration::from_secs(1),
26271 }),
26272 };
26273 s.validate().unwrap();
26274 }
26275
26276 #[test]
26277 fn rejects_empty_cluster_name() {
26278 let mut s = three_member_spec();
26279 s.placement.clusters = vec!["rio".into(), String::new()];
26280 assert_eq!(
26281 s.validate().unwrap_err(),
26282 AplicacaoError::PlacementClusterEmpty
26283 );
26284 }
26285
26286 #[test]
26287 fn rejects_duplicate_cluster_names() {
26288 let mut s = three_member_spec();
26289 s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
26290 let err = s.validate().unwrap_err();
26291 assert!(
26292 matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
26293 "got {err:?}"
26294 );
26295 }
26296
26297 #[test]
26298 fn rejects_placement_cluster_with_uppercase() {
26299 // The canonical "I copied the cluster's display name verbatim"
26300 // typo — K8s context names are lowercase per DNS-1123 label
26301 // rule, but org docs often round-trip a TitleCase identifier
26302 // (`Rio`, `Mar-East`) from an ADR. Mirrors the
26303 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
26304 // on the peer name axis.
26305 let mut s = three_member_spec();
26306 s.placement.clusters = vec!["Rio".into(), "mar".into()];
26307 let err = s.validate().unwrap_err();
26308 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
26309 panic!("expected PlacementClusterInvalid, got other variant");
26310 };
26311 assert_eq!(cluster, "Rio");
26312 assert!(
26313 reason.contains("uppercase"),
26314 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
26315 );
26316 assert!(
26317 reason.contains("\"rio\""),
26318 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
26319 );
26320 }
26321
26322 #[test]
26323 fn rejects_placement_cluster_with_underscore() {
26324 // The canonical "I'm thinking of an env var / hostname slug"
26325 // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
26326 // schema. K8s context filtering on `my_cluster` silently misses
26327 // the cluster the author intended; the gate moves it to caixa-
26328 // build time. Same shape as `rejects_membro_caixa_with_underscore`
26329 // (3f9d7a0).
26330 let mut s = three_member_spec();
26331 s.placement.clusters = vec!["my_cluster".into()];
26332 let err = s.validate().unwrap_err();
26333 assert!(
26334 matches!(
26335 err,
26336 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
26337 if cluster == "my_cluster" && reason.contains('_')
26338 ),
26339 "got {err:?}"
26340 );
26341 }
26342
26343 #[test]
26344 fn rejects_placement_cluster_with_dot() {
26345 // A `:placement :clusters` entry is a single DNS-1123 *label*,
26346 // not a subdomain — even though K8s context names sometimes
26347 // carry a dotted form via kubeconfig conventions, the strictest
26348 // floor among the use sites (DNS-1035 cluster.x-k8s.io
26349 // `metadata.name`, Cilium identity label values) wins. The "I
26350 // want to namespace my cluster names with `.`" intent is
26351 // expressed via `-` (`mar-east`).
26352 let mut s = three_member_spec();
26353 s.placement.clusters = vec!["team.rio".into()];
26354 let err = s.validate().unwrap_err();
26355 assert!(
26356 matches!(
26357 err,
26358 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
26359 if cluster == "team.rio" && reason.contains('.')
26360 ),
26361 "got {err:?}"
26362 );
26363 }
26364
26365 #[test]
26366 fn rejects_placement_cluster_with_leading_hyphen() {
26367 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
26368 // with an alphanumeric. The K8s apiserver rejects `-rio`
26369 // outright; the rendered fan-out would emit a `metadata.name:
26370 // "-rio"` that fails admission far from the source caixa.lisp.
26371 let mut s = three_member_spec();
26372 s.placement.clusters = vec!["-rio".into()];
26373 let err = s.validate().unwrap_err();
26374 assert!(
26375 matches!(
26376 err,
26377 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
26378 if cluster == "-rio" && reason.contains("start and end")
26379 ),
26380 "got {err:?}"
26381 );
26382 }
26383
26384 #[test]
26385 fn rejects_placement_cluster_with_trailing_hyphen() {
26386 // The symmetric arm of the boundary rule. Pin separately so
26387 // both ends are covered against a future relaxation that only
26388 // checks one boundary (parallel to
26389 // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
26390 let mut s = three_member_spec();
26391 s.placement.clusters = vec!["rio-".into()];
26392 let err = s.validate().unwrap_err();
26393 assert!(
26394 matches!(
26395 err,
26396 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
26397 if cluster == "rio-"
26398 ),
26399 "got {err:?}"
26400 );
26401 }
26402
26403 #[test]
26404 fn rejects_placement_cluster_with_unicode() {
26405 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
26406 // before it reaches K8s. The byte-by-byte ASCII validity check
26407 // rejects multi-byte UTF-8 sequences by the first byte that
26408 // fails `[a-z0-9-]`.
26409 let mut s = three_member_spec();
26410 s.placement.clusters = vec!["rió".into()];
26411 let err = s.validate().unwrap_err();
26412 assert!(
26413 matches!(
26414 err,
26415 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
26416 if cluster == "rió"
26417 ),
26418 "got {err:?}"
26419 );
26420 }
26421
26422 #[test]
26423 fn rejects_placement_cluster_with_whitespace() {
26424 // Whitespace is the canonical "I pasted from a sketch / doc"
26425 // footgun. The apiserver rejects every cluster `metadata.name`
26426 // value carrying whitespace.
26427 let mut s = three_member_spec();
26428 s.placement.clusters = vec!["rio cluster".into()];
26429 let err = s.validate().unwrap_err();
26430 assert!(
26431 matches!(
26432 err,
26433 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
26434 if cluster == "rio cluster"
26435 ),
26436 "got {err:?}"
26437 );
26438 }
26439
26440 #[test]
26441 fn rejects_placement_cluster_too_long() {
26442 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
26443 // pin. The diagnostic names both the cap (63) and the actual
26444 // length so the author can shorten in one edit. Mirrors
26445 // `rejects_membro_caixa_too_long` (3f9d7a0).
26446 let mut s = three_member_spec();
26447 let too_long = "a".repeat(64);
26448 s.placement.clusters = vec![too_long.clone()];
26449 let err = s.validate().unwrap_err();
26450 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
26451 panic!("expected PlacementClusterInvalid");
26452 };
26453 assert_eq!(cluster, too_long);
26454 assert!(
26455 reason.contains("63") && reason.contains("64"),
26456 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
26457 );
26458 }
26459
26460 #[test]
26461 fn placement_cluster_max_length_validates() {
26462 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
26463 // future tightening (e.g. dropping to 62) surfaces here as a
26464 // regression, mirroring `membro_caixa_max_length_validates`
26465 // (3f9d7a0).
26466 let mut s = three_member_spec();
26467 s.placement.clusters = vec!["a".repeat(63)];
26468 s.validate().unwrap();
26469 }
26470
26471 #[test]
26472 fn accepts_canonical_placement_cluster_forms() {
26473 // The DNS-1123 label shapes a caixa author is realistically
26474 // going to write for cluster names: single-word lowercase
26475 // (`rio`), regional hyphen-joined (`mar-east`), single
26476 // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
26477 // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
26478 // Pin every leg so a future tightening that bans (e.g.) digit-
26479 // start identifiers surfaces here.
26480 for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
26481 let mut s = three_member_spec();
26482 s.placement.clusters = vec![form.into()];
26483 s.validate().unwrap_or_else(|e| {
26484 panic!("canonical cluster form {form:?} must validate, got {e:?}")
26485 });
26486 }
26487 }
26488
26489 #[test]
26490 fn placement_cluster_empty_takes_precedence_over_invalid() {
26491 // Order pin: the existing `PlacementClusterEmpty` diagnostic
26492 // (which doesn't try to parse) fires before the new
26493 // `PlacementClusterInvalid` parse-side diagnostic, so an empty
26494 // `:clusters` entry keeps its narrower error message — the new
26495 // gate would also reject `""`, but the empty-string arm is the
26496 // more self-locating diagnostic. Mirrors the
26497 // `membro_caixa_empty_takes_precedence_over_invalid` pin
26498 // (3f9d7a0).
26499 let mut s = three_member_spec();
26500 s.placement.clusters = vec!["rio".into(), String::new()];
26501 let err = s.validate().unwrap_err();
26502 assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
26503 }
26504
26505 #[test]
26506 fn placement_cluster_invalid_fires_before_duplicate_check() {
26507 // Order pin: a malformed-shape `:clusters` entry surfaces *its
26508 // own* diagnostic, even when a later entry would otherwise
26509 // collapse onto a duplicate name. The per-entry shape gate runs
26510 // inline before the duplicate-key insert, parallel to
26511 // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
26512 let mut s = three_member_spec();
26513 s.placement.clusters = vec!["Rio".into(), "rio".into()];
26514 let err = s.validate().unwrap_err();
26515 assert!(
26516 matches!(
26517 err,
26518 AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
26519 ),
26520 "got {err:?}"
26521 );
26522 }
26523
26524 #[test]
26525 fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
26526 // The diagnostic-shape pin: the error names the offending
26527 // `:clusters` value verbatim so the author can grep their
26528 // caixa.lisp without re-running the build, and carries a
26529 // non-empty `reason` naming the specific violation. Same shape
26530 // every typed-shape gate enshrines
26531 // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
26532 // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
26533 let mut s = three_member_spec();
26534 s.placement.clusters = vec!["BAD_CLUSTER".into()];
26535 let err = s.validate().unwrap_err();
26536 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
26537 panic!("expected PlacementClusterInvalid");
26538 };
26539 assert_eq!(cluster, "BAD_CLUSTER");
26540 assert!(
26541 !reason.is_empty(),
26542 "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
26543 );
26544 }
26545
26546 #[test]
26547 fn rejects_sharded_with_empty_clusters() {
26548 // §III.1: Sharded uses :clusters as the shard pool. An empty
26549 // pool means "shard across no clusters" — meaningless, same as
26550 // Replicated with no hosts.
26551 let mut s = three_member_spec();
26552 s.placement.estrategia = PlacementStrategy::Sharded;
26553 s.placement.shard_key = Some("$tenantId".into());
26554 s.placement.clusters = vec![];
26555 assert!(matches!(
26556 s.validate().unwrap_err(),
26557 AplicacaoError::PlacementWithoutClusters {
26558 estrategia: PlacementStrategy::Sharded
26559 }
26560 ));
26561 }
26562
26563 #[test]
26564 fn rejects_sharded_with_empty_shard_key() {
26565 let mut s = three_member_spec();
26566 s.placement.estrategia = PlacementStrategy::Sharded;
26567 s.placement.shard_key = Some(String::new());
26568 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
26569 }
26570
26571 #[test]
26572 fn rejects_shard_key_under_replicated_strategy() {
26573 // The fail-before-pass-after pin: a `:placement (:estrategia
26574 // Replicated :shard-key "tenantId")` manifest carries the
26575 // hash-keyed-distribution slot on a strategy that never consumes
26576 // it. Before the gate the typed slot's value silently vanished
26577 // at the renderer layer (caixa-mesh emits `placement.shardKey`
26578 // verbatim regardless of strategy; the Akka-style cluster-
26579 // sharding reconciler keys off `estrategia == Sharded` and
26580 // ignores the slot otherwise), with no diagnostic. Lifting the
26581 // rejection to a build-time gate makes the
26582 // `shard_key.is_some() == matches!(estrategia, Sharded)`
26583 // partition a structural property of every validated
26584 // [`Placement`].
26585 let mut s = three_member_spec();
26586 // The fixture already uses Replicated; just add a shard-key.
26587 s.placement.shard_key = Some("$tenantId".into());
26588 let err = s.validate().unwrap_err();
26589 let AplicacaoError::ShardKeyOnNonSharded {
26590 estrategia,
26591 shard_key,
26592 } = err
26593 else {
26594 panic!("expected ShardKeyOnNonSharded, got {err:?}");
26595 };
26596 assert_eq!(estrategia, PlacementStrategy::Replicated);
26597 assert_eq!(shard_key, "$tenantId");
26598 }
26599
26600 #[test]
26601 fn rejects_shard_key_under_singlenode_strategy() {
26602 // Peer of the Replicated case above on the SingleNode arm: OTP
26603 // distributed-app takeover (one cluster runs at a time) has no
26604 // hash-keyed routing axis to consume `:shard-key` either, so
26605 // the rejection fires on both non-Sharded arms uniformly.
26606 let mut s = three_member_spec();
26607 s.placement.estrategia = PlacementStrategy::SingleNode;
26608 s.placement.shard_key = Some("$tenantId".into());
26609 let err = s.validate().unwrap_err();
26610 let AplicacaoError::ShardKeyOnNonSharded {
26611 estrategia,
26612 shard_key,
26613 } = err
26614 else {
26615 panic!("expected ShardKeyOnNonSharded, got {err:?}");
26616 };
26617 assert_eq!(estrategia, PlacementStrategy::SingleNode);
26618 assert_eq!(shard_key, "$tenantId");
26619 }
26620
26621 #[test]
26622 fn rejects_empty_shard_key_under_replicated_strategy() {
26623 // The `Some("")` case under non-Sharded is rejected by
26624 // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
26625 // fires before the empty-value gate), not
26626 // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
26627 // the `Sharded` arm). Pin the partition so a future reorder of
26628 // the validate_placement match arms doesn't silently swap which
26629 // diagnostic the author sees — both are author errors, but
26630 // ShardKeyOnNonSharded names which strategy is the actual fix
26631 // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
26632 // only says "pick a non-empty key".
26633 let mut s = three_member_spec();
26634 s.placement.shard_key = Some(String::new());
26635 let err = s.validate().unwrap_err();
26636 assert!(
26637 matches!(
26638 err,
26639 AplicacaoError::ShardKeyOnNonSharded {
26640 estrategia: PlacementStrategy::Replicated,
26641 ref shard_key,
26642 } if shard_key.is_empty()
26643 ),
26644 "got {err:?}"
26645 );
26646 }
26647
26648 #[test]
26649 fn replicated_without_shard_key_validates() {
26650 // The complement of the rejection: `:placement :estrategia
26651 // Replicated` with `:shard-key None` is the canonical happy
26652 // path on every existing fixture. Pin the no-shard-key case so
26653 // the new gate doesn't accidentally fire on `None`.
26654 let mut s = three_member_spec();
26655 assert!(matches!(
26656 s.placement.estrategia,
26657 PlacementStrategy::Replicated
26658 ));
26659 s.placement.shard_key = None;
26660 s.validate().unwrap();
26661 }
26662
26663 #[test]
26664 fn singlenode_without_shard_key_validates() {
26665 // Peer of the Replicated no-shard-key case on the SingleNode
26666 // arm — both non-Sharded strategies must validate cleanly when
26667 // the slot is omitted.
26668 let mut s = three_member_spec();
26669 s.placement.estrategia = PlacementStrategy::SingleNode;
26670 s.placement.shard_key = None;
26671 s.validate().unwrap();
26672 }
26673
26674 #[test]
26675 fn shard_key_on_non_sharded_ctor_matches_struct_literal_wrap() {
26676 // Fail-before-pass-after pin on
26677 // [`AplicacaoError::shard_key_on_non_sharded`]'s
26678 // substrate-primitive posture: byte-identity + `Display`
26679 // byte-string parity against the open-coded struct-literal
26680 // for every non-`Sharded` [`PlacementStrategy`] arm across a
26681 // representative `:shard-key` value the sole in-crate wire-up
26682 // site (`AplicacaoSpec::validate_placement`'s
26683 // `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
26684 // arm) emits. Any wrapper-side silent normalization, `.into()`
26685 // divergence, or accidental field rebrand on the ctor body
26686 // surfaces at assert time rather than at a downstream consumer
26687 // that reads `err.estrategia` / `err.shard_key` back and gets a
26688 // different value than the one it stored.
26689 for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
26690 let placement = Placement {
26691 estrategia,
26692 clusters: vec!["cluster-a".to_string()],
26693 shard_key: Some("$tenantId".to_string()),
26694 affinity: None,
26695 };
26696 let via_ctor = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
26697 let via_literal = AplicacaoError::ShardKeyOnNonSharded {
26698 estrategia,
26699 shard_key: "$tenantId".to_string(),
26700 };
26701 assert_eq!(
26702 via_ctor, via_literal,
26703 "shard_key_on_non_sharded(&placement, k) must byte-equal the \
26704 open-coded ShardKeyOnNonSharded struct-literal for {estrategia:?}"
26705 );
26706 assert_eq!(
26707 via_ctor.to_string(),
26708 via_literal.to_string(),
26709 "Display byte-string must byte-equal the open-coded struct-literal \
26710 for {estrategia:?}"
26711 );
26712 }
26713 }
26714
26715 #[test]
26716 fn shard_key_on_non_sharded_routes_estrategia_through_placement_accessor() {
26717 // Boundary-sweep pin on the ctor's substrate-primitive
26718 // projection: the `estrategia` slot is stored verbatim from
26719 // [`Placement::estrategia`] on every arm the accessor can
26720 // return, and the `shard_key` slot preserves the caller-side
26721 // `&str` byte-for-byte. Sweeping every arm of
26722 // [`PlacementStrategy::ALL`] (including the `Sharded` arm the
26723 // current caller never reaches, since the ctor is a substrate
26724 // primitive independent of any single caller's dispatch gate)
26725 // catches a future silent field-rebrand or per-arm ctor
26726 // divergence at caixa-core build time rather than at a
26727 // downstream consumer far from the wire-up commit.
26728 for &estrategia in PlacementStrategy::ALL {
26729 let placement = Placement {
26730 estrategia,
26731 clusters: vec!["cluster-a".to_string()],
26732 shard_key: Some("$tenantId".to_string()),
26733 affinity: None,
26734 };
26735 let err = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
26736 let AplicacaoError::ShardKeyOnNonSharded {
26737 estrategia: stored_estrategia,
26738 shard_key: stored_shard_key,
26739 } = err
26740 else {
26741 panic!(
26742 "shard_key_on_non_sharded must construct ShardKeyOnNonSharded for {estrategia:?}"
26743 );
26744 };
26745 assert_eq!(
26746 stored_estrategia, estrategia,
26747 "estrategia slot must round-trip verbatim through Placement::estrategia \
26748 for {estrategia:?}"
26749 );
26750 assert_eq!(
26751 stored_shard_key, "$tenantId",
26752 "shard_key slot must preserve the caller-side &str byte-for-byte \
26753 for {estrategia:?}"
26754 );
26755 }
26756 }
26757
26758 #[test]
26759 fn validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor() {
26760 // End-to-end pin: the sole in-crate wire-up site
26761 // (`AplicacaoSpec::validate_placement`'s non-`Sharded`-arm
26762 // refusal) routes through
26763 // [`AplicacaoError::shard_key_on_non_sharded`] and the observed
26764 // `Err` byte-equals the ctor's output on the same non-`Sharded`
26765 // fixture. A future silent de-lift of the wire-up back to the
26766 // open-coded struct-literal trips this test at caixa-core build
26767 // time rather than at a downstream diagnostic consumer far from
26768 // the wire-up commit.
26769 for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
26770 let mut s = three_member_spec();
26771 s.placement.estrategia = estrategia;
26772 s.placement.shard_key = Some("$tenantId".to_string());
26773 let observed = s.validate().unwrap_err();
26774 let expected = AplicacaoError::shard_key_on_non_sharded(&s.placement, "$tenantId");
26775 assert_eq!(
26776 observed, expected,
26777 "validate_placement's non-Sharded-arm Err must byte-equal \
26778 shard_key_on_non_sharded(&placement, k) for {estrategia:?}"
26779 );
26780 assert_eq!(
26781 observed.to_string(),
26782 expected.to_string(),
26783 "Display byte-string parity for {estrategia:?}"
26784 );
26785 }
26786 }
26787
26788 fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
26789 // Fixture builder for the `:placement :shard-key` shape gate
26790 // tests: a three-member Aplicacao on the `Sharded` strategy
26791 // with the supplied `:shard-key` slot. Co-locates the
26792 // arm-construction so every test below carries one line of
26793 // setup (the offending `:shard-key` value) and the assertion.
26794 let mut s = three_member_spec();
26795 s.placement.estrategia = PlacementStrategy::Sharded;
26796 s.placement.shard_key = Some(key.into());
26797 s
26798 }
26799
26800 #[test]
26801 fn rejects_shard_key_with_embedded_space() {
26802 // The canonical paste-from-aligned-doc footgun:
26803 // `:shard-key "$tenant Id"` — the Akka-style entity-id
26804 // extractor reads the slot as a single-token reference, and an
26805 // embedded space breaks the token boundary at the runtime
26806 // hash-extractor pass with no diagnostic naming the offending
26807 // entry.
26808 let s = sharded_spec_with_key("$tenant Id");
26809 let err = s.validate().unwrap_err();
26810 assert!(
26811 matches!(
26812 err,
26813 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
26814 if shard_key == "$tenant Id" && reason.contains("space")
26815 ),
26816 "got {err:?}"
26817 );
26818 }
26819
26820 #[test]
26821 fn rejects_shard_key_with_leading_space() {
26822 // Leading-space arm of the embedded-whitespace footgun — the
26823 // paste-from-aligned-doc / paste-from-CSV-cell variant where
26824 // the leading column-padding leaked into the slot.
26825 let s = sharded_spec_with_key(" $tenantId");
26826 let err = s.validate().unwrap_err();
26827 assert!(
26828 matches!(
26829 err,
26830 AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
26831 if shard_key == " $tenantId"
26832 ),
26833 "got {err:?}"
26834 );
26835 }
26836
26837 #[test]
26838 fn rejects_shard_key_with_trailing_newline() {
26839 // The canonical paste-from-shell-heredoc footgun — every
26840 // `<<EOF` heredoc terminator paste leaves a trailing newline
26841 // the YAML emitter then folds away inconsistently across
26842 // emitter implementations.
26843 let s = sharded_spec_with_key("$tenantId\n");
26844 let err = s.validate().unwrap_err();
26845 assert!(
26846 matches!(
26847 err,
26848 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
26849 if shard_key == "$tenantId\n" && reason.contains("0x0a")
26850 ),
26851 "got {err:?}"
26852 );
26853 }
26854
26855 #[test]
26856 fn rejects_shard_key_with_embedded_tab() {
26857 // The paste-from-aligned-doc tab-stop variant — tabs land
26858 // alongside spaces in copy-paste from formatted columns.
26859 let s = sharded_spec_with_key("$tenant\tId");
26860 let err = s.validate().unwrap_err();
26861 assert!(
26862 matches!(
26863 err,
26864 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
26865 if shard_key == "$tenant\tId" && reason.contains("tab")
26866 ),
26867 "got {err:?}"
26868 );
26869 }
26870
26871 #[test]
26872 fn rejects_shard_key_with_control_character() {
26873 // The paste-from-binary / paste-from-screen-cleared-terminal
26874 // footgun — an embedded `\x01` (SOH) byte that some YAML
26875 // emitters silently strip and others escape as ``,
26876 // breaking round-trip across emitter implementations.
26877 let s = sharded_spec_with_key("$tenant\u{0001}Id");
26878 let err = s.validate().unwrap_err();
26879 assert!(
26880 matches!(
26881 err,
26882 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
26883 if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
26884 ),
26885 "got {err:?}"
26886 );
26887 }
26888
26889 #[test]
26890 fn rejects_shard_key_with_non_ascii() {
26891 // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
26892 // footgun — non-ASCII bytes normalize differently between the
26893 // caixa-mesh-side YAML emitter and the in-cluster reconciler's
26894 // YAML parser, the same entity ID can silently map to two
26895 // distinct shards on a re-render.
26896 let s = sharded_spec_with_key("$tenàntId");
26897 let err = s.validate().unwrap_err();
26898 assert!(
26899 matches!(
26900 err,
26901 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
26902 if shard_key == "$tenàntId" && reason.contains("non-ASCII")
26903 ),
26904 "got {err:?}"
26905 );
26906 }
26907
26908 #[test]
26909 fn rejects_shard_key_too_long() {
26910 // Length cap pin: 64 bytes — one byte over the
26911 // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
26912 // here is a paste-from-doc multi-line blob landing in
26913 // `:shard-key` instead of a single-token extractor expression.
26914 let too_long = "a".repeat(64);
26915 let s = sharded_spec_with_key(&too_long);
26916 let err = s.validate().unwrap_err();
26917 let AplicacaoError::ShardKeyInvalid {
26918 ref shard_key,
26919 ref reason,
26920 } = err
26921 else {
26922 panic!("expected ShardKeyInvalid, got {err:?}");
26923 };
26924 assert_eq!(shard_key, &too_long);
26925 assert!(
26926 reason.contains("63") && reason.contains("64"),
26927 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
26928 );
26929 }
26930
26931 #[test]
26932 fn shard_key_max_length_validates() {
26933 // Boundary pin: 63 bytes exactly — the
26934 // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
26935 // dropping to 62) surfaces here as a regression, mirroring
26936 // `placement_cluster_max_length_validates` /
26937 // `placement_affinity_max_length_validates` on the peer
26938 // identifier-shaped slots.
26939 let s = sharded_spec_with_key(&"a".repeat(63));
26940 s.validate().unwrap();
26941 }
26942
26943 #[test]
26944 fn accepts_canonical_shard_key_forms() {
26945 // The Akka-style entity-id extractor shapes a caixa author is
26946 // realistically going to write — pin every leg so a future
26947 // tightening that bans (e.g.) the `${...}` interpolation
26948 // variant or the `metadata.<field>` JSONPath form surfaces
26949 // here as a regression. The canonical forms span:
26950 //
26951 // - bare property name (`tenantId`, `customerId`)
26952 // - Akka `ExtractEntityId` placeholder (`$tenantId`)
26953 // - JSONPath-style nested reference (`metadata.tenantId`,
26954 // `$.user.id`)
26955 // - interpolation-style template (`${tenant}`)
26956 // - snake_case property name (`customer_id`)
26957 // - kebab-case property name (`customer-id` — accepted
26958 // because the slot is a printable-ASCII single-token
26959 // reference, not a DNS-1123 label like
26960 // `:placement :affinity` / `:clusters`)
26961 // - single character (`a`, `$` — boundary)
26962 for form in [
26963 "tenantId",
26964 "customerId",
26965 "$tenantId",
26966 "metadata.tenantId",
26967 "$.user.id",
26968 "${tenant}",
26969 "customer_id",
26970 "customer-id",
26971 "a",
26972 "$",
26973 ] {
26974 let s = sharded_spec_with_key(form);
26975 s.validate().unwrap_or_else(|e| {
26976 panic!("canonical shard-key form {form:?} must validate, got {e:?}")
26977 });
26978 }
26979 }
26980
26981 #[test]
26982 fn shard_key_empty_takes_precedence_over_invalid() {
26983 // Order pin: the existing `ShardedKeyEmpty` diagnostic
26984 // (reserved for the `Sharded` `Some("")` arm) fires before the
26985 // new `ShardKeyInvalid` parse-side diagnostic, so an empty
26986 // `:shard-key` keeps its narrower error message — the new gate
26987 // would also reject `""` defensively, but the empty-string arm
26988 // is the more self-locating diagnostic. Mirrors the
26989 // `placement_cluster_empty_takes_precedence_over_invalid` pin
26990 // on the peer identifier-shaped slot.
26991 let s = sharded_spec_with_key("");
26992 let err = s.validate().unwrap_err();
26993 assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
26994 }
26995
26996 #[test]
26997 fn shard_key_invalid_diagnostic_carries_offending_value() {
26998 // The diagnostic-shape pin: the error names the offending
26999 // `:shard-key` value verbatim so the author can grep their
27000 // caixa.lisp without re-running the build, and carries a
27001 // parser-shaped `reason:` naming the specific violation —
27002 // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
27003 // on the peer identifier-shaped slot.
27004 let s = sharded_spec_with_key("$tenant Id");
27005 let err = s.validate().unwrap_err();
27006 let AplicacaoError::ShardKeyInvalid {
27007 ref shard_key,
27008 ref reason,
27009 } = err
27010 else {
27011 panic!("expected ShardKeyInvalid, got {err:?}");
27012 };
27013 assert_eq!(shard_key, "$tenant Id");
27014 assert!(
27015 !reason.is_empty(),
27016 "reason must name the specific violation, got empty string"
27017 );
27018 }
27019
27020 #[test]
27021 fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
27022 // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
27023 // `:shard-key` carried on non-Sharded strategies) fires before
27024 // the shape gate, so a malformed `:shard-key` carried on (e.g.)
27025 // a `Replicated` strategy surfaces the more self-locating
27026 // strategy-mismatch diagnostic (naming the actual fix — drop
27027 // the slot, or switch to Sharded) rather than the shape
27028 // diagnostic. The strategy-mismatch arm is the more actionable
27029 // diagnostic: a malformed shard-key on Replicated is "you
27030 // shouldn't have a :shard-key here at all", not "your
27031 // :shard-key value is malformed".
27032 let mut s = three_member_spec();
27033 // Replicated is the default fixture strategy.
27034 s.placement.shard_key = Some("$tenant Id".into());
27035 let err = s.validate().unwrap_err();
27036 assert!(
27037 matches!(
27038 err,
27039 AplicacaoError::ShardKeyOnNonSharded {
27040 estrategia: PlacementStrategy::Replicated,
27041 ..
27042 }
27043 ),
27044 "got {err:?}"
27045 );
27046 }
27047
27048 #[test]
27049 fn rejects_empty_affinity_hint() {
27050 let mut s = three_member_spec();
27051 s.placement.affinity = Some(String::new());
27052 assert_eq!(
27053 s.validate().unwrap_err(),
27054 AplicacaoError::PlacementAffinityEmpty
27055 );
27056 }
27057
27058 #[test]
27059 fn placement_without_affinity_validates() {
27060 // Omitting :affinity is fine — the placement engine falls back
27061 // to the default heuristic. Pin the no-hint case so the
27062 // affinity-empty rejection doesn't accidentally fire on `None`.
27063 let mut s = three_member_spec();
27064 s.placement.affinity = None;
27065 s.validate().unwrap();
27066 }
27067
27068 #[test]
27069 fn rejects_placement_affinity_with_uppercase() {
27070 // The canonical "I copied the ADR's display name verbatim" typo
27071 // — placement hints land verbatim in K8s label-selector
27072 // territory, where the apiserver enforces the DNS-1123 label
27073 // rule (lowercase-only) on every identity-keyed admission axis.
27074 // Mirrors `rejects_placement_cluster_with_uppercase` on the
27075 // sibling slot.
27076 let mut s = three_member_spec();
27077 s.placement.affinity = Some("DataLocality".into());
27078 let err = s.validate().unwrap_err();
27079 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
27080 panic!("expected PlacementAffinityInvalid, got other variant");
27081 };
27082 assert_eq!(affinity, "DataLocality");
27083 assert!(
27084 reason.contains("uppercase"),
27085 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
27086 );
27087 assert!(
27088 reason.contains("\"datalocality\""),
27089 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
27090 );
27091 }
27092
27093 #[test]
27094 fn rejects_placement_affinity_with_underscore() {
27095 // The canonical "I'm thinking of an env var / Python identifier"
27096 // leak — `_` is forbidden by every DNS-1123 label schema. Same
27097 // shape as `rejects_placement_cluster_with_underscore` on the
27098 // sibling slot.
27099 let mut s = three_member_spec();
27100 s.placement.affinity = Some("data_locality".into());
27101 let err = s.validate().unwrap_err();
27102 assert!(
27103 matches!(
27104 err,
27105 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
27106 if affinity == "data_locality" && reason.contains('_')
27107 ),
27108 "got {err:?}"
27109 );
27110 }
27111
27112 #[test]
27113 fn rejects_placement_affinity_with_dot() {
27114 // A `:placement :affinity` value is a single DNS-1123 *label*
27115 // (it lands as a K8s label value selector key), not a subdomain.
27116 // The "I want to namespace my hint with `.`" intent is expressed
27117 // via `-` (`data-locality-east`).
27118 let mut s = three_member_spec();
27119 s.placement.affinity = Some("data.locality".into());
27120 let err = s.validate().unwrap_err();
27121 assert!(
27122 matches!(
27123 err,
27124 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
27125 if affinity == "data.locality" && reason.contains('.')
27126 ),
27127 "got {err:?}"
27128 );
27129 }
27130
27131 #[test]
27132 fn rejects_placement_affinity_with_unicode() {
27133 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
27134 // before it reaches K8s. The byte-by-byte ASCII validity check
27135 // rejects multi-byte UTF-8 sequences by the first byte that
27136 // fails `[a-z0-9-]`.
27137 let mut s = three_member_spec();
27138 s.placement.affinity = Some("data-localité".into());
27139 let err = s.validate().unwrap_err();
27140 assert!(
27141 matches!(
27142 err,
27143 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
27144 if affinity == "data-localité"
27145 ),
27146 "got {err:?}"
27147 );
27148 }
27149
27150 #[test]
27151 fn rejects_placement_affinity_with_leading_hyphen() {
27152 // DNS-1123 boundary rule: labels must start with an
27153 // alphanumeric. Pin separately from the trailing-hyphen arm so
27154 // a future relaxation that only checks one boundary surfaces
27155 // here as a regression (parallel to
27156 // `rejects_placement_cluster_with_leading_hyphen`).
27157 let mut s = three_member_spec();
27158 s.placement.affinity = Some("-data-locality".into());
27159 let err = s.validate().unwrap_err();
27160 assert!(
27161 matches!(
27162 err,
27163 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
27164 if affinity == "-data-locality" && reason.contains("start and end")
27165 ),
27166 "got {err:?}"
27167 );
27168 }
27169
27170 #[test]
27171 fn rejects_placement_affinity_with_trailing_hyphen() {
27172 // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
27173 // ends are covered against a future relaxation.
27174 let mut s = three_member_spec();
27175 s.placement.affinity = Some("data-locality-".into());
27176 let err = s.validate().unwrap_err();
27177 assert!(
27178 matches!(
27179 err,
27180 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
27181 if affinity == "data-locality-"
27182 ),
27183 "got {err:?}"
27184 );
27185 }
27186
27187 #[test]
27188 fn rejects_placement_affinity_with_whitespace() {
27189 // Whitespace is the canonical "I pasted from a sketch / doc"
27190 // footgun. The apiserver rejects every label-selector value
27191 // carrying whitespace.
27192 let mut s = three_member_spec();
27193 s.placement.affinity = Some("data locality".into());
27194 let err = s.validate().unwrap_err();
27195 assert!(
27196 matches!(
27197 err,
27198 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
27199 if affinity == "data locality"
27200 ),
27201 "got {err:?}"
27202 );
27203 }
27204
27205 #[test]
27206 fn rejects_placement_affinity_too_long() {
27207 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
27208 // pin. The diagnostic names both the cap (63) and the actual
27209 // length so the author can shorten in one edit. Mirrors
27210 // `rejects_placement_cluster_too_long`.
27211 let mut s = three_member_spec();
27212 let too_long = "a".repeat(64);
27213 s.placement.affinity = Some(too_long.clone());
27214 let err = s.validate().unwrap_err();
27215 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
27216 panic!("expected PlacementAffinityInvalid");
27217 };
27218 assert_eq!(affinity, too_long);
27219 assert!(
27220 reason.contains("63") && reason.contains("64"),
27221 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
27222 );
27223 }
27224
27225 #[test]
27226 fn placement_affinity_max_length_validates() {
27227 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
27228 // future tightening (e.g. dropping to 62) surfaces here as a
27229 // regression, mirroring `placement_cluster_max_length_validates`.
27230 let mut s = three_member_spec();
27231 s.placement.affinity = Some("a".repeat(63));
27232 s.validate().unwrap();
27233 }
27234
27235 #[test]
27236 fn accepts_canonical_placement_affinity_forms() {
27237 // The DNS-1123 label shapes a caixa author is realistically
27238 // going to write for placement hints: the M3 canonical examples
27239 // (`data-locality`, `low-latency`, `anti-affinity`), the
27240 // single-token form (`affinity`), the single-character boundary
27241 // (`a`), the digit-start (DNS-1123 allows this, unlike
27242 // DNS-1035), and a regional-suffixed form. Pin every leg so a
27243 // future tightening that bans (e.g.) digit-start identifiers
27244 // surfaces here.
27245 for form in [
27246 "data-locality",
27247 "low-latency",
27248 "anti-affinity",
27249 "affinity",
27250 "a",
27251 "3-tier",
27252 "locality-east",
27253 ] {
27254 let mut s = three_member_spec();
27255 s.placement.affinity = Some(form.into());
27256 s.validate().unwrap_or_else(|e| {
27257 panic!("canonical affinity form {form:?} must validate, got {e:?}")
27258 });
27259 }
27260 }
27261
27262 #[test]
27263 fn placement_affinity_empty_takes_precedence_over_invalid() {
27264 // Order pin: the existing `PlacementAffinityEmpty` diagnostic
27265 // (which doesn't try to parse) fires before the new
27266 // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
27267 // `:affinity` keeps its narrower error message — the new gate
27268 // would also reject `""`, but the empty-string arm is the more
27269 // self-locating diagnostic. Mirrors the
27270 // `placement_cluster_empty_takes_precedence_over_invalid` pin.
27271 let mut s = three_member_spec();
27272 s.placement.affinity = Some(String::new());
27273 let err = s.validate().unwrap_err();
27274 assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
27275 }
27276
27277 #[test]
27278 fn placement_affinity_invalid_diagnostic_carries_offending_value() {
27279 // The diagnostic shape pin: every rejection carries the offending
27280 // `affinity:` verbatim plus a parser-shaped `reason:` so the
27281 // author can grep their caixa.lisp for `:affinity "<hint>"` and
27282 // fix it in one edit. Mirrors the
27283 // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
27284 // pin on the sibling slot.
27285 let mut s = three_member_spec();
27286 s.placement.affinity = Some("Data_Locality".into());
27287 let err = s.validate().unwrap_err();
27288 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
27289 panic!("expected PlacementAffinityInvalid");
27290 };
27291 assert_eq!(affinity, "Data_Locality");
27292 assert!(
27293 !reason.is_empty(),
27294 "diagnostic reason must not be empty (got: {reason:?})"
27295 );
27296 }
27297
27298 #[test]
27299 fn singlenode_with_takeover_candidates_validates() {
27300 // OTP distributed-application convention (MESH-COMPOSITION
27301 // §II.1): SingleNode runs on one cluster at a time but the
27302 // :clusters list enumerates the takeover candidates. Multiple
27303 // entries are not a contradiction — they are the failover pool.
27304 let mut s = three_member_spec();
27305 s.placement.estrategia = PlacementStrategy::SingleNode;
27306 s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
27307 s.validate().unwrap();
27308 }
27309
27310 // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
27311
27312 #[test]
27313 fn mesh_policy_default_is_empty() {
27314 // The Default impl carries None on every axis — the typed
27315 // analog of an unset `:politicas (())` slot. Renderers that
27316 // overlay the policy onto a cluster artifact key off this
27317 // predicate to skip the slot entirely; pinning so a future
27318 // axis added to MeshPolicy can't silently break the contract
27319 // (a new field whose Default is non-None would flip is_empty
27320 // to false on every existing caixa, surfacing here).
27321 assert!(MeshPolicy::default().is_empty());
27322 }
27323
27324 #[test]
27325 fn mesh_policy_with_only_timeout_is_not_empty() {
27326 let p = MeshPolicy {
27327 timeout: Some(Duration::from_secs(30)),
27328 ..Default::default()
27329 };
27330 assert!(!p.is_empty());
27331 }
27332
27333 #[test]
27334 fn mesh_policy_with_only_retries_is_not_empty() {
27335 let p = MeshPolicy {
27336 retries: Some(3),
27337 ..Default::default()
27338 };
27339 assert!(!p.is_empty());
27340 }
27341
27342 #[test]
27343 fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
27344 let p = MeshPolicy {
27345 circuit_breaker: Some(CircuitBreaker {
27346 max_failures: 5,
27347 window: Duration::from_secs(60),
27348 }),
27349 ..Default::default()
27350 };
27351 assert!(!p.is_empty());
27352 }
27353
27354 #[test]
27355 fn mesh_policy_with_only_mtls_required_is_not_empty() {
27356 // Even `mtls_required: Some(false)` (an explicit opt-out) is
27357 // not empty — the author *named* the axis, the renderer needs
27358 // to honor that vs. fall back to the cluster default.
27359 let p = MeshPolicy {
27360 mtls_required: Some(false),
27361 ..Default::default()
27362 };
27363 assert!(!p.is_empty());
27364 }
27365
27366 #[test]
27367 fn mesh_policy_with_only_rate_limit_is_not_empty() {
27368 let p = MeshPolicy {
27369 rate_limit: Some(RateLimit {
27370 rate: 100,
27371 window: Duration::from_secs(1),
27372 }),
27373 ..Default::default()
27374 };
27375 assert!(!p.is_empty());
27376 }
27377
27378 #[test]
27379 fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
27380 // The three-member happy-path fixture sets timeout + retries +
27381 // mtls_required — every populated axis must read non-empty.
27382 // Pin the round-trip so the M3.x per-:politicas emitter (the
27383 // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
27384 // on is_empty() to decide whether to emit at all without
27385 // re-deriving the contract from inline field probes.
27386 assert!(!three_member_spec().politicas.is_empty());
27387 }
27388
27389 #[test]
27390 fn mesh_policy_empty_is_the_all_none_arm_and_is_empty() {
27391 // Fail-before-pass-after round-trip pin on the paired
27392 // ([`MeshPolicy::empty`], [`MeshPolicy::is_empty`]) constructor /
27393 // predicate on the [`MeshPolicy`] typed slot: the lifted
27394 // constructor must materialize a value whose every one of the
27395 // five `Option<_>`-carrying per-axis fields is `None`, so the
27396 // paired [`MeshPolicy::is_empty`] predicate returns `true` on
27397 // the constructor's output by construction. A future silent
27398 // regression that omits a `None` arm from the constructor's
27399 // struct-literal (a sixth axis added to the type whose
27400 // constructor arm is forgotten, an accidental `Some(0)` on the
27401 // `retries` arm that would silently violate the
27402 // [`AplicacaoError::PolicyRetriesZero`] admission floor) trips
27403 // here at caixa-core test time rather than surfacing as a
27404 // downstream consumer's per-`:politicas` overlay-emit path
27405 // reading a `MeshPolicy::empty()` output that fails the
27406 // emptiness predicate and lands an unexpected `spec.policies.
27407 // <axis>` field in the emitted Cilium/Envoy overlay. Peer of
27408 // the sibling
27409 // [`crate::limits::tests::limits_spec_empty_is_the_all_none_arm_and_is_empty`]
27410 // pin on the M2 `:limits` typed slot — extends the same
27411 // "the canonical unset baseline satisfies the paired
27412 // emptiness predicate" round-trip discipline onto the M3
27413 // `:politicas` slot.
27414 let empty = MeshPolicy::empty();
27415 assert!(
27416 empty.is_empty(),
27417 "MeshPolicy::empty() must return a value whose is_empty() \
27418 predicate is true — got {empty:?}",
27419 );
27420 assert_eq!(empty.timeout(), None);
27421 assert_eq!(empty.retries(), None);
27422 assert_eq!(empty.circuit_breaker(), None);
27423 assert_eq!(empty.mtls_required(), None);
27424 assert_eq!(empty.rate_limit(), None);
27425 }
27426
27427 #[test]
27428 fn mesh_policy_empty_byte_equals_default() {
27429 // Fail-before-pass-after byte-parity pin on the two-path
27430 // convergence: the lifted `pub const fn` [`MeshPolicy::empty`]
27431 // constructor must byte-equal the derived (non-`const`)
27432 // [`Default::default`] on every one of the five
27433 // `Option<_>`-carrying per-axis fields under `PartialEq`. The
27434 // two paths are semantically identical (both name the
27435 // "canonical unset [`MeshPolicy`]" shape) but structurally
27436 // distinct (the derived [`Default::default`] threads through
27437 // the derive-generated per-field `<Option<_> as Default>::default`
27438 // cascade, resolving to `None` on each; the lifted
27439 // constructor's struct-literal names each `None` arm
27440 // verbatim). A future regression on either path — an
27441 // accidental `Some(0)` on the constructor's `retries` arm
27442 // that would silently drift the constructor's output from the
27443 // derived default (surfacing here as the pin's first-arm
27444 // inequality), a future substrate-wide field-default rebrand
27445 // that lands on the derived path's per-field
27446 // `<Option<_> as Default>::default` but forgets to extend the
27447 // constructor's struct-literal (surfacing here as the pin's
27448 // per-arm inequality on the newly rebranded axis) — trips
27449 // here at caixa-core test time. The `const` binding on the
27450 // LHS forces the lifted constructor through the `const`-eval
27451 // surface at compile time, so any future accidental downgrade
27452 // to `pub fn` fires E0015 at the binding rather than at a
27453 // downstream `const`-context consumer's dispatch site. Peer
27454 // of the sibling
27455 // [`crate::limits::tests::limits_spec_empty_byte_equals_default`]
27456 // pin on the M2 `:limits` typed slot.
27457 const EMPTY: MeshPolicy = MeshPolicy::empty();
27458 assert_eq!(
27459 EMPTY,
27460 MeshPolicy::default(),
27461 "MeshPolicy::empty() must byte-equal MeshPolicy::default() on \
27462 every per-axis field — the two paths name the same canonical \
27463 unset baseline; a mismatch means one path drifted from the \
27464 other on some per-axis default",
27465 );
27466 }
27467
27468 #[test]
27469 fn mesh_policy_empty_ctor_is_const_fn() {
27470 // Const-eval-surface pin on the lifted [`MeshPolicy::empty`]
27471 // constructor: the constructor must remain `pub const fn` so
27472 // downstream consumers can materialize a canonical unset
27473 // baseline in `const` context (a `const EMPTY: MeshPolicy =
27474 // MeshPolicy::empty();` module-scope binding for a
27475 // fixture-builder table, a `const`-context per-arm predicate
27476 // that folds emptiness over the constructor's output at
27477 // compile time, a compile-time lookup table the LSP hover
27478 // renderer materializes per typed-slot fixture). A future
27479 // accidental downgrade to non-`const` (an added runtime
27480 // helper reachable only from a non-`const` context in the
27481 // body, a manual hand-rolled `impl` that shadows this method)
27482 // trips at caixa-core build time — E0015 at the `const EMPTY`
27483 // binding below — rather than surfacing as a downstream
27484 // `const`-context regression far from the constructor's
27485 // declaration. The paired [`Self::is_empty`] predicate call
27486 // inside the `const { assert!(..) }` block enforces both
27487 // halves of the round-trip (constructor is `const`-callable
27488 // AND its output satisfies the paired emptiness predicate at
27489 // `const`-eval time) at caixa-core compile time. Peer of the
27490 // sibling
27491 // [`crate::limits::tests::limits_spec_empty_ctor_is_const_fn`]
27492 // pin on the M2 `:limits` typed slot.
27493 const EMPTY: MeshPolicy = MeshPolicy::empty();
27494 const {
27495 assert!(EMPTY.is_empty());
27496 }
27497 }
27498
27499 #[test]
27500 fn mesh_policy_default_routes_through_empty_ctor() {
27501 // Fail-before-pass-after byte-parity pin on the two-path
27502 // convergence discipline lifted onto the [`Default`] impl:
27503 // pre-fold the derive-generated [`Default::default`] and the
27504 // `pub const fn` [`MeshPolicy::empty`] constructor were
27505 // byte-equal by *coincidence* (each hand-authored or derive-
27506 // authored `None` per axis, pinned load-bearing by the
27507 // pre-existing [`mesh_policy_empty_byte_equals_default`]
27508 // sibling pin), while the folded impl now routes
27509 // [`Default::default`] through the substrate-canonical
27510 // [`Self::empty`] constructor — the two paths are byte-equal
27511 // by *construction*, one delegates to the other. This pin
27512 // sharpens the pre-existing byte-parity invariant into a
27513 // structural-delegation invariant: any future silent regression
27514 // that re-derives [`Default`] on the type (a `#[derive(Default)]`
27515 // re-addition that shadows the manual impl, a swap of the
27516 // manual impl's body onto a divergent struct-literal that
27517 // diverges from [`Self::empty`]'s output on a new field's
27518 // non-`None` canonical baseline) trips here at caixa-core test
27519 // time under `PartialEq` rather than at a downstream consumer
27520 // of the derived-until-now [`Default::default`] surface (the
27521 // five per-axis-only `..Default::default()` fixtures at
27522 // [`mesh_policy_with_only_timeout_is_not_empty`] /
27523 // [`mesh_policy_with_only_retries_is_not_empty`] /
27524 // [`mesh_policy_with_only_circuit_breaker_is_not_empty`] /
27525 // [`mesh_policy_with_only_mtls_required_is_not_empty`] /
27526 // [`mesh_policy_with_only_rate_limit_is_not_empty`], the
27527 // `MeshPolicy::default().is_empty()` round-trip at
27528 // [`mesh_policy_default_is_empty`], every future consumer of
27529 // a hypothetical `..MeshPolicy::default()` overlay-elision
27530 // arm). Peer of the sibling
27531 // [`crate::limits::tests::limits_spec_default_routes_through_empty_ctor`]
27532 // pin on the M2 `:limits` typed slot (abd52c2).
27533 assert_eq!(
27534 MeshPolicy::default(),
27535 MeshPolicy::empty(),
27536 "MeshPolicy::default() must delegate through MeshPolicy::empty() \
27537 on every per-axis field — a mismatch means the manual Default \
27538 impl drifted off the substrate-canonical empty() constructor \
27539 (or the constructor drifted off the impl's expected shape)",
27540 );
27541 }
27542
27543 #[test]
27544 fn mesh_policy_empty_validates_ok() {
27545 // Fail-before-pass-after invariant pin on the empty-baseline
27546 // validate composition: the canonical unset [`MeshPolicy`]
27547 // (every one of the five `Option<_>`-carrying per-axis fields
27548 // set to `None`) must pass every gate on
27549 // [`MeshPolicy::validate`]. The invariant is structurally
27550 // guaranteed today — every per-axis value-shape gate on the
27551 // validate dispatch is `if let Some(_) = self.<axis>()` guarded
27552 // and every cross-axis arm on
27553 // [`MeshPolicy::first_cross_axis_violation`] is a
27554 // `let (Some(_), Some(_))` pattern, so an all-`None` input
27555 // short-circuits every arm before any zero-floor / canonical-
27556 // form / cap / pairwise-ordering check fires. Pinning the
27557 // composition here makes the invariant load-bearing so a
27558 // future extension of the validate surface that adds a
27559 // non-`Option`-guarded gate (a hypothetical cross-slot
27560 // coherence gate a future per-axis / per-slot fold on the M3
27561 // `:politicas` slot establishes on top of the current
27562 // pairwise-cross-axis composition per
27563 // `theory/MESH-COMPOSITION.md` §III.2, a per-arm
27564 // `mtls_required`-defaults-to-`true` admission overlay a
27565 // future admission webhook lands) that fires on the all-`None`
27566 // input trips here at caixa-core test time rather than at a
27567 // downstream consumer that composed [`MeshPolicy::default`]
27568 // (which now routes through [`MeshPolicy::empty`]) with
27569 // [`MeshPolicy::validate`] as its "no-op axis short-circuit"
27570 // and observed a spurious rejection on the canonical unset
27571 // baseline. Peer of the sibling
27572 // [`crate::limits::tests::limits_spec_empty_validates_ok`] pin
27573 // on the M2 `:limits` typed slot (abd52c2) — that one anchors
27574 // the invariant on the folded [`Default`] impl the
27575 // [`crate::LimitsSpec::empty`] constructor now backs; this one
27576 // extends it onto the M3 `:politicas` slot's folded impl.
27577 MeshPolicy::empty().validate().expect(
27578 "MeshPolicy::empty() must satisfy MeshPolicy::validate — \
27579 every per-axis value-shape gate is `if let Some(_)` guarded \
27580 and every cross-axis arm is a `let (Some(_), Some(_))` pattern, \
27581 so an all-`None` input short-circuits every arm; a spurious \
27582 rejection on the canonical unset baseline means a future \
27583 validate-side extension added a non-`Option`-guarded gate that \
27584 fires on empty input",
27585 );
27586 }
27587
27588 // ── shared duration codec: cross-slot integer-magnitude gate ──
27589 //
27590 // The integer-magnitude discipline applied to
27591 // `supervisor::duration_codec::parse` lifts onto every typed slot
27592 // that routes through the shared codec — `MeshPolicy::timeout`
27593 // (`:politicas :timeout`) and `CircuitBreaker::window`
27594 // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
27595 // These cross-slot tests pin that the gate fires at the serde
27596 // layer for both typed slots, not just for the supervisor side.
27597
27598 #[test]
27599 fn policy_timeout_serde_rejects_fractional_seconds() {
27600 // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
27601 // so the shared codec's integer-magnitude gate applies on
27602 // deserialize. `"1.5s"` previously parsed to 1500ms and round-
27603 // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
27604 // deserialize with the canonical-form diagnostic naming the
27605 // offending `"1.5"` and the remediation `"1500ms"`.
27606 let payload = r#"{"timeout":"1.5s"}"#;
27607 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27608 let msg = err.to_string();
27609 assert!(
27610 msg.contains("not a non-negative integer"),
27611 "expected integer-magnitude diagnostic in {msg:?}"
27612 );
27613 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
27614 assert!(
27615 msg.contains("\"1500ms\""),
27616 "missing canonical-form remediation in {msg:?}"
27617 );
27618 }
27619
27620 #[test]
27621 fn policy_timeout_serde_rejects_leading_plus_sign() {
27622 // Pin the leading-`+` arm cross-slot — the prior f64 parser
27623 // accepted `"+30s"` silently and round-tripped to `"30s"`.
27624 let payload = r#"{"timeout":"+30s"}"#;
27625 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27626 let msg = err.to_string();
27627 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
27628 }
27629
27630 #[test]
27631 fn circuit_breaker_window_serde_rejects_fractional_minutes() {
27632 // `CircuitBreaker::window` uses `with =
27633 // "supervisor::duration_codec_required"` (the required-Duration
27634 // variant that delegates to the same shared parser). `"0.5m"`
27635 // parsed to 30s and round-tripped to `"30s"` on next emit —
27636 // DRIFT closed.
27637 let payload = format!(
27638 r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
27639 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27640 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
27641 );
27642 let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
27643 let msg = err.to_string();
27644 assert!(
27645 msg.contains("not a non-negative integer"),
27646 "expected integer-magnitude diagnostic in {msg:?}"
27647 );
27648 assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
27649 assert!(
27650 msg.contains("\"30s\""),
27651 "missing canonical-form remediation in {msg:?}"
27652 );
27653 }
27654
27655 #[test]
27656 fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
27657 // Pin the happy-path on the cross-slot side: every canonical
27658 // author shape `render` ever emits parses cleanly through the
27659 // shared codec on the `CircuitBreaker` slot. The
27660 // codec's accepted set (post-gate) is exactly its emitted set
27661 // for the integer-magnitude class.
27662 for window_lit in ["30s", "500ms", "2m", "1h"] {
27663 let payload = format!(
27664 r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
27665 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27666 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
27667 );
27668 let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
27669 panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
27670 });
27671 assert_eq!(cb.max_failures, 5);
27672 }
27673 }
27674
27675 // ── rate_limit_codec: integer-magnitude gate ──
27676 //
27677 // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
27678 // / 737a676 / d53c922 trajectory landed on every typed-duration /
27679 // typed-byte-size codec in caixa-core lifts onto the fifth typed
27680 // codec — `rate_limit_codec` — through the digit-only magnitude
27681 // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
27682 // These tests pin the gate at the serde layer for `:politicas
27683 // :rate-limit` (the only typed slot the codec backs), and at the
27684 // codec-internal `parse` layer for the canonical positive cases.
27685
27686 #[test]
27687 fn rate_limit_serde_rejects_fractional_rate() {
27688 // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
27689 // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
27690 // wording, which didn't name the canonical-form remediation or
27691 // the round-trip drift the next emit would produce. Now refused
27692 // at deserialize with the canonical-form diagnostic naming the
27693 // offending `"1.5"` magnitude and the round-trip drift wording.
27694 let payload = r#"{"rateLimit":"1.5/s"}"#;
27695 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27696 let msg = err.to_string();
27697 assert!(
27698 msg.contains("not a non-negative integer"),
27699 "expected integer-magnitude diagnostic in {msg:?}"
27700 );
27701 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
27702 assert!(
27703 msg.contains("THEORY.md"),
27704 "missing render-determinism contract citation in {msg:?}"
27705 );
27706 }
27707
27708 #[test]
27709 fn rate_limit_serde_rejects_leading_plus_sign() {
27710 // `u32::from_str("+100")` returns `Ok(100)` (Rust's
27711 // permissive-`+` parse), so `"+100/s"` silently parsed to
27712 // `RateLimit { 100, 1s }` and round-tripped through `render` to
27713 // `"100/s"` — a *different* canonical string on the next emit,
27714 // breaking the THEORY.md Part V render-determinism contract
27715 // exactly the way the peer duration codecs' `"+30s"` case did.
27716 // This is the load-bearing class the digit-only gate closes
27717 // beyond what `u32::from_str`'s strictness covers on its own.
27718 let payload = r#"{"rateLimit":"+100/s"}"#;
27719 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27720 let msg = err.to_string();
27721 assert!(
27722 msg.contains("not a non-negative integer"),
27723 "expected integer-magnitude diagnostic in {msg:?}"
27724 );
27725 assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
27726 }
27727
27728 #[test]
27729 fn rate_limit_serde_rejects_leading_minus_sign() {
27730 // The signed-negative arm: `"-1/s"` lands on the
27731 // non-canonical-but-numeric branch via the `i64` fallback (the
27732 // `f64` parse also succeeds), surfacing the canonical-form
27733 // diagnostic. Replaces the prior value-laundered "not a u32"
27734 // wording with the unified diagnostic across signs.
27735 let payload = r#"{"rateLimit":"-1/s"}"#;
27736 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27737 let msg = err.to_string();
27738 assert!(
27739 msg.contains("not a non-negative integer"),
27740 "expected integer-magnitude diagnostic in {msg:?}"
27741 );
27742 assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
27743 }
27744
27745 #[test]
27746 fn rate_limit_serde_rejects_decimal_shaped_integer() {
27747 // `"100.0/s"` is integer-valued numerically but not in the
27748 // codec's accepted set — `render` emits `"100/s"`, so the
27749 // round-trip would drift. Lifted to the canonical-form
27750 // diagnostic peer with the duration codec's `"1.0s"` case
27751 // (1c55a2a).
27752 let payload = r#"{"rateLimit":"100.0/s"}"#;
27753 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27754 let msg = err.to_string();
27755 assert!(
27756 msg.contains("not a non-negative integer"),
27757 "expected integer-magnitude diagnostic in {msg:?}"
27758 );
27759 assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
27760 }
27761
27762 #[test]
27763 fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
27764 // Non-numeric, non-digit-only input lands on the existing
27765 // narrower `"not a u32"` arm (preserved for diagnostic-shape
27766 // stability on the parser-shape footgun case). Pin this so a
27767 // future relaxation of the numeric-fallback predicate doesn't
27768 // silently collapse garbage onto the canonical-form arm — same
27769 // partition the peer duration codecs draw between
27770 // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
27771 let payload = r#"{"rateLimit":"abc/s"}"#;
27772 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27773 let msg = err.to_string();
27774 assert!(
27775 msg.contains("not a u32"),
27776 "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
27777 );
27778 assert!(
27779 !msg.contains("not a non-negative integer"),
27780 "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
27781 );
27782 }
27783
27784 #[test]
27785 fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
27786 // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
27787 // u32's range. The digit-only gate passes; `u32::from_str`
27788 // fails on overflow. Surface that with the overflow-shaped
27789 // diagnostic naming the offending magnitude verbatim, peer
27790 // with `supervisor::duration_codec`'s overflow arm. Pinning
27791 // the wording so a future refactor doesn't silently collapse
27792 // overflow onto the canonical-form arm.
27793 let payload = r#"{"rateLimit":"4294967296/s"}"#;
27794 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27795 let msg = err.to_string();
27796 assert!(
27797 msg.contains("overflows u32"),
27798 "expected overflow diagnostic in {msg:?}"
27799 );
27800 assert!(
27801 msg.contains("\"4294967296\""),
27802 "missing offending magnitude in {msg:?}"
27803 );
27804 }
27805
27806 #[test]
27807 fn rate_limit_serde_rejects_leading_zero_magnitude() {
27808 // `"0100/s"` is digit-only, so the existing
27809 // non-digit-only / sign / fractional arm doesn't catch it —
27810 // `u32::from_str("0100")` returns `Ok(100)`, so before this
27811 // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
27812 // round-tripped through `render` to `"100/s"` — a *different*
27813 // canonical string on the next emit, breaking the THEORY.md
27814 // Part V render-determinism contract exactly the way the
27815 // peer `"+100/s"` case did before the leading-`+` arm landed.
27816 // This is the load-bearing class the leading-zero gate closes
27817 // beyond what the existing digit-only / sign / fractional
27818 // gates cover, and the peer arm to the leading-`+` test
27819 // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
27820 // canonical-form-drift axis.
27821 let payload = r#"{"rateLimit":"0100/s"}"#;
27822 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27823 let msg = err.to_string();
27824 assert!(
27825 msg.contains("non-canonical leading zero"),
27826 "expected leading-zero diagnostic in {msg:?}"
27827 );
27828 assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
27829 assert!(
27830 msg.contains("THEORY.md"),
27831 "missing render-determinism contract citation in {msg:?}"
27832 );
27833 }
27834
27835 #[test]
27836 fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
27837 // `"00/s"` is the degenerate leading-zero case — every byte
27838 // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
27839 // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
27840 // a *different* canonical string, same render-determinism
27841 // violation. The single-byte `"0/s"` itself is in the
27842 // accepted set (round-trips losslessly through `render`,
27843 // refused downstream by `PolicyRateLimitZero`); the
27844 // multi-byte `"00/s"` is not. Pins the boundary between the
27845 // accepted single-`0` and the rejected leading-zero class.
27846 let payload = r#"{"rateLimit":"00/s"}"#;
27847 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27848 let msg = err.to_string();
27849 assert!(
27850 msg.contains("non-canonical leading zero"),
27851 "expected leading-zero diagnostic in {msg:?}"
27852 );
27853 assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
27854 }
27855
27856 #[test]
27857 fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
27858 // Cross-window pin — the gate is window-agnostic; the
27859 // leading-zero class is a property of the magnitude, not the
27860 // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
27861 // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
27862 // single-window coverage extended across the three canonical
27863 // windows the codec accepts.
27864 let payload = r#"{"rateLimit":"007/h"}"#;
27865 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27866 let msg = err.to_string();
27867 assert!(
27868 msg.contains("non-canonical leading zero"),
27869 "expected leading-zero diagnostic in {msg:?}"
27870 );
27871 assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
27872 }
27873
27874 #[test]
27875 fn rate_limit_serde_rejects_leading_whitespace() {
27876 // `" 100/s"` — the canonical paste-from-aligned-doc /
27877 // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
27878 // the top-level `s.trim()` silently ate the leading space and
27879 // parsed the value to `RateLimit { 100, 1s }`, which then
27880 // round-tripped through `render` to `"100/s"` (a *different*
27881 // canonical string on the next emit) — the exact
27882 // canonical-form-drift class the leading-`+` / leading-zero
27883 // arms already close, extended to the whitespace byte class.
27884 let payload = r#"{"rateLimit":" 100/s"}"#;
27885 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27886 let msg = err.to_string();
27887 assert!(
27888 msg.contains("contains whitespace byte"),
27889 "expected whitespace diagnostic in {msg:?}"
27890 );
27891 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
27892 assert!(
27893 msg.contains("THEORY.md"),
27894 "missing render-determinism contract citation in {msg:?}"
27895 );
27896 }
27897
27898 #[test]
27899 fn rate_limit_serde_rejects_trailing_whitespace() {
27900 // `"100/s "` — the canonical shell-history / trailing-space
27901 // paste footgun. Before this gate the top-level `s.trim()`
27902 // silently ate the trailing space and parsed to
27903 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
27904 // next emit — same canonical-form drift as the leading-space
27905 // sibling, closed on the same whitespace-byte arm.
27906 let payload = r#"{"rateLimit":"100/s "}"#;
27907 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27908 let msg = err.to_string();
27909 assert!(
27910 msg.contains("contains whitespace byte"),
27911 "expected whitespace diagnostic in {msg:?}"
27912 );
27913 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
27914 }
27915
27916 #[test]
27917 fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
27918 // `"100 / s"` — the canonical typographically-spaced author
27919 // shape (the same idiom every prose reference to a rate limit
27920 // renders as, mistakenly retained when the value is pasted
27921 // into a codec-shaped slot). Before this gate the per-part
27922 // `rate_str.trim()` / `unit.trim()` calls silently ate both
27923 // spaces on either side of `/` and parsed to
27924 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
27925 // codec's *internal* whitespace-tolerance vector, orthogonal
27926 // to the leading / trailing surface but the same canonical-
27927 // form-drift class. Pins the arm as strictly stronger than the
27928 // pre-existing top-level `s.trim()` behavior: it fires on
27929 // whitespace anywhere in the value, not just at the string
27930 // boundary.
27931 let payload = r#"{"rateLimit":"100 / s"}"#;
27932 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27933 let msg = err.to_string();
27934 assert!(
27935 msg.contains("contains whitespace byte"),
27936 "expected whitespace diagnostic in {msg:?}"
27937 );
27938 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
27939 }
27940
27941 #[test]
27942 fn rate_limit_serde_rejects_tab_byte() {
27943 // `"\t100/s"` — the canonical paste-from-indented-doc /
27944 // paste-from-YAML-block-scalar footgun where a tab byte leads
27945 // the magnitude. Pins that the gate covers tab (`0x09`) as
27946 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
27947 // members and both would be silently swallowed by `s.trim()`
27948 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
27949 // space alone to the full ASCII-whitespace set (space `0x20`,
27950 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
27951 // the tab arm as a representative of the non-space members.
27952 let payload = r#"{"rateLimit":"\t100/s"}"#;
27953 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27954 let msg = err.to_string();
27955 assert!(
27956 msg.contains("contains whitespace byte"),
27957 "expected whitespace diagnostic in {msg:?}"
27958 );
27959 assert!(
27960 msg.contains("0x09"),
27961 "missing offending tab byte in {msg:?}"
27962 );
27963 }
27964
27965 // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
27966 //
27967 // Successor to the ASCII-whitespace arm (1ad7755) on
27968 // `rate_limit_codec` — closes the strictly-complementary class the
27969 // byte-scan cannot see, through the lifted
27970 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
27971
27972 #[test]
27973 fn rate_limit_serde_rejects_leading_nbsp() {
27974 // NBSP prefix — paste-from-typography footgun. Byte-scan
27975 // misses, `str::trim` silently strips it, value drifts to
27976 // `"100/s"` on next serialize.
27977 let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
27978 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27979 let msg = err.to_string();
27980 assert!(
27981 msg.contains("non-ASCII Unicode whitespace character"),
27982 "expected non-ASCII whitespace diagnostic in {msg:?}"
27983 );
27984 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
27985 }
27986
27987 #[test]
27988 fn rate_limit_serde_rejects_internal_em_space() {
27989 // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
27990 // paste-from-typography footgun on the `<integer>/<unit>`
27991 // shape.
27992 let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
27993 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
27994 let msg = err.to_string();
27995 assert!(
27996 msg.contains("non-ASCII Unicode whitespace character"),
27997 "expected non-ASCII whitespace diagnostic in {msg:?}"
27998 );
27999 assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
28000 }
28001
28002 #[test]
28003 fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
28004 // Positive-control pin: every ASCII-only canonical form the
28005 // renderer emits stays accepted through the new arm.
28006 for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
28007 let payload = format!(r#"{{"rateLimit":{lit}}}"#);
28008 let p: MeshPolicy = serde_json::from_str(&payload)
28009 .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
28010 assert!(p.rate_limit.is_some());
28011 }
28012 }
28013
28014 #[test]
28015 fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
28016 // The boundary case — `"0/s"` is the canonical form
28017 // `render(RateLimit { 0, 1s })` emits, so the codec accepts
28018 // it at the parse layer; the downstream
28019 // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
28020 // `rate == 0` at the typed-validate layer above. Pins the
28021 // partition: the leading-zero gate at the codec layer does
28022 // not poach the rate-zero semantic-validation arm at the
28023 // typed-validate layer above (a future stricter codec must
28024 // not reject `"0/s"` here, or it'd collapse the diagnostic
28025 // partitioning that lets `PolicyRateLimitZero` name the
28026 // offending typed slot).
28027 let payload = r#"{"rateLimit":"0/s"}"#;
28028 let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
28029 panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
28030 });
28031 let rl = policy.rate_limit.expect("rate_limit must be Some");
28032 assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
28033 assert_eq!(
28034 rl.window,
28035 Duration::from_secs(1),
28036 "single-`0` magnitude with `s` unit must parse to window=1s"
28037 );
28038 }
28039
28040 #[test]
28041 fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
28042 // The complementary boundary pin — every magnitude
28043 // `render` emits starts with `[1-9]` (or is the single byte
28044 // `"0"`), so the canonical-form predicate is `(len == 1) ||
28045 // (first byte != '0')`. Pinning the `len > 1 && first byte ==
28046 // '1'` case explicitly so a future tightening of the gate
28047 // (e.g. an over-eager "no leading digit < 5" rule, or a
28048 // mistakenly anchored start-of-magnitude byte check) lands
28049 // here before the canonical-forms-iterating test would catch
28050 // it.
28051 let payload = r#"{"rateLimit":"100/s"}"#;
28052 let policy: MeshPolicy = serde_json::from_str(payload)
28053 .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
28054 let rl = policy.rate_limit.expect("rate_limit must be Some");
28055 assert_eq!(
28056 rl.rate, 100,
28057 "canonical-100 magnitude must parse to rate=100"
28058 );
28059 }
28060
28061 #[test]
28062 fn rate_limit_serde_accepts_integer_canonical_forms() {
28063 // Pin the happy-path: every canonical author shape `render`
28064 // ever emits parses cleanly through the codec post-gate. The
28065 // codec's accepted set (post-gate) is exactly its emitted set
28066 // for the integer-magnitude class — same property
28067 // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
28068 // gates guarantee on the peer codecs. Iterating across rate
28069 // magnitudes (including `"0"`, which the codec accepts even
28070 // though `validate_politicas` rejects `rate == 0` at the typed
28071 // layer above) closes the codec contract at the parse layer
28072 // independently of the validate layer.
28073 for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
28074 for unit_lit in ["s", "m", "h"] {
28075 let lit = format!("{rate_lit}/{unit_lit}");
28076 let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
28077 let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
28078 panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
28079 });
28080 let rl = policy.rate_limit.expect("rate_limit must be Some");
28081 assert_eq!(
28082 rl.rate,
28083 rate_lit.parse::<u32>().unwrap(),
28084 "rate mismatch for {lit:?}"
28085 );
28086 }
28087 }
28088 }
28089
28090 #[test]
28091 fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
28092 // The structural property the gate enforces: serialize ∘
28093 // deserialize is the identity on every canonical author shape.
28094 // Peer of `parse_byte_size`'s and `parse_duration`'s
28095 // `_round_trips_through_render_for_every_canonical_form` tests
28096 // on the rate-limit axis. Before the gate, `"+100/s"` violated
28097 // this (`parse` → `RateLimit { 100, 1s }` → `render` →
28098 // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
28099 for rate in [1u32, 100, 5000, 1_000_000] {
28100 for (window, unit) in [
28101 (Duration::from_secs(1), "s"),
28102 (Duration::from_secs(60), "m"),
28103 (Duration::from_secs(3600), "h"),
28104 ] {
28105 let policy = MeshPolicy {
28106 rate_limit: Some(RateLimit { rate, window }),
28107 ..Default::default()
28108 };
28109 let json = serde_json::to_string(&policy).unwrap();
28110 let expected = format!("\"{rate}/{unit}\"");
28111 assert!(
28112 json.contains(&expected),
28113 "expected {expected:?} in {json:?}"
28114 );
28115 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
28116 assert_eq!(
28117 back.rate_limit, policy.rate_limit,
28118 "round-trip for {json:?}"
28119 );
28120 }
28121 }
28122 }
28123
28124 // ── self-membership cross-slot gate ──────────────────────────────
28125
28126 #[test]
28127 fn validate_no_self_membership_rejects_self_named_membro() {
28128 // An Aplicacao whose `:membros` lists its own `:nome` is a
28129 // one-node lacre-closure recursion — rejected, naming the parent.
28130 let membros = vec![
28131 membro("catalog", "^0.1"),
28132 membro("checkout", "^0.1"),
28133 membro("cart", "^0.1"),
28134 ];
28135 let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
28136 assert!(
28137 matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
28138 "got {err:?}"
28139 );
28140 }
28141
28142 #[test]
28143 fn validate_no_self_membership_accepts_distinct_membros() {
28144 // Positive control: distinct member names (including a member
28145 // that is itself an Aplicacao — recursive composition is valid,
28146 // MESH-COMPOSITION §V) pass the gate.
28147 let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
28148 validate_no_self_membership(&membros, "checkout").unwrap();
28149 }
28150
28151 #[test]
28152 fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
28153 // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
28154 // `NoMembros` arm (the more-fundamental "graph must have nodes"
28155 // gate), not by this cross-slot self-edge gate. Keeping the
28156 // self-membership predicate vacuously-ok on the empty input
28157 // matches its supervisor-axis peer
28158 // (`validate_no_self_supervision_empty_children_is_ok`) and
28159 // makes the gate composable from any future call site (an M4
28160 // CR materializer's per-membros validator) without re-checking
28161 // emptiness.
28162 validate_no_self_membership(&[], "checkout").unwrap();
28163 }
28164
28165 #[test]
28166 fn validate_no_self_membership_diagnostic_names_offending_caixa() {
28167 // Pinning the Display: the self-membership diagnostic must name
28168 // the offending caixa verbatim + the "lists itself" framing the
28169 // author can grep for, so the cluster-far failure surfaces at
28170 // build time with one-line remediation. Same diagnostic shape
28171 // as the supervisor-axis `ChildSupervisesSelf` peer.
28172 let membros = vec![membro("orquestra", "^0.1")];
28173 let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
28174 let msg = err.to_string();
28175 assert!(
28176 msg.contains("orquestra"),
28177 "diagnostic must name the offending caixa nome (got: {msg:?})"
28178 );
28179 assert!(
28180 msg.contains("lists itself"),
28181 "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
28182 );
28183 }
28184
28185 #[test]
28186 fn default_servico_port_constant_pins_canonical_8080_literal() {
28187 // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
28188 // at the verbatim `8080` literal both consumers (the
28189 // `Entrada::port` serde default via [`default_port`] and the
28190 // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
28191 // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
28192 // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
28193 // discipline (a085b26) on the per-renderer canonical-K8s-axis
28194 // string-constant axis: a future refactor that drifts the
28195 // constant out from under either consumer surfaces here ahead
28196 // of every per-renderer's first emission. The literal value
28197 // matches the well-known HTTP-alt port the `pleme-computeunit`
28198 // library chart already emits as its `trigger.service.port`
28199 // default — by construction the same value the substrate
28200 // assumes about every Servico's in-cluster L4 listener.
28201 assert_eq!(
28202 DEFAULT_SERVICO_PORT, 8080,
28203 "canonical Servico port literal must remain `8080` verbatim — \
28204 this is the value both the `Entrada::port` serde default and the \
28205 caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
28206 );
28207 }
28208
28209 #[test]
28210 fn default_port_helper_returns_canonical_servico_port_constant() {
28211 // The bridge-arm — pins that the [`default_port`] helper
28212 // [`Entrada::port`]'s `#[serde(default = "default_port")]`
28213 // attribute hooks routes through the lifted
28214 // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
28215 // literal. A future refactor that re-introduces the `8080`
28216 // literal at the helper's return site (silently re-opening
28217 // the drift footgun this lift closed) surfaces here ahead of
28218 // every author-side `(:entrada (:host … :para …))` slot
28219 // without an explicit `:port`. Peer with the
28220 // `default_namespace_re_export_points_at_caixa_core_canonical`
28221 // pin on the caixa-mesh-side re-export axis.
28222 assert_eq!(
28223 default_port(),
28224 DEFAULT_SERVICO_PORT,
28225 "the serde-default helper must route through the lifted constant"
28226 );
28227 }
28228
28229 #[test]
28230 fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
28231 // The end-to-end pin — an author-surface `(:entrada (:host …
28232 // :para …))` without an explicit `:port` slot deserializes to
28233 // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
28234 // verbatim. Routes the canonical lifted constant through both
28235 // the serde-default machinery (the `#[serde(default =
28236 // "default_port")]` attribute) and the typed-value-shape
28237 // contract (the resulting [`Entrada::port`] value). A future
28238 // refactor that drifts either axis — replacing the serde
28239 // hook's helper, changing the typed slot's wire shape — would
28240 // surface here before any per-renderer's CNP / Gateway /
28241 // HTTPRoute emission consumed the drifted default.
28242 let entrada: Entrada =
28243 serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
28244 assert_eq!(
28245 entrada.port, DEFAULT_SERVICO_PORT,
28246 "the serde default must materialize as the lifted canonical Servico port"
28247 );
28248 }
28249
28250 #[test]
28251 fn servico_port_min_pins_canonical_accept_set_floor() {
28252 // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
28253 // verbatim `1` literal every typed `:entrada :port` acceptance
28254 // gate keys off. Peer with the
28255 // [`default_servico_port_constant_pins_canonical_8080_literal`]
28256 // discipline on the canonical-Servico-port-constant axis: a
28257 // future refactor that drifts the accept-set floor out from
28258 // under the sole consumer at [`AplicacaoSpec::validate`]'s
28259 // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
28260 // every per-`:entrada` `EntradaPortZero` diagnostic. The
28261 // literal value matches the IANA-registered TCP/UDP port
28262 // space floor (`1..=65535` — port `0` is the "any ephemeral"
28263 // sentinel, not a well-defined destination the substrate's
28264 // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
28265 // axis can honor).
28266 assert_eq!(
28267 SERVICO_PORT_MIN, 1,
28268 "canonical Servico port accept-set floor must remain `1` verbatim — \
28269 this is the value the `AplicacaoSpec::validate` gate at \
28270 `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
28271 );
28272 }
28273
28274 #[test]
28275 fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
28276 // The cross-const invariant pin — the substrate's canonical
28277 // default port must satisfy its own accept-set floor by
28278 // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
28279 // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
28280 // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
28281 // override the operator pins through a future
28282 // `:placement :default-port` slot that lands out-of-range, a
28283 // per-edition Servico-port migration that lifted the floor
28284 // above the previous default without coordinating the pair —
28285 // would silently invalidate the serde-default emission at
28286 // every author-side `(:entrada (:host … :para …))` slot
28287 // without an explicit `:port`: the default port would fall
28288 // below the accept-set floor, the `AplicacaoSpec::validate`
28289 // gate would reject every default-carrying Aplicacao as
28290 // `EntradaPortZero`, and the substrate's typed
28291 // `(defcaixa … :kind Aplicacao)` surface would fail validate
28292 // on every Aplicacao whose author omitted `:entrada :port`
28293 // for the substrate's chosen default — a class of authoring-
28294 // surface footguns the compile-time pin structurally closes.
28295 // Peer with the
28296 // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
28297 // (27f9b34) cross-const invariant pin discipline on the peer
28298 // canonical-Helm-per-values-block child-chart-enablement-toggle
28299 // axis pair.
28300 const {
28301 assert!(
28302 SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
28303 "the substrate's canonical default port DEFAULT_SERVICO_PORT \
28304 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
28305 every default-carrying `(:entrada (:host … :para …))` slot \
28306 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
28307 through the serde default hook and must pass the \
28308 `AplicacaoSpec::validate` floor gate by construction",
28309 );
28310 }
28311 }
28312
28313 #[test]
28314 fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
28315 // The gate-site pin — asserts the `AplicacaoSpec::validate`
28316 // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
28317 // `EntradaPortZero` diagnostic on the below-floor input
28318 // `port: 0` (the only below-floor value the `u16` field can
28319 // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
28320 // is the singleton `{0}`). A future refactor that drifts the
28321 // gate off the lifted const (silently re-introducing an
28322 // inline `if e.port == 0` byte-check) surfaces here — the
28323 // pin cannot distinguish `< 1` from `== 0` on the current
28324 // floor, but it *does* pin that the diagnostic fires on `0`
28325 // through whichever gate is wired, so any future accept-set
28326 // floor migration (a hypothetical unprivileged-only
28327 // migration lifting `SERVICO_PORT_MIN` to `1024`) must
28328 // update this test alongside the const declaration —
28329 // structurally guaranteeing the gate + accept-set + pin
28330 // trio move together. Peer with the
28331 // [`rejects_zero_entrada_port`] behavioral pin on the same
28332 // per-`:entrada :port` axis — that pin asserts the pre-lift
28333 // behavioral contract (`port: 0` → `EntradaPortZero`); this
28334 // pin adds the structural link to the lifted floor const.
28335 assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
28336 let mut s = three_member_spec();
28337 s.entrada.as_mut().unwrap().port = 0;
28338 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
28339 }
28340
28341 // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
28342
28343 #[test]
28344 fn membro_serde_keys_match_lifted_membro_key_consts() {
28345 // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
28346 // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
28347 // name the exact camelCase JSON keys the
28348 // `#[serde(rename_all = "camelCase")]` attribute on
28349 // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
28350 // that each canonical byte-sequence appears verbatim in the
28351 // JSON — a future accidental `rename_all = "snake_case"` /
28352 // `"kebab-case"` / verbatim-field-name flip at the derive
28353 // attribute (any of which would silently break every downstream
28354 // JSON consumer that reaches for one of the two consts via
28355 // `Value::get(...)`) surfaces here as a build-time test failure
28356 // at `aplicacao.rs`, not as an apply-time
28357 // `.get(<stale-canonical-const>)` returning `None` far from the
28358 // derive-attr drift's commit. Peer with the sibling
28359 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
28360 // (40cc4e5) pin on the M2 supervision-tree top-level axis —
28361 // same discipline the SupervisorSpec top-level lift established,
28362 // extended here to the M3 [`Membro`] per-`:membros` axis.
28363 let m = Membro {
28364 caixa: "catalog".into(),
28365 versao: "^0.1".into(),
28366 };
28367 let json = serde_json::to_string(&m).unwrap();
28368 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
28369 let quoted = format!("\"{key}\"");
28370 assert!(
28371 json.contains("ed),
28372 "serialized Membro must carry the lifted MEMBRO_KEY_* \
28373 byte-sequence {quoted} verbatim in the JSON emission \
28374 (got: {json})",
28375 );
28376 }
28377 }
28378
28379 #[test]
28380 fn membro_key_consts_are_pairwise_distinct() {
28381 // Cross-axis drift-detection pin: a future collapse of the two
28382 // canonical [`Membro`] per-entry byte-strings onto the same
28383 // value (e.g. an accidental copy-paste flip of
28384 // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
28385 // silently reroute every downstream probe on one axis onto the
28386 // sibling axis's overlay entry and pass every propagation-probe
28387 // test that expected only the stale axis's value. Peer of the
28388 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
28389 // (40cc4e5).
28390 let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
28391 for (i, a) in all.iter().enumerate() {
28392 for b in all.iter().skip(i + 1) {
28393 assert_ne!(
28394 a, b,
28395 "MEMBRO_KEY_* consts must be pairwise-distinct \
28396 canonical byte-sequences — got `{a}` == `{b}`",
28397 );
28398 }
28399 }
28400 }
28401
28402 // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
28403 // URL-path fallback resolver every HTTPRoute-aware renderer
28404 // reaching for a per-rule path-list resolution routes through.
28405 // The four pin tests below fix the four-way accept-set the
28406 // resolver must always honor: (:paths-non-empty-verbatim,
28407 // :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
28408 // :paths-preserves-order-across-multiple-entries) — drift on any
28409 // arm surfaces at caixa-core build time rather than at cluster-
28410 // apply time. Peer discipline with `MeshPolicy::is_empty` on the
28411 // sibling `:politicas` typed-primitive dispatch axis.
28412
28413 fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
28414 Entrada {
28415 host: "example.com".into(),
28416 para: "cart".into(),
28417 paths: paths.into_iter().map(String::from).collect(),
28418 port: DEFAULT_SERVICO_PORT,
28419 }
28420 }
28421
28422 #[test]
28423 fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
28424 // The typed `:entrada :paths` slot carries an author-declared
28425 // list — the resolver returns each entry verbatim, no
28426 // catch-all substitution. The canonical "author declared
28427 // paths, honor them verbatim" arm of the path-list dispatch.
28428 let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
28429 assert_eq!(
28430 e.resolved_paths(),
28431 vec!["/api/cart", "/api/products"],
28432 "resolved_paths must return each `:entrada :paths` entry \
28433 verbatim when the typed slot is non-empty (got {:?})",
28434 e.resolved_paths(),
28435 );
28436 }
28437
28438 #[test]
28439 fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
28440 // Empty `:entrada :paths` slot — the resolver substitutes the
28441 // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
28442 // catch-all fallback verbatim. Pins the empty-arm of the
28443 // resolver's four-way accept-set against a future silent
28444 // detour that returned an empty Vec (which would emit an
28445 // HTTPRoute with zero rules — silently dropping every
28446 // external `:entrada` flow at admission time), routed to a
28447 // different fallback shape, or dropped the catch-all
28448 // altogether.
28449 let e = entrada_with_paths(vec![]);
28450 assert_eq!(
28451 e.resolved_paths(),
28452 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
28453 "resolved_paths on empty `:entrada :paths` must fall back \
28454 to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
28455 all — got {:?}",
28456 e.resolved_paths(),
28457 );
28458 }
28459
28460 #[test]
28461 fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
28462 // Single-entry `:entrada :paths` — the resolver returns the
28463 // single declared path verbatim, NOT the catch-all fallback
28464 // (author declared a path, honor it — the empty-arm and the
28465 // len-1 arm are semantically distinct axes of the resolver's
28466 // accept-set). Pins that the resolver treats "author declared
28467 // one path" as authored input, not as the empty case.
28468 let e = entrada_with_paths(vec!["/api/only"]);
28469 assert_eq!(
28470 e.resolved_paths(),
28471 vec!["/api/only"],
28472 "resolved_paths on single-entry `:entrada :paths` must \
28473 return the declared path verbatim, NOT the catch-all \
28474 fallback (got {:?})",
28475 e.resolved_paths(),
28476 );
28477 }
28478
28479 #[test]
28480 fn resolved_paths_preserves_author_declared_order() {
28481 // The `:entrada :paths` list is author-ordered — the resolver
28482 // preserves the author's declaration order verbatim, since
28483 // per-rule dispatch order at the K8s Gateway API HTTPRoute
28484 // consumer is significant (first-match-wins under the
28485 // path-prefix matcher). Pins against a future silent
28486 // re-sort / dedup / normalize detour that reordered author
28487 // input.
28488 let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
28489 assert_eq!(
28490 e.resolved_paths(),
28491 vec!["/z/last", "/a/first", "/m/mid"],
28492 "resolved_paths must preserve author-declared `:entrada \
28493 :paths` order verbatim — got {:?}",
28494 e.resolved_paths(),
28495 );
28496 }
28497
28498 // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
28499 // slot `&[String]` slice accessor every per-`:entrada` consumer
28500 // that must see the author's declaration verbatim (not the
28501 // fallback-applied projection the sibling `resolved_paths`
28502 // returns) routes through. The three pin tests below fix the
28503 // accept-set the accessor must honor: (:non-empty-byte-equal,
28504 // :empty-projects-empty-slice, :preserves-author-declared-order)
28505 // — drift on any arm surfaces at caixa-core build time rather
28506 // than at cluster-apply time. Peer discipline with the sibling
28507 // [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
28508 // peer M3 mesh-slot `Vec<String>`-carry axis.
28509
28510 #[test]
28511 fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
28512 // Byte-equal pin: [`Entrada::paths`] must project the raw
28513 // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
28514 // slice borrowed from the typed slot's own [`Vec<String>`]
28515 // storage — no re-ordering, no dedup, no per-entry normalization,
28516 // no fallback substitution (the fallback-applying projection is
28517 // the sibling [`Entrada::resolved_paths`] resolver). Pins against
28518 // a future silent detour that re-normalized the list, dropped
28519 // duplicates the [`AplicacaoSpec::validate`]
28520 // `EntradaPathDuplicate` refusal already rejects at build time,
28521 // or (most severe) accidentally routed through the fallback-
28522 // applying sibling and returned the substrate catch-all when
28523 // the author declared an empty list — collapsing the raw-slot
28524 // and fallback-applied axes into one and breaking the
28525 // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
28526 //
28527 // Peer of the sibling
28528 // [`Placement::clusters`]-shape byte-equal pin
28529 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
28530 // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
28531 let fixtures: Vec<Vec<String>> = vec![
28532 Vec::new(),
28533 vec!["/api/cart".into()],
28534 vec!["/api/cart".into(), "/api/products".into()],
28535 vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
28536 ];
28537 for paths in fixtures {
28538 let e = Entrada {
28539 host: "example.com".into(),
28540 para: "cart".into(),
28541 paths: paths.clone(),
28542 port: DEFAULT_SERVICO_PORT,
28543 };
28544 assert_eq!(
28545 e.paths(),
28546 paths.as_slice(),
28547 "Entrada::paths must return :entrada :paths verbatim \
28548 (got {:?}, expected {:?})",
28549 e.paths(),
28550 paths.as_slice(),
28551 );
28552 assert_eq!(
28553 e.paths(),
28554 e.paths.as_slice(),
28555 "Entrada::paths accessor and .paths.as_slice() field \
28556 access must byte-equal — the accessor is the substrate-\
28557 primitive typed dispatch every downstream per-`:entrada` \
28558 raw-slot path-list consumer must route through",
28559 );
28560 assert_eq!(
28561 e.paths().len(),
28562 e.paths.len(),
28563 "Entrada::paths().len() must byte-equal self.paths.len() \
28564 — a length drift would silently split the paired \
28565 pre-flight cascade-head `.is_empty()` probe input in \
28566 the sibling [`Entrada::resolved_paths`] resolver from \
28567 the per-entry validate loop's traversal input in \
28568 [`AplicacaoSpec::validate`]",
28569 );
28570 }
28571 }
28572
28573 #[test]
28574 fn resolved_paths_reads_through_lifted_paths_accessor() {
28575 // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
28576 // pre-flight `.paths().is_empty()` cascade-head probe (which
28577 // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
28578 // catch-all fallback arm when the accessor projects the empty
28579 // slice) and the per-entry `.paths().iter().map(String::as_str)`
28580 // projection (which must reach every entry in the same order
28581 // the accessor projects, so the sibling
28582 // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
28583 // per-entry projection stay in lockstep by construction) must
28584 // both key off the lifted accessor. Pins the two-site coherence
28585 // by exercising each production consumer end-to-end: (1) the
28586 // catch-all-fallback arm under the empty slice, (2) the
28587 // author-declared-verbatim arm under a two-entry cohort whose
28588 // per-entry projection must byte-equal the input's per-entry
28589 // author-declared paths in the author's declared order.
28590 //
28591 // Peer of the sibling M3
28592 // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
28593 // `validate_placement_reads_through_lifted_clusters_accessor`
28594 // on the sibling `Placement::clusters` reader-site convergence.
28595 let empty = entrada_with_paths(vec![]);
28596 assert_eq!(
28597 empty.resolved_paths(),
28598 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
28599 "resolved_paths on empty :entrada :paths must trip the \
28600 lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
28601 catch-all fallback — routing through the lifted paths() \
28602 accessor must not silently drop the fallback arm",
28603 );
28604
28605 let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
28606 assert_eq!(
28607 declared.resolved_paths(),
28608 vec!["/api/cart", "/api/products"],
28609 "resolved_paths on non-empty :entrada :paths must return each \
28610 entry verbatim in the author's declared order — routing \
28611 through the lifted paths() accessor must not silently \
28612 reorder or drop entries",
28613 );
28614 // Byte-equal pin against the raw-slot accessor to keep the
28615 // fallback-applying resolver's per-entry projection input in
28616 // lockstep with the raw-slot accessor's projection.
28617 let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
28618 assert_eq!(
28619 declared.resolved_paths(),
28620 raw_projected,
28621 "resolved_paths non-empty projection must byte-equal the \
28622 lifted paths() accessor's per-entry String::as_str projection \
28623 — the two projections share the same input slice by \
28624 construction, so any drift here would surface a silent \
28625 re-ordering / dedup / normalization detour in the resolver",
28626 );
28627 }
28628
28629 #[test]
28630 fn validate_reads_through_lifted_entrada_paths_accessor() {
28631 // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
28632 // per-entry value-shape gate's `for p in e.paths()` traversal
28633 // (which must reach every entry in the same order the accessor
28634 // projects, so both the per-entry `EntradaPathEmpty` /
28635 // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
28636 // the duplicate-detection HashSet insert that trips
28637 // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
28638 // projection) must route through the lifted accessor. Pins the
28639 // coherence by exercising each production consumer end-to-end:
28640 // (1) the `EntradaPathEmpty` refusal fires on the second entry
28641 // of a two-entry cohort whose head is valid but tail is empty
28642 // (which requires the loop to reach the second entry through
28643 // the accessor), and (2) the `EntradaPathDuplicate` refusal
28644 // fires on the second entry of a two-entry cohort that shares
28645 // a path (which requires the loop to reach both entries — a
28646 // first-entry-only projection would silently pass since the
28647 // dedup HashSet has room for the first insert).
28648 //
28649 // Peer of the sibling
28650 // `validate_placement_reads_through_lifted_clusters_accessor`
28651 // on the sibling `Placement::clusters` reader-site convergence.
28652 let base = crate::AplicacaoSpec {
28653 membros: vec![crate::Membro {
28654 caixa: "cart".into(),
28655 versao: "^0.1".into(),
28656 }],
28657 contratos: Vec::new(),
28658 politicas: crate::MeshPolicy::default(),
28659 placement: crate::Placement {
28660 estrategia: crate::PlacementStrategy::SingleNode,
28661 clusters: vec!["rio".into()],
28662 shard_key: None,
28663 affinity: None,
28664 },
28665 entrada: Some(Entrada {
28666 host: "example.com".into(),
28667 para: "cart".into(),
28668 paths: vec!["/api/cart".into(), String::new()],
28669 port: DEFAULT_SERVICO_PORT,
28670 }),
28671 };
28672 assert_eq!(
28673 base.validate(),
28674 Err(crate::AplicacaoError::EntradaPathEmpty),
28675 "validate must trip EntradaPathEmpty on the second entry of \
28676 a two-entry cohort — routing through the lifted paths() \
28677 accessor must not silently short-circuit the loop at the \
28678 valid head entry",
28679 );
28680
28681 let mut dup = base;
28682 dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
28683 assert_eq!(
28684 dup.validate(),
28685 Err(crate::AplicacaoError::EntradaPathDuplicate {
28686 path: "/api/cart".into(),
28687 }),
28688 "validate must trip EntradaPathDuplicate on the second entry \
28689 of a two-entry cohort that shares a path — routing through \
28690 the lifted paths() accessor must not silently short-circuit \
28691 the dedup HashSet insert at the first entry",
28692 );
28693 }
28694
28695 // ── Entrada::hostname / Entrada::hostnames — the substrate-
28696 // canonical per-`:entrada` DNS-hostname resolver pair every
28697 // Gateway-API-aware renderer reaching for a per-listener
28698 // singular `hostname:` filter (Gateway) or a per-route plural
28699 // `spec.hostnames[]` filter list (HTTPRoute) routes through.
28700 // The three pin tests below fix the two-way accept-set the pair
28701 // must always honor: (:singular-byte-equal-to-host,
28702 // :plural-is-singleton-of-singular, :plural-len-is-one) — drift
28703 // on any arm surfaces at caixa-core build time rather than at
28704 // cluster-apply time when the API server refuses the HTTPRoute
28705 // for non-intersecting hostname filters. Peer discipline with
28706 // the sibling `resolved_paths` accept-set pin block above on the
28707 // per-`:entrada` path-list resolver axis.
28708
28709 fn entrada_with_host(host: &str) -> Entrada {
28710 Entrada {
28711 host: host.into(),
28712 para: "cart".into(),
28713 paths: Vec::new(),
28714 port: DEFAULT_SERVICO_PORT,
28715 }
28716 }
28717
28718 #[test]
28719 fn hostname_returns_entrada_host_byte_equal() {
28720 // The canonical singular-axis pin: [`Entrada::hostname`] must
28721 // return the `:entrada :host` field byte-for-byte, borrowed
28722 // from the typed slot's own [`String`] storage. Pins against a
28723 // future silent detour that re-normalized the host (an
28724 // accidental `.to_lowercase()` — validate_entrada_host already
28725 // enforces lowercase, so any re-normalization is redundant + a
28726 // drift surface between the validator and the accessor), a
28727 // trailing-`.` fully-qualified DNS shape substitution, or a
28728 // Punycode round-trip that lowered a Unicode host through IDNA.
28729 let e = entrada_with_host("checkout.quero.cloud");
28730 assert_eq!(
28731 e.hostname(),
28732 "checkout.quero.cloud",
28733 "Entrada::hostname must return :entrada :host verbatim \
28734 (got {:?})",
28735 e.hostname(),
28736 );
28737 assert_eq!(
28738 e.hostname(),
28739 e.host.as_str(),
28740 "Entrada::hostname must byte-equal the .host field access",
28741 );
28742 }
28743
28744 #[test]
28745 fn hostnames_returns_singleton_of_hostname_accessor() {
28746 // The pair-invariant pin: [`Entrada::hostnames`] must always
28747 // return exactly `vec![hostname()]` — the singleton list whose
28748 // sole entry is the substrate's canonical per-`:entrada`
28749 // singular hostname. Pins the two-consumer coherence axis: the
28750 // Gateway listener's singular `hostname:` filter and the
28751 // HTTPRoute's plural `spec.hostnames[]` filter list must
28752 // agree, else the Gateway API v1.x conformance layer rejects
28753 // the HTTPRoute at attach time with
28754 // `Accepted:False/NoMatchingParent` (the parent Gateway's
28755 // listener hostname doesn't intersect the route's hostname
28756 // filter list) — a divergence whose apply-time symptom is far
28757 // from any single-site commit and never surfaces in the
28758 // emitted YAML. Pinning the pair-invariant here makes any
28759 // future accidental split (an accidental `.to_string() + "."`
28760 // trailing-`.` on the plural side that didn't land on the
28761 // singular side, an accidental prefix stripping on one axis,
28762 // an accidental wildcard prepend the SNI fan-out overlay
28763 // authors on the plural side without a paired singular
28764 // migration) trip at caixa-core build time.
28765 let e = entrada_with_host("checkout.quero.cloud");
28766 assert_eq!(
28767 e.hostnames(),
28768 vec![e.hostname()],
28769 "Entrada::hostnames must return `vec![hostname()]` under \
28770 the pair-invariant — got {:?} vs. singleton {:?}",
28771 e.hostnames(),
28772 vec![e.hostname()],
28773 );
28774 }
28775
28776 #[test]
28777 fn hostnames_is_singleton_under_single_host_author_surface() {
28778 // The singleton-shape pin: under today's single-hostname-per-
28779 // `:entrada` author surface (the `:host` slot is a single
28780 // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
28781 // must always return a list of length exactly one. Pins
28782 // against a future silent detour that returned an empty list
28783 // (which would emit an HTTPRoute with `spec.hostnames: []` —
28784 // matching every incoming Host header regardless of the
28785 // Aplicacao's declared ingress apex, silently over-matching
28786 // every foreign VirtualHost the parent Gateway also fronts) or
28787 // a duplicated entry (which the Gateway API v1.x parser
28788 // accepts as a `[]-length-2 list of equal hostnames]` but
28789 // whose semantics differ from the intended singleton). The
28790 // author-surface extension point ("a future `:entrada
28791 // :alt-hosts` list overlay" the docstring names) is the sole
28792 // future axis that flips this pin — that migration will re-
28793 // author this test to pin the new plural cardinality.
28794 let e = entrada_with_host("checkout.quero.cloud");
28795 assert_eq!(
28796 e.hostnames().len(),
28797 1,
28798 "Entrada::hostnames must be a singleton under today's \
28799 single-hostname-per-`:entrada` author surface — got \
28800 length {}: {:?}",
28801 e.hostnames().len(),
28802 e.hostnames(),
28803 );
28804 }
28805
28806 // ── Entrada::destination — the substrate-canonical per-`:entrada`
28807 // destination-Servico scalar accessor every Gateway-API
28808 // HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
28809 // discriminator arg (HTTPRoute name composer) or a per-rule
28810 // `backendRefs[0].name` axis routes through. The two pin tests
28811 // below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
28812 // either arm surfaces at caixa-core build time rather than at
28813 // cluster-apply time when an HTTPRoute's `metadata.name` and
28814 // `backendRefs[]` silently disagree on which destination Servico
28815 // the ingress fronts. Peer discipline with the sibling
28816 // `resolved_paths` + `hostname` + `hostnames` accept-set pin
28817 // blocks above on the per-`:entrada` path-list / DNS-hostname
28818 // resolver axes.
28819
28820 #[test]
28821 fn destination_returns_entrada_para_byte_equal() {
28822 // The canonical destination-scalar pin: [`Entrada::destination`]
28823 // must return the `:entrada :para` field byte-for-byte, borrowed
28824 // from the typed slot's own [`String`] storage. Pins against a
28825 // future silent detour that re-normalized the destination (an
28826 // accidental `.to_lowercase()` — the destination Servico is
28827 // already validated as a DNS-1123 label upstream, so any
28828 // re-normalization is redundant + a drift surface between the
28829 // validator and the accessor), a namespace-prefix rewrite (an
28830 // accidental `format!("{namespace}/{para}")` per-CR fully-
28831 // qualified rewrite that didn't land on the peer axis), or a
28832 // per-cluster suffix stamp the operator authors on one
28833 // consumer without the other.
28834 for para in ["cart", "checkout", "catalog", "orders-v2"] {
28835 let e = Entrada {
28836 host: "checkout.quero.cloud".into(),
28837 para: para.into(),
28838 paths: Vec::new(),
28839 port: DEFAULT_SERVICO_PORT,
28840 };
28841 assert_eq!(
28842 e.destination(),
28843 para,
28844 "Entrada::destination must return :entrada :para verbatim \
28845 (got {:?}, expected {para:?})",
28846 e.destination(),
28847 );
28848 assert_eq!(
28849 e.destination(),
28850 e.para.as_str(),
28851 "Entrada::destination must byte-equal the .para field access",
28852 );
28853 }
28854 }
28855
28856 #[test]
28857 fn destination_borrows_from_entrada_para_storage() {
28858 // The borrow-not-copy pin: [`Entrada::destination`] must
28859 // return a `&str` slice that borrows from the typed slot's
28860 // own [`String`] storage — same-address invariant with
28861 // `entrada.para.as_str()`. Pins against a future silent detour
28862 // that allocated a fresh `String` (`self.para.clone()` in the
28863 // body would type-check but silently drop the borrow, and
28864 // every downstream consumer that assumed the returned slice
28865 // outlives `&self` would break on a stale-reference use-after-
28866 // free). Peer with the sibling `hostname_returns_entrada_
28867 // host_byte_equal` on the singular-DNS-hostname axis.
28868 let e = entrada_with_host("checkout.quero.cloud");
28869 let dest = e.destination();
28870 let para_slice = e.para.as_str();
28871 assert_eq!(
28872 dest.as_ptr(),
28873 para_slice.as_ptr(),
28874 "Entrada::destination must borrow from the .para String's \
28875 backing storage — a fresh allocation here means the \
28876 accessor no longer names the substrate-primitive typed \
28877 dispatch and every downstream consumer would silently \
28878 carry a detached copy",
28879 );
28880 assert_eq!(
28881 dest.len(),
28882 para_slice.len(),
28883 "Entrada::destination and .para.as_str() must byte-equal in \
28884 length as well as in address",
28885 );
28886 }
28887
28888 #[test]
28889 fn port_returns_entrada_port_verbatim_across_permutations() {
28890 // The canonical L4-port-scalar pin: [`Entrada::port`] must
28891 // return the `:entrada :port` field verbatim as a `u16` across
28892 // every author-declared value in the validated accept-set
28893 // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
28894 // silent detour that clamped the port (an accidental
28895 // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
28896 // land on the peer [`AplicacaoSpec::port_for_destination`]
28897 // resolver), rewrote it through a per-cluster port-remap table
28898 // the operator authors on one consumer without the other, or
28899 // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
28900 // serde-default value (which would silently collapse the
28901 // distinction between "author explicitly declared `:port 8080`"
28902 // and "author omitted the slot and inherited the default" the
28903 // future per-cluster override slot depends on). Peer with the
28904 // sibling `destination_returns_entrada_para_byte_equal` +
28905 // `hostname_returns_entrada_host_byte_equal` pins on the
28906 // per-`:entrada` `&str` scalar axes.
28907 for port in [
28908 SERVICO_PORT_MIN,
28909 DEFAULT_SERVICO_PORT,
28910 8443u16,
28911 9090u16,
28912 u16::MAX,
28913 ] {
28914 let e = Entrada {
28915 host: "checkout.quero.cloud".into(),
28916 para: "cart".into(),
28917 paths: Vec::new(),
28918 port,
28919 };
28920 assert_eq!(
28921 e.port(),
28922 port,
28923 "Entrada::port must return :entrada :port verbatim \
28924 (got {}, expected {port})",
28925 e.port(),
28926 );
28927 assert_eq!(
28928 e.port(),
28929 e.port,
28930 "Entrada::port accessor and .port field access must \
28931 byte-equal — the accessor is the substrate-primitive \
28932 typed dispatch every downstream L4-port consumer must \
28933 route through",
28934 );
28935 }
28936 }
28937
28938 #[test]
28939 fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
28940 // Two-consumer coherence pin: the
28941 // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
28942 // (which reads through [`Entrada::port`] to compare against
28943 // [`SERVICO_PORT_MIN`]) and the
28944 // [`AplicacaoSpec::port_for_destination`] resolver (which reads
28945 // through [`Entrada::port`] to emit the per-destination
28946 // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
28947 // lifted accessor, so any future rebrand on the typed slot's
28948 // reader shape lands at exactly one place. Pins the two-site
28949 // coherence by exercising a below-floor port through validate
28950 // (which must reject) and a validated in-accept-set port through
28951 // port_for_destination (which must emit the same value the
28952 // accessor returns).
28953 let mut spec = three_member_spec();
28954 if let Some(e) = spec.entrada.as_mut() {
28955 e.port = 0;
28956 }
28957 assert_eq!(
28958 spec.validate().unwrap_err(),
28959 AplicacaoError::EntradaPortZero,
28960 "validate must reject `:entrada :port 0` through the lifted \
28961 Entrada::port accessor — port zero lies below \
28962 SERVICO_PORT_MIN and the validator routes through port() \
28963 to name the floor",
28964 );
28965
28966 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
28967 let mut spec = three_member_spec();
28968 if let Some(e) = spec.entrada.as_mut() {
28969 e.port = port;
28970 }
28971 spec.validate().expect(
28972 "entrada with in-accept-set :port must validate — the \
28973 structural-floor gate reads through Entrada::port",
28974 );
28975 let entrada_ref = spec.entrada().expect(":entrada present");
28976 assert_eq!(
28977 spec.port_for_destination(entrada_ref.destination()),
28978 entrada_ref.port(),
28979 "port_for_destination(entrada.destination()) must equal \
28980 entrada.port() — the two consumers of the per-:entrada \
28981 L4-port axis (validator, per-destination resolver) both \
28982 route through Entrada::port",
28983 );
28984 }
28985 }
28986
28987 #[test]
28988 fn wit_contract_source_returns_de_byte_equal_across_permutations() {
28989 // The canonical caller-Servico-scalar pin: [`WitContract::source`]
28990 // must return the `:contratos :de` field byte-for-byte, borrowed
28991 // from the typed slot's own [`String`] storage. Peer of the
28992 // sibling `destination_returns_entrada_para_byte_equal` pin on
28993 // the per-`:entrada` axis — same "the substrate-primitive
28994 // accessor must byte-equal the raw field access verbatim across
28995 // every author-declared value" discipline extended to the
28996 // per-`:contratos` caller arm. Pins against a future silent
28997 // detour that re-normalized the caller (an accidental
28998 // `.to_lowercase()` — every `:contratos :de` is validated as a
28999 // DNS-1123 label upstream via `validate_contrato_caixa`, so any
29000 // re-normalization is redundant + a drift surface between the
29001 // validator and the accessor), a namespace-prefix rewrite (an
29002 // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
29003 // rewrite that didn't land on the peer axis), or a per-cluster
29004 // suffix stamp the operator authors on one consumer without the
29005 // other.
29006 for de in ["cart", "checkout", "catalog", "orders-v2"] {
29007 let c = WitContract {
29008 de: de.into(),
29009 para: "downstream".into(),
29010 wit: "wasi:http/proxy".into(),
29011 endpoint: Some("/lookup".into()),
29012 subject: None,
29013 slot: None,
29014 };
29015 assert_eq!(
29016 c.source(),
29017 de,
29018 "WitContract::source must return :contratos :de verbatim \
29019 (got {:?}, expected {de:?})",
29020 c.source(),
29021 );
29022 assert_eq!(
29023 c.source(),
29024 c.de.as_str(),
29025 "WitContract::source must byte-equal the .de field access",
29026 );
29027 }
29028 }
29029
29030 #[test]
29031 fn wit_contract_source_borrows_from_de_storage() {
29032 // The borrow-not-copy pin: [`WitContract::source`] must return a
29033 // `&str` slice that borrows from the typed slot's own [`String`]
29034 // storage — same-address invariant with `c.de.as_str()`. Pins
29035 // against a future silent detour that allocated a fresh `String`
29036 // (`self.de.clone()` in the body would type-check but silently
29037 // drop the borrow, and every downstream consumer that assumed
29038 // the returned slice outlives `&self` would break on a stale-
29039 // reference use-after-free). Peer of the sibling
29040 // `destination_borrows_from_entrada_para_storage` on the
29041 // per-`:entrada` axis.
29042 let c = WitContract {
29043 de: "cart".into(),
29044 para: "catalog".into(),
29045 wit: "wasi:http/proxy".into(),
29046 endpoint: Some("/lookup".into()),
29047 subject: None,
29048 slot: None,
29049 };
29050 let src = c.source();
29051 let de_slice = c.de.as_str();
29052 assert_eq!(
29053 src.as_ptr(),
29054 de_slice.as_ptr(),
29055 "WitContract::source must borrow from the .de String's \
29056 backing storage — a fresh allocation here means the \
29057 accessor no longer names the substrate-primitive typed \
29058 dispatch and every downstream consumer would silently \
29059 carry a detached copy",
29060 );
29061 assert_eq!(
29062 src.len(),
29063 de_slice.len(),
29064 "WitContract::source and .de.as_str() must byte-equal in \
29065 length as well as in address",
29066 );
29067 }
29068
29069 #[test]
29070 fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
29071 // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
29072 // must return the `:contratos :para` field byte-for-byte,
29073 // borrowed from the typed slot's own [`String`] storage. Peer of
29074 // the sibling `destination_returns_entrada_para_byte_equal` on
29075 // the per-`:entrada` axis — both accessors name "the destination-
29076 // Servico byte-string" concept on their respective mesh-slot
29077 // atoms (per-ingress apex vs. per-typed-edge callee) and both
29078 // must project the underlying `.para` field verbatim so every
29079 // downstream renderer that composes them with peer accessors
29080 // (e.g. `spec.port_for_destination(c.destination())` at the CNP
29081 // per-edge L4 port emit site) reads the same byte-string the
29082 // author declared.
29083 for para in ["catalog", "payment", "orders", "inventory-v3"] {
29084 let c = WitContract {
29085 de: "cart".into(),
29086 para: para.into(),
29087 wit: "wasi:http/proxy".into(),
29088 endpoint: Some("/lookup".into()),
29089 subject: None,
29090 slot: None,
29091 };
29092 assert_eq!(
29093 c.destination(),
29094 para,
29095 "WitContract::destination must return :contratos :para \
29096 verbatim (got {:?}, expected {para:?})",
29097 c.destination(),
29098 );
29099 assert_eq!(
29100 c.destination(),
29101 c.para.as_str(),
29102 "WitContract::destination must byte-equal the .para \
29103 field access",
29104 );
29105 }
29106 }
29107
29108 #[test]
29109 fn wit_contract_destination_borrows_from_para_storage() {
29110 // The borrow-not-copy pin: [`WitContract::destination`] must
29111 // return a `&str` slice that borrows from the typed slot's own
29112 // [`String`] storage — same-address invariant with
29113 // `c.para.as_str()`. Peer of the sibling
29114 // `destination_borrows_from_entrada_para_storage` on the
29115 // per-`:entrada` axis.
29116 let c = WitContract {
29117 de: "cart".into(),
29118 para: "catalog".into(),
29119 wit: "wasi:http/proxy".into(),
29120 endpoint: Some("/lookup".into()),
29121 subject: None,
29122 slot: None,
29123 };
29124 let dest = c.destination();
29125 let para_slice = c.para.as_str();
29126 assert_eq!(
29127 dest.as_ptr(),
29128 para_slice.as_ptr(),
29129 "WitContract::destination must borrow from the .para \
29130 String's backing storage — a fresh allocation here means \
29131 the accessor no longer names the substrate-primitive typed \
29132 dispatch and every downstream consumer would silently \
29133 carry a detached copy",
29134 );
29135 assert_eq!(
29136 dest.len(),
29137 para_slice.len(),
29138 "WitContract::destination and .para.as_str() must byte-equal \
29139 in length as well as in address",
29140 );
29141 }
29142
29143 #[test]
29144 fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
29145 // The canonical per-`:contratos` WIT-world-reference scalar pin:
29146 // [`WitContract::world_ref`] must return the `:contratos :wit`
29147 // field byte-for-byte, borrowed from the typed slot's own
29148 // [`String`] storage. Sibling of the peer per-`:contratos`
29149 // [`WitContract::source`] / [`WitContract::destination`]
29150 // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
29151 // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
29152 // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
29153 // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
29154 // "the substrate-primitive accessor must byte-equal the raw
29155 // field access verbatim across every author-declared value"
29156 // discipline extended to the per-`:contratos` WIT-world arm.
29157 // Pins against a future silent detour that re-canonicalized the
29158 // WIT world reference (an accidental `.to_lowercase()` pass that
29159 // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
29160 // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
29161 // gate is already lowercase-prefixed so any re-normalization is
29162 // redundant + a drift surface between the validator and the
29163 // accessor), an M4-promotion-shape rewrite that formatted a
29164 // typed WIT-world enum through [`Display`] and silently drifted
29165 // the printer output from the source `caixa.lisp`, or a per-
29166 // cluster WIT-alias rewrite that didn't land on the peer field-
29167 // access sites. Five values sweep the shape-dispatch accept-set
29168 // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
29169 // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
29170 // `wasi:keyvalue/`).
29171 for (wit, endpoint, subject, slot) in [
29172 ("wasi:http/proxy", Some("/lookup"), None, None),
29173 ("http:proxy", Some("/health"), None, None),
29174 ("nats:pub-sub", None, Some("orders.paid"), None),
29175 ("kafka:events", None, Some("checkout-events"), None),
29176 ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
29177 ] {
29178 let c = WitContract {
29179 de: "cart".into(),
29180 para: "downstream".into(),
29181 wit: wit.into(),
29182 endpoint: endpoint.map(str::to_string),
29183 subject: subject.map(str::to_string),
29184 slot: slot.map(str::to_string),
29185 };
29186 assert_eq!(
29187 c.world_ref(),
29188 wit,
29189 "WitContract::world_ref must return :contratos :wit \
29190 verbatim (got {:?}, expected {wit:?})",
29191 c.world_ref(),
29192 );
29193 assert_eq!(
29194 c.world_ref(),
29195 c.wit.as_str(),
29196 "WitContract::world_ref must byte-equal the .wit field \
29197 access",
29198 );
29199 }
29200 }
29201
29202 #[test]
29203 fn wit_contract_world_ref_borrows_from_wit_storage() {
29204 // The borrow-not-copy pin: [`WitContract::world_ref`] must
29205 // return a `&str` slice that borrows from the typed slot's own
29206 // [`String`] storage — same-address invariant with
29207 // `c.wit.as_str()`. Pins against a future silent detour that
29208 // allocated a fresh `String` (`self.wit.clone()` in the body
29209 // would type-check but silently drop the borrow, and every
29210 // downstream consumer that assumed the returned slice outlives
29211 // `&self` would break on a stale-reference use-after-free — the
29212 // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
29213 // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
29214 // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
29215 // / [`is_pubsub`][WitContract::is_pubsub] /
29216 // [`is_store`][WitContract::is_store] methods route through —
29217 // each borrow from the WitContract's own storage and each would
29218 // silently misbehave if this accessor produced a detached copy).
29219 // Peer of the sibling per-`:contratos` [`WitContract::source`] /
29220 // [`WitContract::destination`] and per-`:entrada`
29221 // [`Entrada::destination`] / [`Entrada::hostname`] and
29222 // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
29223 // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
29224 let c = WitContract {
29225 de: "cart".into(),
29226 para: "catalog".into(),
29227 wit: "wasi:http/proxy".into(),
29228 endpoint: Some("/lookup".into()),
29229 subject: None,
29230 slot: None,
29231 };
29232 let world = c.world_ref();
29233 let wit_slice = c.wit.as_str();
29234 assert_eq!(
29235 world.as_ptr(),
29236 wit_slice.as_ptr(),
29237 "WitContract::world_ref must borrow from the .wit String's \
29238 backing storage — a fresh allocation here means the \
29239 accessor no longer names the substrate-primitive typed \
29240 dispatch and every downstream consumer would silently carry \
29241 a detached copy",
29242 );
29243 assert_eq!(
29244 world.len(),
29245 wit_slice.len(),
29246 "WitContract::world_ref and .wit.as_str() must byte-equal in \
29247 length as well as in address",
29248 );
29249 }
29250
29251 #[test]
29252 fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
29253 // Sibling-triple invariant pin composing all three per-`:contratos`
29254 // substrate-primitive typed dispatches — [`WitContract::source`]
29255 // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
29256 // [`WitContract::world_ref`] — at the joint
29257 // `(source(), destination(), world_ref())` call shape every
29258 // renderer that fans on per-edge caller-callee-shape identity
29259 // keys off. The invariant, evaluated per-contract:
29260 //
29261 // (c.source(), c.destination(), c.world_ref())
29262 // == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
29263 //
29264 // Closes the last unlifted per-`:contratos` scalar axis — every
29265 // downstream consumer that reads the triple now routes through
29266 // exactly three typed dispatches on the substrate primitive,
29267 // not two typed + one open-coded field access. A future refactor
29268 // that silently split any one accessor's projection (an
29269 // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
29270 // canonicalization that didn't reach the peer `source`/
29271 // `destination` arms, an accidental `source()` per-cluster
29272 // caller-alias rewrite that didn't land on the `world_ref` peer)
29273 // surfaces at caixa-core build time. Peer of the sibling per-
29274 // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
29275 // per-`:entrada` `(hostname(), destination())` (6db982c /
29276 // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
29277 // axes, extended to the per-`:contratos` triple.
29278 for (de, para, wit, endpoint, subject, slot) in [
29279 (
29280 "cart",
29281 "catalog",
29282 "wasi:http/proxy",
29283 Some("/lookup"),
29284 None,
29285 None,
29286 ),
29287 (
29288 "checkout",
29289 "orders",
29290 "nats:pub-sub",
29291 None,
29292 Some("orders.paid"),
29293 None,
29294 ),
29295 (
29296 "cart",
29297 "kv",
29298 "wasi:keyvalue/store",
29299 None,
29300 None,
29301 Some("carts/{cart_id}"),
29302 ),
29303 (
29304 "orders-v2",
29305 "inventory-v3",
29306 "http:proxy",
29307 Some("/reserve"),
29308 None,
29309 None,
29310 ),
29311 ] {
29312 let c = WitContract {
29313 de: de.into(),
29314 para: para.into(),
29315 wit: wit.into(),
29316 endpoint: endpoint.map(str::to_string),
29317 subject: subject.map(str::to_string),
29318 slot: slot.map(str::to_string),
29319 };
29320 assert_eq!(
29321 (c.source(), c.destination(), c.world_ref()),
29322 (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
29323 "(WitContract::source, ::destination, ::world_ref) must \
29324 project (.de, .para, .wit) verbatim across every author-\
29325 declared triple (got ({:?}, {:?}, {:?}), expected \
29326 ({de:?}, {para:?}, {wit:?}))",
29327 c.source(),
29328 c.destination(),
29329 c.world_ref(),
29330 );
29331 }
29332 }
29333
29334 #[test]
29335 fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
29336 // The canonical per-`:contratos` owned-form caller-callee-pair
29337 // pin: [`WitContract::edge_pair`] must return the
29338 // `(source(), destination())` tuple in owned form byte-for-byte,
29339 // projected through the lifted [`WitContract::source`] /
29340 // [`WitContract::destination`] scalar accessors. Pins the
29341 // composite-projection invariant on the per-`:contratos`
29342 // mesh-slot atom — every author-declared `(de, para)` pair must
29343 // round-trip verbatim through the substrate primitive's typed
29344 // dispatch, so the nine [`AplicacaoError`] diagnostic-
29345 // construction sites the accessor now feeds
29346 // ([`AplicacaoError::EmptyWit`],
29347 // [`AplicacaoError::ContratoEndpointEmpty`],
29348 // [`AplicacaoError::ContratoEndpointNotAbsolute`],
29349 // [`AplicacaoError::ContratoEndpointInvalid`],
29350 // [`AplicacaoError::ContratoSubjectEmpty`],
29351 // [`AplicacaoError::ContratoSubjectInvalid`],
29352 // [`AplicacaoError::ContratoSlotEmpty`],
29353 // [`AplicacaoError::ContratoSlotInvalid`],
29354 // [`AplicacaoError::ContratoDuplicate`]) all read the same
29355 // `(de, para)` label pair every author sees at the source
29356 // `caixa.lisp`. Pins against a future silent detour that swapped
29357 // the `.0` / `.1` arms (an accidental `(destination(),
29358 // source())` re-order in the body would silently invert every
29359 // downstream diagnostic's `de:` / `para:` label pair, silently
29360 // reversing the direction of every operator-facing typed error
29361 // arrow), a fresh-allocation shape drift (an accidental
29362 // `.to_string()` on one arm but not the other would leave the
29363 // owned/borrowed pair mismatched vs. the sibling `source()` /
29364 // `destination()` returns), or an M4 per-cluster caller/callee-
29365 // alias rewrite that landed on `source()` without reaching
29366 // `destination()` (or vice versa). Peer of the sibling per-
29367 // `:contratos` `(source, destination, world_ref)` triple
29368 // pin above on the mesh-slot-atom scalar-value axes, extended
29369 // to the owned-form pair-projection axis.
29370 for (de, para, wit, endpoint, subject, slot) in [
29371 (
29372 "cart",
29373 "catalog",
29374 "wasi:http/proxy",
29375 Some("/lookup"),
29376 None,
29377 None,
29378 ),
29379 (
29380 "checkout",
29381 "orders",
29382 "nats:pub-sub",
29383 None,
29384 Some("orders.paid"),
29385 None,
29386 ),
29387 (
29388 "cart",
29389 "kv",
29390 "wasi:keyvalue/store",
29391 None,
29392 None,
29393 Some("carts/{cart_id}"),
29394 ),
29395 (
29396 "orders-v2",
29397 "inventory-v3",
29398 "http:proxy",
29399 Some("/reserve"),
29400 None,
29401 None,
29402 ),
29403 ] {
29404 let c = WitContract {
29405 de: de.into(),
29406 para: para.into(),
29407 wit: wit.into(),
29408 endpoint: endpoint.map(str::to_string),
29409 subject: subject.map(str::to_string),
29410 slot: slot.map(str::to_string),
29411 };
29412 assert_eq!(
29413 c.edge_pair(),
29414 (de.to_string(), para.to_string()),
29415 "WitContract::edge_pair must return (:contratos :de, \
29416 :contratos :para) as an owned tuple verbatim (got {:?}, \
29417 expected ({de:?}, {para:?}))",
29418 c.edge_pair(),
29419 );
29420 }
29421 }
29422
29423 #[test]
29424 fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
29425 // The composition pin: [`WitContract::edge_pair`] must return
29426 // exactly `(source().to_string(), destination().to_string())` —
29427 // the owned form of the sibling accessor pair — so any future
29428 // refactor that silently re-authored the caller-arm / callee-arm
29429 // projection to bypass the lifted scalar accessors (an accidental
29430 // `(self.de.clone(), self.para.clone())` regression back to the
29431 // raw field-access shape, an M4-typed-caller-enum `Display`
29432 // re-canonicalization on `source()` that didn't reach
29433 // `edge_pair()`, a per-cluster alias rewrite the operator lands
29434 // on `destination()` without reaching this composite projection)
29435 // trips at caixa-core build time. Pins the "typed dispatch
29436 // composes with typed dispatch, not with raw field access"
29437 // discipline every downstream diagnostic-construction site now
29438 // routes through — a `de:` / `para:` label pair whose
29439 // projection silently drifted off the substrate primitive's
29440 // scalar accessors would silently split the diagnostic's self-
29441 // locating signal from the source `caixa.lisp` author's view.
29442 // Peer of the sibling per-`:politicas` `is_empty` /
29443 // `validate_politicas` accessor-routing-pin family on the M3
29444 // mesh-slot family (18575, 18739, 18918, 19140, 19371).
29445 let c = WitContract {
29446 de: "cart".into(),
29447 para: "catalog".into(),
29448 wit: "wasi:http/proxy".into(),
29449 endpoint: Some("/lookup".into()),
29450 subject: None,
29451 slot: None,
29452 };
29453 assert_eq!(
29454 c.edge_pair(),
29455 (c.source().to_string(), c.destination().to_string()),
29456 "WitContract::edge_pair must compose exactly \
29457 (source().to_string(), destination().to_string()) — a \
29458 bypass of either sibling accessor here would silently \
29459 decouple the composite-projection axis from the \
29460 substrate-primitive scalar accessors every downstream \
29461 consumer routes through",
29462 );
29463 }
29464
29465 #[test]
29466 fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
29467 {
29468 // The canonical per-`:contratos` owned-form
29469 // caller-callee-world-ref-triple pin:
29470 // [`WitContract::edge_triple`] must return the
29471 // `(source(), destination(), world_ref())` tuple in owned form
29472 // byte-for-byte, projected through the lifted
29473 // [`WitContract::source`] / [`WitContract::destination`] /
29474 // [`WitContract::world_ref`] scalar accessors. Pins the
29475 // composite-projection invariant on the per-`:contratos`
29476 // mesh-slot atom — every author-declared `(de, para, wit)`
29477 // triple must round-trip verbatim through the substrate
29478 // primitive's typed dispatch, so the nine
29479 // [`AplicacaoError`] diagnostic-construction sites the
29480 // accessor now feeds (the [`WitTarget`]-dispatch's eight
29481 // wrong-target / missing-target / invalid-wit / capability-
29482 // with-payload arms in [`WitContract::target`], plus the
29483 // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
29484 // diagnostic constructor in [`AplicacaoSpec::validate`]) all
29485 // read the same `(de, para, wit)` triple every author sees at
29486 // the source `caixa.lisp`. Pins against a future silent
29487 // detour that swapped any two arms (an accidental `(destination(),
29488 // source(), world_ref())` re-order in the body would silently
29489 // invert every downstream diagnostic's `de:` / `para:` label
29490 // pair, silently reversing the direction of every operator-
29491 // facing typed error arrow), a fresh-allocation shape drift
29492 // (an accidental `.to_string()` skipped on one arm would leave
29493 // the owned/borrowed triple mismatched vs. the sibling
29494 // `source()` / `destination()` / `world_ref()` returns), or an
29495 // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
29496 // canonicalization pass that landed on one accessor without
29497 // reaching the peers. Peer of the sibling per-`:contratos`
29498 // caller-callee-pair
29499 // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
29500 // pin on the mesh-slot-atom composite-projection axis,
29501 // extended to the triple-projection axis.
29502 for (de, para, wit, endpoint, subject, slot) in [
29503 (
29504 "cart",
29505 "catalog",
29506 "wasi:http/proxy",
29507 Some("/lookup"),
29508 None,
29509 None,
29510 ),
29511 (
29512 "checkout",
29513 "orders",
29514 "nats:pub-sub",
29515 None,
29516 Some("orders.paid"),
29517 None,
29518 ),
29519 (
29520 "cart",
29521 "kv",
29522 "wasi:keyvalue/store",
29523 None,
29524 None,
29525 Some("carts/{cart_id}"),
29526 ),
29527 (
29528 "orders-v2",
29529 "inventory-v3",
29530 "http:proxy",
29531 Some("/reserve"),
29532 None,
29533 None,
29534 ),
29535 ] {
29536 let c = WitContract {
29537 de: de.into(),
29538 para: para.into(),
29539 wit: wit.into(),
29540 endpoint: endpoint.map(str::to_string),
29541 subject: subject.map(str::to_string),
29542 slot: slot.map(str::to_string),
29543 };
29544 assert_eq!(
29545 c.edge_triple(),
29546 (de.to_string(), para.to_string(), wit.to_string()),
29547 "WitContract::edge_triple must return (:contratos :de, \
29548 :contratos :para, :contratos :wit) as an owned triple \
29549 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
29550 c.edge_triple(),
29551 );
29552 }
29553 }
29554
29555 #[test]
29556 fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
29557 // The composition pin: [`WitContract::edge_triple`] must return
29558 // exactly `(source().to_string(), destination().to_string(),
29559 // world_ref().to_string())` — the owned form of the sibling
29560 // scalar-accessor triple — so any future refactor that silently
29561 // re-authored one arm's projection to bypass the lifted scalar
29562 // accessors (an accidental `(self.de.clone(), self.para.clone(),
29563 // self.wit.clone())` regression back to the raw field-access
29564 // shape the internal `edge` closure and the ContratoDuplicate
29565 // diagnostic both carried before this lift landed, an
29566 // M4-typed-caller-enum `Display` re-canonicalization on
29567 // `source()` that didn't reach `edge_triple()`, a per-cluster
29568 // alias rewrite the operator lands on `destination()` /
29569 // `world_ref()` without reaching this composite projection)
29570 // trips at caixa-core build time. Pins the "typed dispatch
29571 // composes with typed dispatch, not with raw field access"
29572 // discipline every downstream diagnostic-construction site now
29573 // routes through — a `de:` / `para:` / `wit:` triple whose
29574 // projection silently drifted off the substrate primitive's
29575 // scalar accessors would silently split the diagnostic's self-
29576 // locating signal from the source `caixa.lisp` author's view.
29577 // Peer of the sibling per-`:contratos` edge_pair composition-
29578 // pin above on the mesh-slot-atom composite-projection axis.
29579 let c = WitContract {
29580 de: "cart".into(),
29581 para: "catalog".into(),
29582 wit: "wasi:http/proxy".into(),
29583 endpoint: Some("/lookup".into()),
29584 subject: None,
29585 slot: None,
29586 };
29587 assert_eq!(
29588 c.edge_triple(),
29589 (
29590 c.source().to_string(),
29591 c.destination().to_string(),
29592 c.world_ref().to_string(),
29593 ),
29594 "WitContract::edge_triple must compose exactly \
29595 (source().to_string(), destination().to_string(), \
29596 world_ref().to_string()) — a bypass of any sibling accessor \
29597 here would silently decouple the composite-projection axis \
29598 from the substrate-primitive scalar accessors every \
29599 downstream consumer routes through",
29600 );
29601 }
29602
29603 #[test]
29604 fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
29605 // The canonical semantics-pin: [`WitContract::edge_triple`] must
29606 // project the full `(de, para, wit)` identity of a `:contratos`
29607 // edge — the sub-triple every triple-carrying
29608 // [`AplicacaoError::Contrato*`] diagnostic weaves into its
29609 // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
29610 // missing-target, capability-with-payload, invalid-wit, and the
29611 // duplicate-gate). Rejects a drift in shape (an accidental
29612 // silent detour that returned a `(de, para)` pair or added an
29613 // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
29614 // would trip here because the return type would no longer
29615 // pattern-match the eight `let (de, para, wit) = edge();`
29616 // destructures the [`WitContract::target`] dispatch feeds off
29617 // + the paired duplicate-gate `let (de, para, wit) =
29618 // c.edge_triple();` destructure in
29619 // [`AplicacaoSpec::validate`]). Peer of the sibling per-
29620 // `:contratos` caller-callee-pair pin above extended to the
29621 // triple projection surface: closes the "one composite
29622 // accessor per typed diagnostic-construction sub-tuple"
29623 // discipline on the per-`:contratos` mesh-slot-atom axis.
29624 let c = WitContract {
29625 de: "checkout".into(),
29626 para: "orders".into(),
29627 wit: "nats:pub-sub".into(),
29628 endpoint: None,
29629 subject: Some("orders.paid".into()),
29630 slot: None,
29631 };
29632 let (de, para, wit) = c.edge_triple();
29633 assert_eq!(de, "checkout");
29634 assert_eq!(para, "orders");
29635 assert_eq!(wit, "nats:pub-sub");
29636 }
29637
29638 #[test]
29639 fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
29640 {
29641 // The composition pin: [`WitContract::identity`] must return
29642 // exactly `(source(), destination(), world_ref(), endpoint(),
29643 // subject(), slot())` — the borrowed form of the six-scalar-
29644 // accessor identity axis. Any future refactor that silently
29645 // re-authored one arm's projection to bypass a scalar accessor
29646 // (a `self.de.as_str()` regression back to raw field access on
29647 // any of the three required arms, a `self.endpoint.as_deref()`
29648 // regression on any of the three optional arms, an M4 per-
29649 // cluster caller/callee-alias rewrite the operator lands on
29650 // `source()` / `destination()` without reaching this composite
29651 // projection) trips at caixa-core build time. Sweeps four
29652 // permutations of the WIT-shape × payload lattice — HTTP with
29653 // endpoint, pub-sub with subject, store with slot, payload-less
29654 // capability — so every payload arm is exercised. Peer of the
29655 // sibling per-`:contratos`
29656 // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
29657 // composition pin on the mesh-slot-atom composite-projection
29658 // axis; extends the discipline from the (de, para, wit) prefix
29659 // onto the full-identity axis carrying the three payload arms.
29660 for (de, para, wit, endpoint, subject, slot) in [
29661 (
29662 "cart",
29663 "catalog",
29664 "wasi:http/proxy",
29665 Some("/lookup"),
29666 None,
29667 None,
29668 ),
29669 (
29670 "checkout",
29671 "orders",
29672 "nats:pub-sub",
29673 None,
29674 Some("orders.paid"),
29675 None,
29676 ),
29677 (
29678 "cart",
29679 "kv",
29680 "wasi:keyvalue/store",
29681 None,
29682 None,
29683 Some("carts/{cart_id}"),
29684 ),
29685 ("audit", "sink", "wasi:logging", None, None, None),
29686 ] {
29687 let c = WitContract {
29688 de: de.into(),
29689 para: para.into(),
29690 wit: wit.into(),
29691 endpoint: endpoint.map(str::to_owned),
29692 subject: subject.map(str::to_owned),
29693 slot: slot.map(str::to_owned),
29694 };
29695 assert_eq!(
29696 c.identity(),
29697 (
29698 c.source(),
29699 c.destination(),
29700 c.world_ref(),
29701 c.endpoint(),
29702 c.subject(),
29703 c.slot(),
29704 ),
29705 "WitContract::identity must compose exactly \
29706 (source(), destination(), world_ref(), endpoint(), \
29707 subject(), slot()) — a bypass of any sibling accessor \
29708 here would silently decouple the identity-projection \
29709 axis from the substrate-primitive scalar accessors \
29710 every dedup-key consumer routes through",
29711 );
29712 }
29713 }
29714
29715 #[test]
29716 fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
29717 // The canonical semantics-pin: [`WitContract::identity`] must
29718 // project the six-axis (de, para, wit, endpoint, subject, slot)
29719 // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
29720 // gate keys off — two `WitContract`s that agree on all six axes
29721 // are the same typed edge declared twice, the graph-edge
29722 // analogue of duplicate `:membros` / `:placement :clusters` /
29723 // `:entrada :paths` entries. Rejects a shape drift (an
29724 // accidental silent detour that returned a prefix tuple or
29725 // added an extra field) by pattern-matching the six-arm shape.
29726 // Peer of the sibling per-`:contratos`
29727 // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
29728 // pin extended from the (de, para, wit) prefix onto the full
29729 // six-axis identity that the dedup key rides.
29730 let c = WitContract {
29731 de: "cart".into(),
29732 para: "catalog".into(),
29733 wit: "wasi:http/proxy".into(),
29734 endpoint: Some("/products/:id".into()),
29735 subject: None,
29736 slot: None,
29737 };
29738 let (de, para, wit, endpoint, subject, slot) = c.identity();
29739 assert_eq!(de, "cart");
29740 assert_eq!(para, "catalog");
29741 assert_eq!(wit, "wasi:http/proxy");
29742 assert_eq!(endpoint, Some("/products/:id"));
29743 assert_eq!(subject, None);
29744 assert_eq!(slot, None);
29745
29746 // Two byte-identical contracts must produce equal identities —
29747 // the dedup key's foundational invariant.
29748 let c2 = c.clone();
29749 assert_eq!(c.identity(), c2.identity());
29750
29751 // Any change on any of the six axes must break the identity —
29752 // sweeps by mutating one axis at a time.
29753 let mut mutated = c.clone();
29754 mutated.de = "search".into();
29755 assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
29756 let mut mutated = c.clone();
29757 mutated.para = "warehouse".into();
29758 assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
29759 let mut mutated = c.clone();
29760 mutated.wit = "http:legacy".into();
29761 assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
29762 let mut mutated = c.clone();
29763 mutated.endpoint = Some("/search".into());
29764 assert_ne!(
29765 c.identity(),
29766 mutated.identity(),
29767 "endpoint axis must partition"
29768 );
29769 let mut mutated = c.clone();
29770 mutated.subject = Some("orders.paid".into());
29771 assert_ne!(
29772 c.identity(),
29773 mutated.identity(),
29774 "subject axis must partition"
29775 );
29776 let mut mutated = c;
29777 mutated.slot = Some("carts/{id}".into());
29778 assert_ne!(mutated.identity().5, None, "slot axis must partition");
29779 }
29780
29781 #[test]
29782 fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
29783 // The canonical per-`:contratos` structural-self-edge pin:
29784 // [`WitContract::is_self_loop`] must return `true` when the
29785 // `:de` and `:para` fields agree byte-for-byte, across every
29786 // WIT-shape variant the per-edge shape family carries. Pins
29787 // the shape-agnostic identity-space partition the
29788 // [`AplicacaoSpec::validate`] self-edge gate at
29789 // caixa-core/src/aplicacao.rs:5559 fires against — all four
29790 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
29791 // under the same one predicate. Four permutations sweep the
29792 // accept-set: HTTP with endpoint, pub-sub with subject, KV
29793 // store with slot, and payload-less capability.
29794 for (nome, wit, endpoint, subject, slot) in [
29795 ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
29796 ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
29797 (
29798 "kv",
29799 "wasi:keyvalue/store",
29800 None,
29801 None,
29802 Some("carts/{cart_id}"),
29803 ),
29804 ("audit", "wasi:logging", None, None, None),
29805 ] {
29806 let c = WitContract {
29807 de: nome.into(),
29808 para: nome.into(),
29809 wit: wit.into(),
29810 endpoint: endpoint.map(str::to_string),
29811 subject: subject.map(str::to_string),
29812 slot: slot.map(str::to_string),
29813 };
29814 assert!(
29815 c.is_self_loop(),
29816 "WitContract::is_self_loop must return true when \
29817 :contratos :de == :contratos :para (got false on \
29818 {nome:?} under {wit:?})",
29819 );
29820 }
29821 }
29822
29823 #[test]
29824 fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
29825 // The complement pin: [`WitContract::is_self_loop`] must return
29826 // `false` on every well-shaped inter-Servico contract (the
29827 // author-intended `:contratos` shape MESH-COMPOSITION §III.1
29828 // names — "Servico A calls Servico B" between two distinct
29829 // graph nodes). Pins against a future silent detour that
29830 // inverted the predicate (an accidental `!= ` swap for `==`
29831 // would silently reject every legitimate inter-Servico edge
29832 // and admit every self-edge — the exact inversion of the
29833 // author-intended shape). Four permutations sweep the same
29834 // WIT-shape accept-set the sibling positive-arm test carries.
29835 for (de, para, wit, endpoint, subject, slot) in [
29836 (
29837 "cart",
29838 "catalog",
29839 "wasi:http/proxy",
29840 Some("/lookup"),
29841 None,
29842 None,
29843 ),
29844 (
29845 "checkout",
29846 "orders",
29847 "nats:pub-sub",
29848 None,
29849 Some("orders.paid"),
29850 None,
29851 ),
29852 (
29853 "cart",
29854 "kv",
29855 "wasi:keyvalue/store",
29856 None,
29857 None,
29858 Some("carts/{cart_id}"),
29859 ),
29860 ("audit", "sink", "wasi:logging", None, None, None),
29861 ] {
29862 let c = WitContract {
29863 de: de.into(),
29864 para: para.into(),
29865 wit: wit.into(),
29866 endpoint: endpoint.map(str::to_string),
29867 subject: subject.map(str::to_string),
29868 slot: slot.map(str::to_string),
29869 };
29870 assert!(
29871 !c.is_self_loop(),
29872 "WitContract::is_self_loop must return false when \
29873 :contratos :de differs from :contratos :para (got true \
29874 on {de:?} → {para:?} under {wit:?})",
29875 );
29876 }
29877 }
29878
29879 #[test]
29880 fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
29881 // The composition pin: [`WitContract::is_self_loop`] must
29882 // resolve to exactly `self.source() == self.destination()` —
29883 // the equality probe of the sibling scalar-accessor pair — so
29884 // any future refactor that silently re-authored the predicate
29885 // to bypass the lifted scalar accessors (an accidental
29886 // `self.de == self.para` regression back to the raw field-
29887 // access shape, an M4-typed-caller-enum identity-comparison
29888 // rule that landed on `source()` without reaching
29889 // `destination()`, a per-cluster alias rewrite the operator
29890 // pins on `destination()` without reaching this predicate)
29891 // trips at caixa-core build time. Pins the "typed dispatch
29892 // composes with typed dispatch, not with raw field access"
29893 // discipline the sibling [`WitContract::edge_pair`] /
29894 // [`WitContract::edge_triple`] composite-projection accessors
29895 // already carry, extended onto the per-edge endpoint-equality
29896 // predicate axis. Positive and complement arms both fire.
29897 let self_edge = WitContract {
29898 de: "cart".into(),
29899 para: "cart".into(),
29900 wit: "wasi:http/proxy".into(),
29901 endpoint: Some("/lookup".into()),
29902 subject: None,
29903 slot: None,
29904 };
29905 assert_eq!(
29906 self_edge.is_self_loop(),
29907 self_edge.source() == self_edge.destination(),
29908 "WitContract::is_self_loop must compose exactly \
29909 `source() == destination()` — a bypass of either sibling \
29910 accessor here would silently decouple the endpoint-\
29911 equality predicate from the substrate-primitive scalar \
29912 accessors every downstream consumer routes through",
29913 );
29914 let inter_edge = WitContract {
29915 de: "cart".into(),
29916 para: "catalog".into(),
29917 wit: "wasi:http/proxy".into(),
29918 endpoint: Some("/lookup".into()),
29919 subject: None,
29920 slot: None,
29921 };
29922 assert_eq!(
29923 inter_edge.is_self_loop(),
29924 inter_edge.source() == inter_edge.destination(),
29925 "WitContract::is_self_loop must compose exactly \
29926 `source() == destination()` on the complement arm too",
29927 );
29928 }
29929
29930 #[test]
29931 fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
29932 // The composition pin: [`WitContract::target`]'s invalid-wit
29933 // value-shape gate must feed the reason string through the
29934 // lifted [`WitContract::world_ref`] scalar accessor — the same
29935 // typed dispatch on the substrate primitive every peer
29936 // per-`:contratos` payload-carrier extraction in the same
29937 // method body already routes through
29938 // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
29939 // [`WitContract::subject`] on the pub-sub-arm target extraction,
29940 // [`WitContract::slot`] on the store-arm target extraction) and
29941 // every peer composite-projection accessor
29942 // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
29943 // [`WitContract::identity`]) already composes from. Any future
29944 // refactor that silently re-authored the gate to bypass the
29945 // lifted accessor (an accidental `&self.wit` regression back to
29946 // the raw field-access shape, an M4-typed-`WitWorld` `Display`
29947 // re-canonicalization on `world_ref()` that didn't reach this
29948 // gate, a per-CR lowercasing canonicalization pass the M4
29949 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
29950 // per-tenant that lands on `world_ref()` without reaching this
29951 // gate) would silently split the invalid-wit diagnostic reason
29952 // from the substrate-primitive projection every downstream
29953 // consumer routes through. Same "typed dispatch composes with
29954 // typed dispatch, not with raw field access" discipline the
29955 // sibling
29956 // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
29957 // pin already carries on the endpoint-equality predicate axis,
29958 // extended onto the invalid-wit value-shape gate axis inside
29959 // the same [`WitContract::target`] body. Closes the last
29960 // unlifted raw-field-access site inside `impl WitContract`.
29961 //
29962 // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
29963 // uppercase-typo footgun the pre-c4213a4 shape silently demoted
29964 // to a capability-only edge; the value-shape gate rejects it
29965 // through [`crate::render::is_wit_world_ref`] on the substrate
29966 // primitive's ASCII-lowercase-only accept-set, with a
29967 // parser-shaped reason string the test asserts round-trips
29968 // byte-for-byte between the direct-dispatch call (through the
29969 // predicate on the accessor's projection) and the
29970 // [`WitContract::target`] gate's produced reason field.
29971 let c = WitContract {
29972 de: "cart".into(),
29973 para: "catalog".into(),
29974 wit: "WASI:HTTP/proxy".into(),
29975 endpoint: Some("/lookup".into()),
29976 subject: None,
29977 slot: None,
29978 };
29979 let err = c.target().unwrap_err();
29980 let AplicacaoError::ContratoWitInvalid {
29981 ref de,
29982 ref para,
29983 ref wit,
29984 ref reason,
29985 } = err
29986 else {
29987 panic!("expected ContratoWitInvalid, got {err:?}");
29988 };
29989 assert_eq!(de, "cart");
29990 assert_eq!(para, "catalog");
29991 assert_eq!(wit, "WASI:HTTP/proxy");
29992 let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
29993 assert_eq!(
29994 *reason, expected_reason,
29995 "WitContract::target's invalid-wit value-shape gate reason \
29996 must compose exactly is_wit_world_ref(self.world_ref()) — \
29997 a bypass here (e.g. a raw `&self.wit` field-access \
29998 regression, or a divergent predicate on a different \
29999 projection) would silently decouple the invalid-wit \
30000 diagnostic's reason field from the substrate-primitive \
30001 scalar accessor every peer per-`:contratos` extraction in \
30002 the same method body already routes through",
30003 );
30004 }
30005
30006 #[test]
30007 fn wit_contract_is_self_loop_predicate_is_const_fn() {
30008 // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
30009 // caller-callee identity-space predicate's `const`-eval-surface
30010 // posture. The wrapper below dispatches through
30011 // [`WitContract::is_self_loop`] and is well-formed only when the
30012 // callee is itself `pub const fn` — any future accidental
30013 // downgrade to non-`const` fails the wrapper at caixa-core build
30014 // time with E0015 (`cannot call non-const method`), strictly
30015 // stronger than a runtime `assert!` and strictly stronger than a
30016 // module-scope `const _: () = assert!(…)` pin (the type's
30017 // `String` / `Option<String>` carriers rule out `const`-context
30018 // value construction; the `const fn` wrapper is the load-bearing
30019 // shape that side-steps the destructor-in-const restriction on
30020 // the value axis while still pinning the `const`-fn posture on
30021 // the callee — mirror of the sibling
30022 // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
30023 // (279823b) and
30024 // [`wit_contract_identity_projection_accessor_is_const_fn`]
30025 // (1ab648c) pins' discipline verbatim on the peer scalar-
30026 // accessor and composite-projection surfaces). Closes the last
30027 // unlifted per-`:contratos` shape/identity predicate on the
30028 // const-eval surface — the peer WIT-shape-partition family
30029 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
30030 // [`WitContract::is_store`] / [`WitContract::is_capability`]
30031 // already carried the `pub const fn` posture on the peer
30032 // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
30033 // this pin extends the same posture onto the caller-callee
30034 // identity-space partition. Sweeps every WIT-shape arm on both
30035 // the equal-endpoints (self-edge) and distinct-endpoints
30036 // (inter-edge) arms of the identity-space partition, plus one
30037 // same-length distinct-byte pair to pin the mid-loop `!=` arm
30038 // past the leading length-mismatch shortcut.
30039 const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
30040 c.is_self_loop()
30041 }
30042 let mk = |de: &str, para: &str, wit: &str| WitContract {
30043 de: de.into(),
30044 para: para.into(),
30045 wit: wit.into(),
30046 endpoint: None,
30047 subject: None,
30048 slot: None,
30049 };
30050 for (nome, wit) in [
30051 ("cart", "wasi:http/proxy"),
30052 ("checkout", "nats:pub-sub"),
30053 ("kv", "wasi:keyvalue/store"),
30054 ("audit", "wasi:logging"),
30055 ] {
30056 let self_edge = mk(nome, nome, wit);
30057 assert!(
30058 is_self_loop_via_const_fn(&self_edge),
30059 "self-edge {nome:?} under {wit:?}"
30060 );
30061 assert_eq!(
30062 is_self_loop_via_const_fn(&self_edge),
30063 self_edge.is_self_loop()
30064 );
30065 }
30066 for (de, para, wit) in [
30067 ("cart", "catalog", "wasi:http/proxy"),
30068 ("checkout", "orders", "nats:pub-sub"),
30069 ("cart", "kv", "wasi:keyvalue/store"),
30070 ("audit", "sink", "wasi:logging"),
30071 ] {
30072 let inter_edge = mk(de, para, wit);
30073 assert!(
30074 !is_self_loop_via_const_fn(&inter_edge),
30075 "inter-edge {de:?}→{para:?} under {wit:?}",
30076 );
30077 assert_eq!(
30078 is_self_loop_via_const_fn(&inter_edge),
30079 inter_edge.is_self_loop()
30080 );
30081 }
30082 // Same-length distinct-byte pair — pins the mid-loop `!=` arm
30083 // past the leading `a.len() != b.len()` shortcut so the const-fn
30084 // wrapper exercises every arm of the byte-slice equality loop.
30085 let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
30086 assert!(
30087 !is_self_loop_via_const_fn(&same_len_pair),
30088 "same-length distinct-byte"
30089 );
30090 assert_eq!(
30091 is_self_loop_via_const_fn(&same_len_pair),
30092 same_len_pair.is_self_loop()
30093 );
30094 }
30095
30096 #[test]
30097 fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
30098 // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
30099 // pin: [`WitContract::endpoint`] must return the `:contratos
30100 // :endpoint` field byte-for-byte, borrowed from the typed slot's
30101 // own `Option<String>` storage. Peer of the sibling
30102 // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
30103 // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
30104 // mesh-slot `Option<String>` optional-scalar axes — same "the
30105 // substrate-primitive accessor must byte-equal the raw field
30106 // access verbatim across every author-declared value" discipline
30107 // extended to the per-`:contratos` HTTP-payload-carrier arm.
30108 // Pins against a future silent detour that re-canonicalized the
30109 // endpoint (an accidental percent-encoding pass that didn't
30110 // reach the peer field-access site at the dedup key, a per-CR
30111 // fully-qualified prefix rewrite the operator authors on one
30112 // consumer without the other, or an M4 typed-path-template
30113 // `Display` re-canonicalization that silently drifted the
30114 // printer output from the source `caixa.lisp`). Four values
30115 // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
30116 // gate upstream admits (short root-path, dashed, param-shaped,
30117 // deep-hierarchy).
30118 for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
30119 let c = WitContract {
30120 de: "cart".into(),
30121 para: "catalog".into(),
30122 wit: "wasi:http/proxy".into(),
30123 endpoint: Some(endpoint.into()),
30124 subject: None,
30125 slot: None,
30126 };
30127 assert_eq!(
30128 c.endpoint(),
30129 Some(endpoint),
30130 "WitContract::endpoint must return :contratos :endpoint \
30131 verbatim (got {:?}, expected Some({endpoint:?}))",
30132 c.endpoint(),
30133 );
30134 assert_eq!(
30135 c.endpoint(),
30136 c.endpoint.as_deref(),
30137 "WitContract::endpoint must byte-equal the .endpoint \
30138 field's `.as_deref()` projection",
30139 );
30140 }
30141 }
30142
30143 #[test]
30144 fn wit_contract_endpoint_none_when_field_is_none() {
30145 // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
30146 // payload-carrier accessor pin: when the typed slot is absent —
30147 // the canonical shape under a non-HTTP `:wit` world per the
30148 // [`WitContract::target`]-enforced shape ↔ target partition
30149 // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
30150 // carries `:slot`, [`WitTarget::Capability`] carries none) —
30151 // [`WitContract::endpoint`] must return `None`. Pins against a
30152 // future silent detour that projected the absent slot to a
30153 // `Some("")` empty-string default (the canonical `Option<String>`
30154 // → `String` collapse footgun the sibling M2
30155 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
30156 // emptiness predicates already guard on the peer M2 typed-slot
30157 // surfaces), a `Some("None")` stringified-None round-trip, or a
30158 // `Some` arm whose contents were derived from a sibling slot (an
30159 // accidental fallback to the `:subject` / `:slot` payload that
30160 // read the pub-sub / store payload into the endpoint axis).
30161 // Three contracts sweep the accept-set every non-HTTP `:wit`
30162 // world lands on — pub-sub NATS, key/value, and payload-less
30163 // capability.
30164 for (wit, subject, slot) in [
30165 ("nats:pub-sub", Some("orders.paid"), None),
30166 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
30167 ("wasi:cli/environment", None, None),
30168 ] {
30169 let c = WitContract {
30170 de: "cart".into(),
30171 para: "downstream".into(),
30172 wit: wit.into(),
30173 endpoint: None,
30174 subject: subject.map(str::to_string),
30175 slot: slot.map(str::to_string),
30176 };
30177 assert!(
30178 c.endpoint().is_none(),
30179 "WitContract::endpoint must return None when the typed \
30180 slot is absent under :wit {wit:?} (got {:?})",
30181 c.endpoint(),
30182 );
30183 assert_eq!(
30184 c.endpoint(),
30185 c.endpoint.as_deref(),
30186 "WitContract::endpoint must byte-equal the .endpoint \
30187 field's `.as_deref()` projection in the absent arm",
30188 );
30189 }
30190 }
30191
30192 #[test]
30193 fn wit_contract_endpoint_borrows_from_endpoint_storage() {
30194 // The borrow-not-copy pin: [`WitContract::endpoint`] must return
30195 // an `Option<&str>` whose `Some` arm borrows from the typed
30196 // slot's own [`String`] storage — same-address invariant with
30197 // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
30198 // detour that allocated a fresh `String`
30199 // (`self.endpoint.clone().map(...)` in the body would type-check
30200 // but silently drop the borrow, and every downstream consumer
30201 // that assumed the returned slice outlives `&self` would break
30202 // on a stale-reference use-after-free — the [`WitContract::target`]
30203 // Http-arm payload extraction rebinds the returned `Option<&str>`
30204 // through `.ok_or_else(...)` and threads the `&str` payload into
30205 // [`WitTarget::Http { endpoint: &'a str }`], the
30206 // [`AplicacaoSpec::validate`] duplicate-`:contratos`
30207 // [`ContratoIdentity`] dedup key threads the returned
30208 // `Option<&str>` into the six-tuple's HTTP arm — each borrow
30209 // from the WitContract's own storage and each would silently
30210 // misbehave if this accessor produced a detached copy). Peer of
30211 // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
30212 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
30213 // shaped optional-scalar axes — first extension of the
30214 // `Option<&str>` borrow-not-copy discipline onto the
30215 // per-`:contratos` HTTP-shaped payload-carrier axis.
30216 let c = WitContract {
30217 de: "cart".into(),
30218 para: "catalog".into(),
30219 wit: "wasi:http/proxy".into(),
30220 endpoint: Some("/lookup".into()),
30221 subject: None,
30222 slot: None,
30223 };
30224 let ep = c.endpoint().expect("Some arm");
30225 let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
30226 assert_eq!(
30227 ep.as_ptr(),
30228 storage_slice.as_ptr(),
30229 "WitContract::endpoint must borrow from the .endpoint \
30230 String's backing storage — a fresh allocation here means \
30231 the accessor no longer names the substrate-primitive typed \
30232 dispatch and every downstream consumer would silently \
30233 carry a detached copy",
30234 );
30235 assert_eq!(
30236 ep.len(),
30237 storage_slice.len(),
30238 "WitContract::endpoint and .endpoint.as_deref() must byte-\
30239 equal in length as well as in address",
30240 );
30241 }
30242
30243 #[test]
30244 fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
30245 // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
30246 // pin: [`WitContract::subject`] must return the `:contratos
30247 // :subject` field byte-for-byte, borrowed from the typed slot's
30248 // own `Option<String>` storage. Peer of the sibling per-`:contratos`
30249 // [`WitContract::endpoint`] (7020470) accessor pin on the M3
30250 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
30251 // optional-scalar axis — same "the substrate-primitive accessor
30252 // must byte-equal the raw field access verbatim across every
30253 // author-declared value" discipline extended to the pub-sub arm.
30254 // Pins against a future silent detour that re-canonicalized the
30255 // subject (an accidental `.to_lowercase()` normalization that
30256 // didn't reach the peer field-access site at the dedup key, a
30257 // per-CR fully-qualified prefix rewrite the operator authors on
30258 // one consumer without the other, or an M4 typed-subject-template
30259 // `Display` re-canonicalization that silently drifted the printer
30260 // output from the source `caixa.lisp`). Four values sweep the
30261 // NATS accept-set every pub-sub author-declared subject lands on
30262 // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
30263 for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
30264 let c = WitContract {
30265 de: "cart".into(),
30266 para: "notifier".into(),
30267 wit: "nats:pub-sub".into(),
30268 endpoint: None,
30269 subject: Some(subject.into()),
30270 slot: None,
30271 };
30272 assert_eq!(
30273 c.subject(),
30274 Some(subject),
30275 "WitContract::subject must return :contratos :subject \
30276 verbatim (got {:?}, expected Some({subject:?}))",
30277 c.subject(),
30278 );
30279 assert_eq!(
30280 c.subject(),
30281 c.subject.as_deref(),
30282 "WitContract::subject must byte-equal the .subject \
30283 field's `.as_deref()` projection",
30284 );
30285 }
30286 }
30287
30288 #[test]
30289 fn wit_contract_subject_none_when_field_is_none() {
30290 // The absent-`:subject` arm of the per-`:contratos` pub-sub-
30291 // shaped payload-carrier accessor pin: when the typed slot is
30292 // absent — the canonical shape under a non-pub-sub `:wit` world
30293 // per the [`WitContract::target`]-enforced shape ↔ target
30294 // partition ([`WitTarget::Http`] carries `:endpoint`,
30295 // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
30296 // carries none) — [`WitContract::subject`] must return `None`.
30297 // Pins against a future silent detour that projected the absent
30298 // slot to a `Some("")` empty-string default (the canonical
30299 // `Option<String>` → `String` collapse footgun the sibling M2
30300 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
30301 // emptiness predicates already guard on the peer M2 typed-slot
30302 // surfaces), a `Some("None")` stringified-None round-trip, or a
30303 // `Some` arm whose contents were derived from a sibling slot (an
30304 // accidental fallback to the `:endpoint` / `:slot` payload that
30305 // read the HTTP / store payload into the subject axis). Three
30306 // contracts sweep the accept-set every non-pub-sub `:wit` world
30307 // lands on — HTTP proxy, key/value store, and payload-less
30308 // capability.
30309 for (wit, endpoint, slot) in [
30310 ("wasi:http/proxy", Some("/lookup"), None),
30311 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
30312 ("wasi:cli/environment", None, None),
30313 ] {
30314 let c = WitContract {
30315 de: "cart".into(),
30316 para: "downstream".into(),
30317 wit: wit.into(),
30318 endpoint: endpoint.map(str::to_string),
30319 subject: None,
30320 slot: slot.map(str::to_string),
30321 };
30322 assert!(
30323 c.subject().is_none(),
30324 "WitContract::subject must return None when the typed \
30325 slot is absent under :wit {wit:?} (got {:?})",
30326 c.subject(),
30327 );
30328 assert_eq!(
30329 c.subject(),
30330 c.subject.as_deref(),
30331 "WitContract::subject must byte-equal the .subject \
30332 field's `.as_deref()` projection in the absent arm",
30333 );
30334 }
30335 }
30336
30337 #[test]
30338 fn wit_contract_subject_borrows_from_subject_storage() {
30339 // The borrow-not-copy pin: [`WitContract::subject`] must return
30340 // an `Option<&str>` whose `Some` arm borrows from the typed
30341 // slot's own [`String`] storage — same-address invariant with
30342 // `c.subject.as_deref().unwrap()`. Pins against a future silent
30343 // detour that allocated a fresh `String`
30344 // (`self.subject.clone().map(...)` in the body would type-check
30345 // but silently drop the borrow, and every downstream consumer
30346 // that assumed the returned slice outlives `&self` would break
30347 // on a stale-reference use-after-free — the [`WitContract::target`]
30348 // PubSub-arm payload extraction rebinds the returned
30349 // `Option<&str>` through `.ok_or_else(...)` and threads the
30350 // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
30351 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
30352 // [`ContratoIdentity`] dedup key threads the returned
30353 // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
30354 // from the WitContract's own storage and each would silently
30355 // misbehave if this accessor produced a detached copy). Peer of
30356 // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
30357 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
30358 // shaped optional-scalar axis — second extension of the
30359 // `Option<&str>` borrow-not-copy discipline onto the
30360 // per-`:contratos` payload-carrier family, this time on the
30361 // pub-sub arm.
30362 let c = WitContract {
30363 de: "cart".into(),
30364 para: "notifier".into(),
30365 wit: "nats:pub-sub".into(),
30366 endpoint: None,
30367 subject: Some("orders.paid".into()),
30368 slot: None,
30369 };
30370 let sub = c.subject().expect("Some arm");
30371 let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
30372 assert_eq!(
30373 sub.as_ptr(),
30374 storage_slice.as_ptr(),
30375 "WitContract::subject must borrow from the .subject \
30376 String's backing storage — a fresh allocation here means \
30377 the accessor no longer names the substrate-primitive typed \
30378 dispatch and every downstream consumer would silently \
30379 carry a detached copy",
30380 );
30381 assert_eq!(
30382 sub.len(),
30383 storage_slice.len(),
30384 "WitContract::subject and .subject.as_deref() must byte-\
30385 equal in length as well as in address",
30386 );
30387 }
30388
30389 #[test]
30390 fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
30391 // The canonical per-`:contratos` key/value-store-shaped
30392 // `:slot`-scalar pin: [`WitContract::slot`] must return the
30393 // `:contratos :slot` field byte-for-byte, borrowed from the
30394 // typed slot's own `Option<String>` storage. Peer of the
30395 // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
30396 // [`WitContract::subject`] (90de675) accessor pins on the M3
30397 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
30398 // optional-scalar axis — same "the substrate-primitive
30399 // accessor must byte-equal the raw field access verbatim
30400 // across every author-declared value" discipline extended to
30401 // the store arm. Pins against a future silent detour that
30402 // re-canonicalized the slot template (an accidental
30403 // `.to_lowercase()` bucket-prefix normalization that didn't
30404 // reach the peer field-access site at the dedup key, a per-CR
30405 // fully-qualified prefix rewrite the operator authors on one
30406 // consumer without the other, or an M4 typed-key-template
30407 // `Display` re-canonicalization that silently drifted the
30408 // printer output from the source `caixa.lisp`). Four values
30409 // sweep the wasi:keyvalue accept-set every store-shaped
30410 // author-declared slot lands on (flat bucket, single-param
30411 // template, multi-param template, nested-hierarchy template).
30412 for slot in [
30413 "sessions",
30414 "carts/{cart_id}",
30415 "orders/{tenant}/{order_id}",
30416 "cache/tenant-a/orders/{id}",
30417 ] {
30418 let c = WitContract {
30419 de: "cart".into(),
30420 para: "kv".into(),
30421 wit: "wasi:keyvalue/store".into(),
30422 endpoint: None,
30423 subject: None,
30424 slot: Some(slot.into()),
30425 };
30426 assert_eq!(
30427 c.slot(),
30428 Some(slot),
30429 "WitContract::slot must return :contratos :slot \
30430 verbatim (got {:?}, expected Some({slot:?}))",
30431 c.slot(),
30432 );
30433 assert_eq!(
30434 c.slot(),
30435 c.slot.as_deref(),
30436 "WitContract::slot must byte-equal the .slot field's \
30437 `.as_deref()` projection",
30438 );
30439 }
30440 }
30441
30442 #[test]
30443 fn wit_contract_slot_none_when_field_is_none() {
30444 // The absent-`:slot` arm of the per-`:contratos` store-shaped
30445 // payload-carrier accessor pin: when the typed slot is absent —
30446 // the canonical shape under a non-store `:wit` world per the
30447 // [`WitContract::target`]-enforced shape ↔ target partition
30448 // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
30449 // carries `:subject`, [`WitTarget::Capability`] carries none) —
30450 // [`WitContract::slot`] must return `None`. Pins against a
30451 // future silent detour that projected the absent slot to a
30452 // `Some("")` empty-string default (the canonical
30453 // `Option<String>` → `String` collapse footgun the sibling M2
30454 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
30455 // emptiness predicates already guard on the peer M2 typed-slot
30456 // surfaces), a `Some("None")` stringified-None round-trip, or
30457 // a `Some` arm whose contents were derived from a sibling
30458 // slot (an accidental fallback to the `:endpoint` / `:subject`
30459 // payload that read the HTTP / pub-sub payload into the store
30460 // axis). Three contracts sweep the accept-set every non-store
30461 // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
30462 // payload-less capability.
30463 for (wit, endpoint, subject) in [
30464 ("wasi:http/proxy", Some("/lookup"), None),
30465 ("nats:pub-sub", None, Some("orders.paid")),
30466 ("wasi:cli/environment", None, None),
30467 ] {
30468 let c = WitContract {
30469 de: "cart".into(),
30470 para: "downstream".into(),
30471 wit: wit.into(),
30472 endpoint: endpoint.map(str::to_string),
30473 subject: subject.map(str::to_string),
30474 slot: None,
30475 };
30476 assert!(
30477 c.slot().is_none(),
30478 "WitContract::slot must return None when the typed \
30479 slot is absent under :wit {wit:?} (got {:?})",
30480 c.slot(),
30481 );
30482 assert_eq!(
30483 c.slot(),
30484 c.slot.as_deref(),
30485 "WitContract::slot must byte-equal the .slot field's \
30486 `.as_deref()` projection in the absent arm",
30487 );
30488 }
30489 }
30490
30491 #[test]
30492 fn wit_contract_slot_borrows_from_slot_storage() {
30493 // The borrow-not-copy pin: [`WitContract::slot`] must return
30494 // an `Option<&str>` whose `Some` arm borrows from the typed
30495 // slot's own [`String`] storage — same-address invariant with
30496 // `c.slot.as_deref().unwrap()`. Pins against a future silent
30497 // detour that allocated a fresh `String`
30498 // (`self.slot.clone().map(...)` in the body would type-check
30499 // but silently drop the borrow, and every downstream consumer
30500 // that assumed the returned slice outlives `&self` would
30501 // break on a stale-reference use-after-free — the
30502 // [`WitContract::target`] Store-arm payload extraction rebinds
30503 // the returned `Option<&str>` through `.ok_or_else(...)` and
30504 // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
30505 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
30506 // [`ContratoIdentity`] dedup key threads the returned
30507 // `Option<&str>` into the six-tuple's store arm — each borrow
30508 // from the WitContract's own storage and each would silently
30509 // misbehave if this accessor produced a detached copy). Peer
30510 // of the sibling per-`:contratos` [`WitContract::endpoint`]
30511 // (7020470) / [`WitContract::subject`] (90de675)
30512 // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
30513 // shaped optional-scalar axis — third and final extension of
30514 // the `Option<&str>` borrow-not-copy discipline onto the
30515 // per-`:contratos` payload-carrier family, this time on the
30516 // store arm.
30517 let c = WitContract {
30518 de: "cart".into(),
30519 para: "kv".into(),
30520 wit: "wasi:keyvalue/store".into(),
30521 endpoint: None,
30522 subject: None,
30523 slot: Some("carts/{cart_id}".into()),
30524 };
30525 let slot = c.slot().expect("Some arm");
30526 let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
30527 assert_eq!(
30528 slot.as_ptr(),
30529 storage_slice.as_ptr(),
30530 "WitContract::slot must borrow from the .slot String's \
30531 backing storage — a fresh allocation here means the \
30532 accessor no longer names the substrate-primitive typed \
30533 dispatch and every downstream consumer would silently \
30534 carry a detached copy",
30535 );
30536 assert_eq!(
30537 slot.len(),
30538 storage_slice.len(),
30539 "WitContract::slot and .slot.as_deref() must byte-equal \
30540 in length as well as in address",
30541 );
30542 }
30543
30544 #[test]
30545 fn membro_nome_returns_caixa_byte_equal_across_permutations() {
30546 // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
30547 // [`Membro::nome`] must return the `:membros :caixa` field
30548 // byte-for-byte, borrowed from the typed slot's own [`String`]
30549 // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
30550 // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
30551 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
30552 // slot-atom scalar-value axes — same "the substrate-primitive
30553 // accessor must byte-equal the raw field access verbatim across
30554 // every author-declared value" discipline extended to the
30555 // per-`:membros` member-identity arm. Pins against a future
30556 // silent detour that re-normalized the member identity (an
30557 // accidental `.to_lowercase()` — every `:membros :caixa` is
30558 // validated as a DNS-1123 label upstream via
30559 // [`validate_membro_caixa`], so any re-normalization is
30560 // redundant + a drift surface between the validator and the
30561 // accessor), a namespace-prefix rewrite (an accidental
30562 // `format!("{namespace}/{caixa}")` per-CR fully-qualified
30563 // rewrite that didn't land on the peer axes), or a per-cluster
30564 // alias stamp the operator authors on one consumer without the
30565 // other. Four values sweep the accept-set the DNS-1123 gate
30566 // upstream admits (short single-word / dashed / v-suffixed
30567 // member names).
30568 for name in ["cart", "checkout", "catalog", "orders-v2"] {
30569 let m = Membro {
30570 caixa: name.into(),
30571 versao: "^0.1".into(),
30572 };
30573 assert_eq!(
30574 m.nome(),
30575 name,
30576 "Membro::nome must return :membros :caixa verbatim \
30577 (got {:?}, expected {name:?})",
30578 m.nome(),
30579 );
30580 assert_eq!(
30581 m.nome(),
30582 m.caixa.as_str(),
30583 "Membro::nome must byte-equal the .caixa field access",
30584 );
30585 }
30586 }
30587
30588 #[test]
30589 fn membro_nome_borrows_from_caixa_storage() {
30590 // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
30591 // slice that borrows from the typed slot's own [`String`]
30592 // storage — same-address invariant with `m.caixa.as_str()`. Pins
30593 // against a future silent detour that allocated a fresh `String`
30594 // (`self.caixa.clone()` in the body would type-check but
30595 // silently drop the borrow, and every downstream consumer that
30596 // assumed the returned slice outlives `&self` would break on a
30597 // stale-reference use-after-free — the `HashSet<&str>` collector
30598 // at [`AplicacaoSpec::validate`]'s `names` seed, the
30599 // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
30600 // [`AplicacaoSpec::detect_sync_cycles`], the
30601 // [`crate::render::insert_first_seen`] dedup key at
30602 // [`AplicacaoSpec::validate_membros`] — each borrow from the
30603 // Membro's own storage and each would silently misbehave if
30604 // this accessor produced a detached copy). Peer of the sibling
30605 // per-`:contratos` [`WitContract::source`] /
30606 // [`WitContract::destination`] and per-`:entrada`
30607 // [`Entrada::destination`] borrow-invariant pins on the mesh-
30608 // slot-atom scalar-value axes.
30609 let m = Membro {
30610 caixa: "checkout".into(),
30611 versao: "^0.1".into(),
30612 };
30613 let name = m.nome();
30614 let caixa_slice = m.caixa.as_str();
30615 assert_eq!(
30616 name.as_ptr(),
30617 caixa_slice.as_ptr(),
30618 "Membro::nome must borrow from the .caixa String's backing \
30619 storage — a fresh allocation here means the accessor no \
30620 longer names the substrate-primitive typed dispatch and \
30621 every downstream consumer would silently carry a detached \
30622 copy",
30623 );
30624 assert_eq!(
30625 name.len(),
30626 caixa_slice.len(),
30627 "Membro::nome and .caixa.as_str() must byte-equal in length \
30628 as well as in address",
30629 );
30630 }
30631
30632 #[test]
30633 fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
30634 // The canonical per-`:membros` member-`:versao`-scalar pin:
30635 // [`Membro::versao_requirement`] must return the
30636 // `:membros :versao` field byte-for-byte, borrowed from the typed
30637 // slot's own [`String`] storage. Sibling of the peer
30638 // `membro_nome_returns_caixa_byte_equal_across_permutations`
30639 // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
30640 // — same "the substrate-primitive accessor must byte-equal the
30641 // raw field access verbatim across every author-declared value"
30642 // discipline extended to the per-`:membros` member-`:versao`
30643 // requirement-string arm. Pins against a future silent detour
30644 // that re-canonicalized the requirement (an accidental
30645 // `.to_string()` via [`parse_requirement`] → [`Display`] round-
30646 // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
30647 // drifted the printer output away from the source `caixa.lisp`,
30648 // an accidental whitespace trim on `"^ 0.1"` that no consumer
30649 // ever produced from the field-access side, an accidental
30650 // per-cluster lacre-projected concrete-version rewrite that
30651 // didn't land on the peer field-access sites). Five values sweep
30652 // the accept-set the shared
30653 // [`crate::render::require_valid_versao_requirement`] gate
30654 // admits (caret / tilde / exact / wildcard / bare-major).
30655 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
30656 let m = Membro {
30657 caixa: "cart".into(),
30658 versao: req.into(),
30659 };
30660 assert_eq!(
30661 m.versao_requirement(),
30662 req,
30663 "Membro::versao_requirement must return :membros :versao \
30664 verbatim (got {:?}, expected {req:?})",
30665 m.versao_requirement(),
30666 );
30667 assert_eq!(
30668 m.versao_requirement(),
30669 m.versao.as_str(),
30670 "Membro::versao_requirement must byte-equal the .versao \
30671 field access",
30672 );
30673 }
30674 }
30675
30676 #[test]
30677 fn membro_versao_requirement_borrows_from_versao_storage() {
30678 // The borrow-not-copy pin: [`Membro::versao_requirement`] must
30679 // return a `&str` slice that borrows from the typed slot's own
30680 // [`String`] storage — same-address invariant with
30681 // `m.versao.as_str()`. Pins against a future silent detour that
30682 // allocated a fresh `String` (`self.versao.clone()` in the body
30683 // would type-check but silently drop the borrow, and every
30684 // downstream consumer that assumed the returned slice outlives
30685 // `&self` would break on a stale-reference use-after-free). Peer
30686 // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
30687 // per-`:contratos` [`WitContract::source`] /
30688 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
30689 // [`Entrada::destination`] (6db982c) borrow-invariant pins on
30690 // the mesh-slot-atom scalar-value axes.
30691 let m = Membro {
30692 caixa: "checkout".into(),
30693 versao: "^0.1".into(),
30694 };
30695 let req = m.versao_requirement();
30696 let versao_slice = m.versao.as_str();
30697 assert_eq!(
30698 req.as_ptr(),
30699 versao_slice.as_ptr(),
30700 "Membro::versao_requirement must borrow from the .versao \
30701 String's backing storage — a fresh allocation here means \
30702 the accessor no longer names the substrate-primitive typed \
30703 dispatch and every downstream consumer would silently carry \
30704 a detached copy",
30705 );
30706 assert_eq!(
30707 req.len(),
30708 versao_slice.len(),
30709 "Membro::versao_requirement and .versao.as_str() must byte-\
30710 equal in length as well as in address",
30711 );
30712 }
30713
30714 #[test]
30715 fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
30716 // Sibling-pair invariant pin composing both per-`:membros`
30717 // substrate-primitive typed dispatches — [`Membro::nome`]
30718 // (4a32abf) and [`Membro::versao_requirement`] — at the joint
30719 // `(nome(), versao_requirement())` call shape every renderer
30720 // that fans on per-member identity + version pin keys off. The
30721 // invariant, evaluated per-member:
30722 //
30723 // (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
30724 //
30725 // Closes the last unlifted per-`:membros` scalar axis — every
30726 // downstream consumer that reads the pair now routes through
30727 // exactly two typed dispatches on the substrate primitive, not
30728 // one typed + one open-coded field access. A future refactor
30729 // that silently split either accessor's projection (an
30730 // accidental `nome()` namespace-prefix rewrite that didn't
30731 // reach the peer, an accidental `versao_requirement()` lacre-
30732 // projected concrete-version rewrite that didn't land on the
30733 // `nome()` peer) surfaces at caixa-core build time. Peer of the
30734 // sibling per-`:entrada` `(hostname(), destination())` and
30735 // per-`:contratos` `(source(), destination())` pair invariants
30736 // on the mesh-slot-atom scalar-value axes.
30737 for (caixa, versao) in [
30738 ("cart", "^0.1"),
30739 ("checkout", "~0.1.2"),
30740 ("catalog", "0.1.0"),
30741 ("orders-v2", "*"),
30742 ] {
30743 let m = Membro {
30744 caixa: caixa.into(),
30745 versao: versao.into(),
30746 };
30747 assert_eq!(
30748 (m.nome(), m.versao_requirement()),
30749 (m.caixa.as_str(), m.versao.as_str()),
30750 "(Membro::nome, Membro::versao_requirement) must project \
30751 (.caixa, .versao) verbatim across every author-declared \
30752 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
30753 m.nome(),
30754 m.versao_requirement(),
30755 );
30756 }
30757 }
30758
30759 #[test]
30760 fn validate_membros_empty_gate_routes_through_nome_accessor() {
30761 // Composition pin: [`AplicacaoSpec::validate_membros`]'s
30762 // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
30763 // not the raw `.caixa` field access. Structurally: setting
30764 // ONLY the `.caixa` field to `""` on an otherwise-well-formed
30765 // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
30766 // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
30767 // (i.e. the empty string) — so the emptiness predicate the
30768 // refusal arm reaches under is the accessor-projected value,
30769 // not a peer field that would silently drift under a future
30770 // accessor-side rewrite.
30771 //
30772 // Pins against a future silent detour that (a) re-derived the
30773 // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
30774 // instead of `self.nome().is_empty()`, silently disagreeing with
30775 // every peer consumer (the `validate_membro_caixa(m.nome())`
30776 // per-slot helper — which now owns the emptiness arm outright —
30777 // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
30778 // below, and the emit-side per-`programs[]` entry-`name:` at
30779 // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
30780 // per-tenant alias arm the caller was unaware of, silently
30781 // rewriting an author-declared `:caixa "checkout"` to `""` —
30782 // the raw-field-access gate would fail-open while the
30783 // accessor-routed peer consumers would fail-closed, splitting
30784 // the diagnostic from the actual failure surface.
30785 //
30786 // Peer of the sibling
30787 // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
30788 // (c0110f1) composition pin — same "the shape-gate predicate
30789 // must route through the substrate-primitive typed dispatch"
30790 // discipline extended onto the per-`:membros` empty-`:caixa`
30791 // refusal-arm axis. Closes the last unlifted `.caixa` production-
30792 // code read site on `Membro` — after this converge every
30793 // caixa-core `.caixa` field access outside the accessor's own
30794 // body is either a test-side field-setter (in-module tests
30795 // constructing invalid-shape inputs) or a doc-comment reference.
30796 let mut s = three_member_spec();
30797 s.membros[1].caixa = String::new();
30798 assert!(
30799 s.membros[1].nome().is_empty(),
30800 "Membro::nome must byte-equal the .caixa field access — an \
30801 accessor-side detour that no longer projects the raw field \
30802 would silently split this drift-detection test from the \
30803 validate() refusal arm",
30804 );
30805 assert_eq!(
30806 s.membros[1].nome(),
30807 s.membros[1].caixa.as_str(),
30808 "Membro::nome and .caixa.as_str() must byte-equal on an \
30809 empty-`:caixa` entry — the emptiness gate keys off the \
30810 accessor by construction",
30811 );
30812 assert_eq!(
30813 s.validate().unwrap_err(),
30814 AplicacaoError::MembroCaixaEmpty,
30815 "validate_membros' emptiness gate must fire MembroCaixaEmpty \
30816 on an entry whose accessor-projected `nome()` is empty",
30817 );
30818 }
30819
30820 #[test]
30821 fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
30822 // Convergence pin, paired with the deletion of the redundant
30823 // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
30824 // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
30825 // after the collapse, the `MembroCaixaEmpty` refusal on every
30826 // empty-`:caixa` per-member input is owned solely by the shared
30827 // [`validate_membro_caixa`] helper — the same per-slot substrate
30828 // primitive routing empty + shape arms uniformly onto
30829 // [`crate::render::require_valid_dns_1123_label`] that every
30830 // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
30831 // on `:placement :clusters`, [`validate_entrada_para`] on
30832 // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
30833 // :de`/`:para`) already funnels its own empty arm through.
30834 //
30835 // Two arms pin the collapse:
30836 //
30837 // (1) The per-slot helper called with the empty string returns
30838 // byte-equal to the previous inline arm's diagnostic — so
30839 // a future rebrand of [`validate_membro_caixa`] that
30840 // (accidentally) stopped returning [`MembroCaixaEmpty`] on
30841 // empty input (an inadvertent switch to
30842 // [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
30843 // `on_invalid` arm, an accidental re-routing to a shared
30844 // `MembroError::Empty` under a future error-hierarchy
30845 // flattening) would silently split the drift from the
30846 // [`validate_membros`] caller and surface the wrong
30847 // diagnostic on the author-facing empty-`:caixa` footgun.
30848 //
30849 // (2) The whole-spec equivalence: an empty-`:caixa` entry
30850 // anywhere in the `:membros` fan-out still trips
30851 // [`MembroCaixaEmpty`] end-to-end via [`validate`], with
30852 // no outer inline guard needed. Same shape as the
30853 // whole-spec arm on [`validate_placement_cluster`] /
30854 // [`validate_entrada_para`] / [`validate_contrato_caixa`]:
30855 // one substrate primitive per axis, folding empty + shape.
30856 //
30857 // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
30858 // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
30859 // MeshPolicy::validate) already extend across the M3 mesh-slot
30860 // family — closes the last per-slot gate on the family carrying
30861 // an inline empty guard duplicating its own helper.
30862 assert_eq!(
30863 validate_membro_caixa(""),
30864 Err(AplicacaoError::MembroCaixaEmpty),
30865 "validate_membro_caixa must own the empty arm outright — a \
30866 regression here would silently split MembroCaixaEmpty from \
30867 validate_membros' end-to-end refusal shape after the outer \
30868 inline `if m.nome().is_empty()` guard collapse",
30869 );
30870 let mut s = three_member_spec();
30871 s.membros[0].caixa = String::new();
30872 assert_eq!(
30873 s.validate().unwrap_err(),
30874 AplicacaoError::MembroCaixaEmpty,
30875 "an empty-`:caixa` :membros head entry must trip \
30876 MembroCaixaEmpty end-to-end via validate() with the outer \
30877 inline guard removed — the per-slot helper alone is now \
30878 load-bearing",
30879 );
30880 let mut s = three_member_spec();
30881 s.membros[2].caixa = String::new();
30882 assert_eq!(
30883 s.validate().unwrap_err(),
30884 AplicacaoError::MembroCaixaEmpty,
30885 "an empty-`:caixa` :membros tail entry must trip \
30886 MembroCaixaEmpty end-to-end via validate() with the outer \
30887 inline guard removed — the per-slot helper alone reaches \
30888 every fan-out position",
30889 );
30890 }
30891
30892 #[test]
30893 fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
30894 // The canonical per-`:placement` Akka-cluster-sharding
30895 // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
30896 // the `:placement :shard-key` field byte-for-byte, borrowed
30897 // from the typed slot's own `Option<String>` storage. Peer of
30898 // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
30899 // per-`:contratos` [`WitContract::source`] /
30900 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
30901 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
30902 // slot-atom scalar-value axes — same "the substrate-primitive
30903 // accessor must byte-equal the raw field access verbatim across
30904 // every author-declared value" discipline extended to the
30905 // per-`:placement` Akka-cluster-sharding key extractor arm.
30906 // Pins against a future silent detour that re-normalized the
30907 // key (an accidental `.to_lowercase()` — every non-empty
30908 // `:shard-key` is validated as a printable-ASCII single-token
30909 // reference upstream via [`validate_placement_shard_key`], so
30910 // any re-normalization is redundant + a drift surface between
30911 // the validator and the accessor), a per-cluster alias rewrite
30912 // the operator authors on one consumer without the other, or an
30913 // accidental variable-prefix strip (`$tenantId` → `tenantId`)
30914 // that didn't land on the peer field-access sites. Four values
30915 // sweep the accept-set the shape gate admits — bare identifier,
30916 // `$`-prefixed variable, dotted path, `${}`-quoted variable —
30917 // the four canonical Akka-style entity-id extractor shapes the
30918 // future M4 cluster-sharding reconciler hashes.
30919 for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
30920 let p = Placement {
30921 estrategia: PlacementStrategy::Sharded,
30922 clusters: vec!["rio".into()],
30923 affinity: None,
30924 shard_key: Some(key.into()),
30925 };
30926 assert_eq!(
30927 p.shard_key(),
30928 Some(key),
30929 "Placement::shard_key must return :placement :shard-key \
30930 verbatim (got {:?}, expected Some({key:?}))",
30931 p.shard_key(),
30932 );
30933 assert_eq!(
30934 p.shard_key(),
30935 p.shard_key.as_deref(),
30936 "Placement::shard_key must byte-equal the .shard_key \
30937 field's `.as_deref()` projection",
30938 );
30939 }
30940 }
30941
30942 #[test]
30943 fn placement_shard_key_none_when_field_is_none() {
30944 // The absent-`:shard-key` arm of the per-`:placement`
30945 // Akka-cluster-sharding accessor pin: when the typed slot is
30946 // absent — the canonical shape under `:estrategia Replicated` /
30947 // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
30948 // enforced `shard_key.is_some() == matches!(estrategia,
30949 // Sharded)` partition — [`Placement::shard_key`] must return
30950 // `None`. Pins against a future silent detour that projected
30951 // the absent slot to a `Some("")` empty-string default (the
30952 // canonical `Option<String>` → `String` collapse footgun the
30953 // sibling M2 [`crate::LimitsSpec::is_empty`] /
30954 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
30955 // already guard on the peer M2 typed-slot surfaces), a
30956 // `Some("None")` stringified-None round-trip, or a `Some` arm
30957 // whose contents were derived from a sibling slot (an
30958 // accidental fallback to `estrategia.as_str()` that read the
30959 // strategy discriminator into the key axis). Two placements
30960 // sweep the accept-set every `validate`-passing non-`Sharded`
30961 // shape lands on — `Replicated` (Erlang/OTP distributed-app
30962 // takeover) and `SingleNode` (single-node hosting).
30963 for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
30964 let p = Placement {
30965 estrategia,
30966 clusters: vec!["rio".into()],
30967 affinity: None,
30968 shard_key: None,
30969 };
30970 assert!(
30971 p.shard_key().is_none(),
30972 "Placement::shard_key must return None when the typed \
30973 slot is absent under :estrategia {estrategia:?} (got {:?})",
30974 p.shard_key(),
30975 );
30976 assert_eq!(
30977 p.shard_key(),
30978 p.shard_key.as_deref(),
30979 "Placement::shard_key must byte-equal the .shard_key \
30980 field's `.as_deref()` projection in the absent arm",
30981 );
30982 }
30983 }
30984
30985 #[test]
30986 fn placement_shard_key_borrows_from_shard_key_storage() {
30987 // The borrow-not-copy pin: [`Placement::shard_key`] must return
30988 // an `Option<&str>` whose `Some` arm borrows from the typed
30989 // slot's own [`String`] storage — same-address invariant with
30990 // `p.shard_key.as_deref().unwrap()`. Pins against a future
30991 // silent detour that allocated a fresh `String`
30992 // (`self.shard_key.clone().map(...)` in the body would type-
30993 // check but silently drop the borrow, and every downstream
30994 // consumer that assumed the returned slice outlives `&self`
30995 // would break on a stale-reference use-after-free — the
30996 // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
30997 // gate's `Some(k)`-bound match arm reads `k: &str` under the
30998 // accessor's return type and would silently misbehave if this
30999 // accessor produced a detached copy). Peer of the sibling
31000 // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
31001 // [`WitContract::source`] / [`WitContract::destination`]
31002 // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
31003 // (6db982c) borrow-invariant pins on the mesh-slot-atom
31004 // scalar-value axes — first extension of the discipline onto
31005 // an `Option<String>`-shaped optional-scalar axis.
31006 let p = Placement {
31007 estrategia: PlacementStrategy::Sharded,
31008 clusters: vec!["rio".into()],
31009 affinity: None,
31010 shard_key: Some("tenantId".into()),
31011 };
31012 let key = p.shard_key().expect("Some arm");
31013 let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
31014 assert_eq!(
31015 key.as_ptr(),
31016 storage_slice.as_ptr(),
31017 "Placement::shard_key must borrow from the .shard_key \
31018 String's backing storage — a fresh allocation here means \
31019 the accessor no longer names the substrate-primitive typed \
31020 dispatch and every downstream consumer would silently \
31021 carry a detached copy",
31022 );
31023 assert_eq!(
31024 key.len(),
31025 storage_slice.len(),
31026 "Placement::shard_key and .shard_key.as_deref() must byte-\
31027 equal in length as well as in address",
31028 );
31029 }
31030
31031 #[test]
31032 fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
31033 // The canonical per-`:placement` M3-Adaptive-compression-hint
31034 // scalar pin: [`Placement::affinity`] must return the
31035 // `:placement :affinity` field byte-for-byte, borrowed from the
31036 // typed slot's own `Option<String>` storage. Peer of the sibling
31037 // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
31038 // pin on the sibling `Option<&str>` optional-scalar axis — same
31039 // "the substrate-primitive accessor must byte-equal the raw
31040 // field access verbatim across every author-declared value"
31041 // discipline extended to the peer per-`:placement` M3-Adaptive-
31042 // compression-hint arm. Pins against a future silent detour
31043 // that re-normalized the hint (an accidental `.to_lowercase()`
31044 // — every `:affinity` is already validated as a DNS-1123 label
31045 // upstream via [`validate_placement_affinity`], so any re-
31046 // normalization is redundant + a drift surface between the
31047 // validator and the accessor), a per-cluster alias rewrite the
31048 // operator authors on one consumer without the other, or an
31049 // accidental hint-family collapse (`low-latency` → `latency`
31050 // that dropped the qualifier prefix). Four values sweep the
31051 // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
31052 // canonical adaptive-compression-weight biases the future M4
31053 // placement engine reads.
31054 for hint in [
31055 "data-locality",
31056 "low-latency",
31057 "high-throughput",
31058 "cost-optimized",
31059 ] {
31060 let p = Placement {
31061 estrategia: PlacementStrategy::Replicated,
31062 clusters: vec!["rio".into()],
31063 affinity: Some(hint.into()),
31064 shard_key: None,
31065 };
31066 assert_eq!(
31067 p.affinity(),
31068 Some(hint),
31069 "Placement::affinity must return :placement :affinity \
31070 verbatim (got {:?}, expected Some({hint:?}))",
31071 p.affinity(),
31072 );
31073 assert_eq!(
31074 p.affinity(),
31075 p.affinity.as_deref(),
31076 "Placement::affinity must byte-equal the .affinity \
31077 field's `.as_deref()` projection",
31078 );
31079 }
31080 }
31081
31082 #[test]
31083 fn placement_affinity_none_when_field_is_none() {
31084 // The absent-`:affinity` arm of the per-`:placement`
31085 // M3-Adaptive-compression-hint accessor pin: when the typed
31086 // slot is absent — the canonical shape of an Aplicacao that
31087 // leaves the compression weighting up to the placement engine's
31088 // cluster-default arm — [`Placement::affinity`] must return
31089 // `None`. Pins against a future silent detour that projected
31090 // the absent slot to a `Some("")` empty-string default (the
31091 // canonical `Option<String>` → `String` collapse footgun the
31092 // sibling M2 [`crate::LimitsSpec::is_empty`] /
31093 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
31094 // already guard on the peer M2 typed-slot surfaces), a
31095 // `Some("None")` stringified-None round-trip, a `Some` arm
31096 // whose contents were derived from a sibling slot (an
31097 // accidental fallback to `estrategia.as_str()` that read the
31098 // strategy discriminator into the hint axis), or a
31099 // `Some("default")` implicit-default that would silently biases
31100 // the routing without the author having written one. Three
31101 // placements sweep the accept-set every `validate`-passing
31102 // `:affinity None` shape lands on — one per PlacementStrategy
31103 // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
31104 // with a shard-key), since `:affinity` is orthogonal to
31105 // `:estrategia` in the typed grammar.
31106 for (estrategia, shard_key) in [
31107 (PlacementStrategy::SingleNode, None),
31108 (PlacementStrategy::Replicated, None),
31109 (PlacementStrategy::Sharded, Some("tenantId".to_string())),
31110 ] {
31111 let p = Placement {
31112 estrategia,
31113 clusters: vec!["rio".into()],
31114 affinity: None,
31115 shard_key,
31116 };
31117 assert!(
31118 p.affinity().is_none(),
31119 "Placement::affinity must return None when the typed \
31120 slot is absent under :estrategia {estrategia:?} (got {:?})",
31121 p.affinity(),
31122 );
31123 assert_eq!(
31124 p.affinity(),
31125 p.affinity.as_deref(),
31126 "Placement::affinity must byte-equal the .affinity \
31127 field's `.as_deref()` projection in the absent arm",
31128 );
31129 }
31130 }
31131
31132 #[test]
31133 fn placement_affinity_borrows_from_affinity_storage() {
31134 // The borrow-not-copy pin: [`Placement::affinity`] must return
31135 // an `Option<&str>` whose `Some` arm borrows from the typed
31136 // slot's own [`String`] storage — same-address invariant with
31137 // `p.affinity.as_deref().unwrap()`. Pins against a future
31138 // silent detour that allocated a fresh `String`
31139 // (`self.affinity.clone().map(...)` in the body would type-
31140 // check but silently drop the borrow, and every downstream
31141 // consumer that assumed the returned slice outlives `&self`
31142 // would break on a stale-reference use-after-free — the
31143 // [`AplicacaoSpec::validate_placement`] per-hint value-shape
31144 // gate reads the accessor's `&str` return through the
31145 // [`validate_placement_affinity`] `&str` parameter and would
31146 // silently misbehave if this accessor produced a detached
31147 // copy). Peer of the sibling per-`:placement`
31148 // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
31149 // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
31150 // extends the discipline onto the sibling per-`:placement`
31151 // M3-Adaptive-compression-hint arm.
31152 let p = Placement {
31153 estrategia: PlacementStrategy::Replicated,
31154 clusters: vec!["rio".into()],
31155 affinity: Some("data-locality".into()),
31156 shard_key: None,
31157 };
31158 let hint = p.affinity().expect("Some arm");
31159 let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
31160 assert_eq!(
31161 hint.as_ptr(),
31162 storage_slice.as_ptr(),
31163 "Placement::affinity must borrow from the .affinity \
31164 String's backing storage — a fresh allocation here means \
31165 the accessor no longer names the substrate-primitive typed \
31166 dispatch and every downstream consumer would silently \
31167 carry a detached copy",
31168 );
31169 assert_eq!(
31170 hint.len(),
31171 storage_slice.len(),
31172 "Placement::affinity and .affinity.as_deref() must byte-\
31173 equal in length as well as in address",
31174 );
31175 }
31176
31177 #[test]
31178 fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
31179 // The canonical per-`:placement` distribution-strategy-scalar
31180 // pin: [`Placement::estrategia`] must return the `:placement
31181 // :estrategia` field verbatim as a [`PlacementStrategy`],
31182 // `Copy`-projected from the typed slot's own `PlacementStrategy`
31183 // storage across every variant in the closed accept-set
31184 // (`SingleNode` — Erlang/OTP distributed-app takeover;
31185 // `Replicated` — active-active across every named cluster;
31186 // `Sharded` — Akka-style hash-keyed entity distribution). Pins
31187 // against a future silent detour that re-derived the strategy
31188 // from a peer axis (an accidental fallback to
31189 // `if shard_key.is_some() { Sharded } else { Replicated }`
31190 // collapse that read the shard-key axis into the strategy
31191 // discriminator), a variant remap the operator authors on one
31192 // consumer without the other, or a stale-derive detour that
31193 // substituted [`PlacementStrategy::default`] when the field
31194 // held any explicit variant (which would silently collapse the
31195 // distinction between "author explicitly declared `:estrategia
31196 // Replicated`" and "author omitted the slot and inherited the
31197 // default" the future per-cluster override slot depends on).
31198 // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
31199 // pin on the `Copy`-return `u16` scalar axis — same "the
31200 // substrate-primitive accessor must byte-equal the raw field
31201 // access verbatim across every author-declared value" discipline
31202 // extended onto the per-`:placement` distribution-strategy
31203 // `Copy`-composite-enum scalar axis.
31204 for estrategia in [
31205 PlacementStrategy::SingleNode,
31206 PlacementStrategy::Replicated,
31207 PlacementStrategy::Sharded,
31208 ] {
31209 // Route the paired `:shard-key` fixture-builder through the
31210 // typed cross-slot invariant predicate
31211 // [`PlacementStrategy::requires_shard_key`] rather than the
31212 // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
31213 // arm-identity predicate — same discipline the sibling
31214 // `placement_strategy_variants_round_trip` fixture builder now
31215 // reads through.
31216 let shard_key = estrategia
31217 .requires_shard_key()
31218 .then(|| "tenantId".to_string());
31219 let p = Placement {
31220 estrategia,
31221 clusters: vec!["rio".into()],
31222 affinity: None,
31223 shard_key,
31224 };
31225 assert_eq!(
31226 p.estrategia(),
31227 estrategia,
31228 "Placement::estrategia must return :placement :estrategia \
31229 verbatim (got {:?}, expected {estrategia:?})",
31230 p.estrategia(),
31231 );
31232 assert_eq!(
31233 p.estrategia(),
31234 p.estrategia,
31235 "Placement::estrategia accessor and .estrategia field \
31236 access must byte-equal — the accessor is the substrate-\
31237 primitive typed dispatch every downstream distribution-\
31238 strategy consumer must route through",
31239 );
31240 }
31241 }
31242
31243 #[test]
31244 fn validate_placement_reads_through_lifted_estrategia_accessor() {
31245 // Three-consumer coherence pin: the
31246 // [`AplicacaoSpec::validate_placement`]
31247 // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
31248 // `estrategia:` field (which reads through
31249 // [`Placement::estrategia`] to name the strategy the empty
31250 // `:clusters` list was declared against), the same method's
31251 // `Sharded ↔ non-Sharded` `match` partition dispatch (which
31252 // reads through [`Placement::estrategia`] to fan across the
31253 // shape-gate cascades), and the non-`Sharded`-arm
31254 // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
31255 // `estrategia:` field (which reads through
31256 // [`Placement::estrategia`] to name the strategy the declared-
31257 // but-inert `:shard-key` was authored under) must all key off
31258 // the lifted accessor, so any future rebrand on the typed
31259 // slot's reader shape lands at exactly one place. Pins the
31260 // three-site coherence by exercising each error surface end-
31261 // to-end and asserting the surfaced `estrategia:` field byte-
31262 // equals the accessor's return. Peer of the sibling per-
31263 // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
31264 // pin on the M3 mesh-slot `Copy`-return scalar axis.
31265
31266 // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
31267 // whose `estrategia:` field must byte-equal the accessor's return
31268 // for every variant in the closed accept-set.
31269 for estrategia in [
31270 PlacementStrategy::SingleNode,
31271 PlacementStrategy::Replicated,
31272 PlacementStrategy::Sharded,
31273 ] {
31274 let mut spec = three_member_spec();
31275 spec.placement.estrategia = estrategia;
31276 spec.placement.clusters = Vec::new();
31277 // Route the paired `:shard-key` spec-mutator through the typed
31278 // cross-slot invariant predicate
31279 // [`PlacementStrategy::requires_shard_key`] rather than the
31280 // [`gen_platform::IsVariant`]-derived
31281 // [`PlacementStrategy::is_sharded`] arm-identity predicate —
31282 // same discipline the sibling
31283 // `placement_strategy_variants_round_trip` and
31284 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
31285 // fixture builders now read through.
31286 spec.placement.shard_key = estrategia
31287 .requires_shard_key()
31288 .then(|| "tenantId".to_string());
31289 let err = spec.validate().unwrap_err();
31290 match err {
31291 AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
31292 assert_eq!(
31293 e,
31294 spec.placement.estrategia(),
31295 "PlacementWithoutClusters.estrategia must byte-equal \
31296 Placement::estrategia() — the error carrier reads \
31297 through the lifted accessor",
31298 );
31299 }
31300 other => panic!(
31301 "expected PlacementWithoutClusters, got {other:?} for \
31302 estrategia={estrategia:?}"
31303 ),
31304 }
31305 }
31306
31307 // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
31308 // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
31309 // must byte-equal the accessor's return for both non-`Sharded`
31310 // strategies.
31311 for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
31312 let mut spec = three_member_spec();
31313 spec.placement.estrategia = estrategia;
31314 spec.placement.shard_key = Some("tenantId".into());
31315 let err = spec.validate().unwrap_err();
31316 match err {
31317 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
31318 assert_eq!(
31319 e,
31320 spec.placement.estrategia(),
31321 "ShardKeyOnNonSharded.estrategia must byte-equal \
31322 Placement::estrategia() — the non-Sharded-arm \
31323 refusal reads through the lifted accessor",
31324 );
31325 }
31326 other => panic!(
31327 "expected ShardKeyOnNonSharded, got {other:?} for \
31328 estrategia={estrategia:?}"
31329 ),
31330 }
31331 }
31332 }
31333
31334 // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
31335 //
31336 // The [`Placement::clusters`] accessor lift is the second slice-return
31337 // (`&[T]`) accessor on any typed slot — sibling to the seed M2
31338 // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
31339 // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
31340 // below cover (1) the accessor's byte-equal projection against the raw
31341 // field access across the empty / singleton / cohort fixtures the
31342 // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
31343 // and the per-cluster validate loop fan between, and (2) the two-
31344 // consumer coherence of the paired pre-flight refusal probe and the
31345 // per-cluster validate loop routing through the accessor on both arms.
31346
31347 #[test]
31348 fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
31349 // The canonical per-`:placement` cluster-pool-scalar-shape pin:
31350 // [`Placement::clusters`] must return the `:placement :clusters`
31351 // typed `Vec<String>` verbatim as a `&[String]` slice-view over
31352 // the same backing buffer the raw `self.clusters.as_slice()`
31353 // field access borrows from, byte-equal across every
31354 // representative fixture in the accept-set — the empty slice
31355 // (the pre-validation sentinel every
31356 // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
31357 // the singleton slice (the minimal `SingleNode`-shape cohort),
31358 // and multi-entry cohorts (the peer `Replicated` / `Sharded`
31359 // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
31360 //
31361 // Pins against a future silent detour that returned
31362 // `&Vec<String>` (which would type-check but leak the storage-
31363 // side `Vec`'s grow/push/reserve surface no consumer of the
31364 // typed view reaches for), a fresh-allocated `Vec<String>` copy
31365 // (which would type-check via a coercion but silently break
31366 // every downstream caller that relied on the slice sharing the
31367 // backing buffer's identity), or an out-of-order or length-
31368 // drifted projection (which would silently split the paired
31369 // pre-flight `.is_empty()` refusal probe's input from the per-
31370 // cluster validate loop's traversal input).
31371 //
31372 // Peer of the sibling M2
31373 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
31374 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
31375 // `:supervisor` static-child-list axis, extended onto the M3
31376 // per-`:placement` distribution-target-list `Vec`-carry axis.
31377 let fixtures: Vec<Vec<String>> = vec![
31378 Vec::new(),
31379 vec!["rio".into()],
31380 vec!["rio".into(), "mar".into()],
31381 vec!["rio".into(), "mar".into(), "plo".into()],
31382 ];
31383 for clusters in fixtures {
31384 let p = Placement {
31385 clusters: clusters.clone(),
31386 ..Placement::default()
31387 };
31388 assert_eq!(
31389 p.clusters(),
31390 clusters.as_slice(),
31391 "Placement::clusters must return :placement :clusters \
31392 verbatim (got {:?}, expected {:?})",
31393 p.clusters(),
31394 clusters.as_slice(),
31395 );
31396 assert_eq!(
31397 p.clusters(),
31398 p.clusters.as_slice(),
31399 "Placement::clusters accessor and .clusters.as_slice() \
31400 field access must byte-equal — the accessor is the \
31401 substrate-primitive typed dispatch every downstream \
31402 cluster-pool consumer must route through",
31403 );
31404 assert_eq!(
31405 p.clusters().len(),
31406 p.clusters.len(),
31407 "Placement::clusters().len() must byte-equal \
31408 self.clusters.len() — a length-drift would silently \
31409 split the paired pre-flight `.is_empty()` refusal \
31410 probe input from the per-cluster validate loop's \
31411 traversal input",
31412 );
31413 }
31414 }
31415
31416 #[test]
31417 fn validate_placement_reads_through_lifted_clusters_accessor() {
31418 // Two-consumer coherence pin: the
31419 // [`AplicacaoSpec::validate_placement`] pre-flight
31420 // `self.placement.clusters().is_empty()` refusal probe (which
31421 // must trip [`AplicacaoError::PlacementWithoutClusters`] when
31422 // the accessor projects the empty slice) and the per-cluster
31423 // validate loop's `for c in self.placement.clusters()`
31424 // traversal (which must reach every entry in the same order
31425 // the accessor projects, so both the per-entry value-shape
31426 // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
31427 // and the duplicate-detection HashSet insert that trips
31428 // [`AplicacaoError::PlacementClusterDuplicate`] key off the
31429 // accessor's projection) must both key off the lifted
31430 // accessor, so any future rebrand on the typed slot's reader
31431 // shape lands at exactly one place. Pins the two-site
31432 // coherence by exercising each production consumer end-to-end:
31433 // (1) the `PlacementWithoutClusters` refusal under the empty
31434 // slice, (2) the `PlacementClusterInvalid` refusal fires on
31435 // the second entry of a two-cluster cohort whose head is
31436 // valid but tail is not (which requires the loop to reach the
31437 // second entry through the accessor), and (3) the
31438 // `PlacementClusterDuplicate` refusal fires on the second
31439 // entry of a two-cluster cohort that shares a name (which
31440 // requires the loop to reach both entries — a first-entry-only
31441 // projection would silently pass since the dedup HashSet has
31442 // room for the first insert).
31443 //
31444 // Peer of the sibling M2
31445 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
31446 // (bc92bce) coherence pin on the per-`:supervisor` static-
31447 // child-list axis, extended onto the M3 per-`:placement`
31448 // distribution-target-list `Vec`-carry axis.
31449
31450 // (1) Pre-flight `.is_empty()` probe: the empty slice must
31451 // trip `PlacementWithoutClusters`.
31452 let mut spec = three_member_spec();
31453 spec.placement.clusters = Vec::new();
31454 match spec.validate().unwrap_err() {
31455 AplicacaoError::PlacementWithoutClusters { .. } => {}
31456 other => panic!("expected PlacementWithoutClusters, got {other:?}"),
31457 }
31458 assert!(
31459 spec.placement.clusters().is_empty(),
31460 "the pre-flight refusal input must be the empty slice per \
31461 the accessor's projection",
31462 );
31463
31464 // (2) Per-cluster validate loop: a two-cluster cohort with an
31465 // invalid tail entry must trip `PlacementClusterInvalid` on
31466 // the tail — the loop must reach the second entry through
31467 // the accessor.
31468 let mut spec = three_member_spec();
31469 spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
31470 match spec.validate().unwrap_err() {
31471 AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
31472 assert_eq!(
31473 cluster, "BAD_CLUSTER",
31474 "PlacementClusterInvalid.cluster must carry the \
31475 tail entry the loop reached through the accessor",
31476 );
31477 }
31478 other => panic!("expected PlacementClusterInvalid, got {other:?}"),
31479 }
31480 assert_eq!(
31481 spec.placement.clusters().len(),
31482 2,
31483 "the per-cluster validate loop's traversal input must be \
31484 a two-element slice per the accessor's projection",
31485 );
31486
31487 // (3) Per-cluster validate loop: a two-cluster cohort that
31488 // shares a name must trip `PlacementClusterDuplicate` on the
31489 // second entry — the loop must reach both entries through the
31490 // accessor for the dedup HashSet's second insert to collide.
31491 let mut spec = three_member_spec();
31492 spec.placement.clusters = vec!["rio".into(), "rio".into()];
31493 match spec.validate().unwrap_err() {
31494 AplicacaoError::PlacementClusterDuplicate { cluster } => {
31495 assert_eq!(
31496 cluster, "rio",
31497 "PlacementClusterDuplicate.cluster must carry the \
31498 shared cluster name verbatim",
31499 );
31500 }
31501 other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
31502 }
31503 assert_eq!(
31504 spec.placement.clusters().len(),
31505 2,
31506 "the per-cluster validate loop's traversal input must be \
31507 a two-element slice per the accessor's projection",
31508 );
31509 }
31510
31511 #[test]
31512 fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
31513 // The canonical per-`:membros` member-list-slice-shape pin:
31514 // [`AplicacaoSpec::membros`] must return the `:membros` typed
31515 // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
31516 // same backing buffer the raw `self.membros.as_slice()` field
31517 // access borrows from, byte-equal across every representative
31518 // fixture in the accept-set — the empty slice (the pre-
31519 // validation sentinel every [`AplicacaoError::NoMembros`]
31520 // refusal keys off), the singleton slice (the minimal one-
31521 // Servico Aplicacao shape), and multi-entry cohorts (the peer
31522 // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
31523 // load-bearing identity of the application graph).
31524 //
31525 // Pins against a future silent detour that returned
31526 // `&Vec<Membro>` (which would type-check but leak the storage-
31527 // side `Vec`'s grow/push/reserve surface no consumer of the
31528 // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
31529 // (which would type-check via a coercion but silently break
31530 // every downstream caller that relied on the slice sharing the
31531 // backing buffer's identity), or an out-of-order or length-
31532 // drifted projection (which would silently split the paired
31533 // `HashSet<&str>` name-set seed's collect input from the
31534 // pre-flight `.is_empty()` refusal probe's input from the per-
31535 // member validate loop's traversal input from the
31536 // programs.yaml emitter's per-entry fan-out loop's input from
31537 // the `feira app graph` per-member print traversal's input).
31538 //
31539 // Peer of the sibling M2
31540 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
31541 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
31542 // `:supervisor` static-child-list axis and the sibling M3
31543 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
31544 // (a6e18d7) `&[String]` byte-equal pin on the per-
31545 // `:placement` distribution-target-list axis — extends the
31546 // slice-return-accessor byte-equal-projection discipline onto
31547 // the outermost M3 mesh-slot type's per-Aplicacao member-list
31548 // `Vec`-carry axis.
31549 let fixtures: Vec<Vec<Membro>> = vec![
31550 Vec::new(),
31551 vec![membro("catalog", "^0.1")],
31552 vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
31553 vec![
31554 membro("catalog", "^0.1"),
31555 membro("cart", "^0.1"),
31556 membro("payment", "^0.2"),
31557 ],
31558 ];
31559 for membros in fixtures {
31560 let s = AplicacaoSpec {
31561 membros: membros.clone(),
31562 contratos: Vec::new(),
31563 politicas: MeshPolicy::default(),
31564 placement: Placement::default(),
31565 entrada: None,
31566 };
31567 assert_eq!(
31568 s.membros(),
31569 membros.as_slice(),
31570 "AplicacaoSpec::membros must return :membros verbatim \
31571 (got {:?}, expected {:?})",
31572 s.membros(),
31573 membros.as_slice(),
31574 );
31575 assert_eq!(
31576 s.membros(),
31577 s.membros.as_slice(),
31578 "AplicacaoSpec::membros accessor and .membros.as_slice() \
31579 field access must byte-equal — the accessor is the \
31580 substrate-primitive typed dispatch every downstream \
31581 member-list consumer must route through",
31582 );
31583 assert_eq!(
31584 s.membros().len(),
31585 s.membros.len(),
31586 "AplicacaoSpec::membros().len() must byte-equal \
31587 self.membros.len() — a length-drift would silently \
31588 split the paired `HashSet<&str>` name-set seed's \
31589 collect input from the pre-flight `.is_empty()` \
31590 refusal probe input from the per-member validate \
31591 loop's traversal input",
31592 );
31593 }
31594 }
31595
31596 #[test]
31597 fn validate_reads_through_lifted_membros_accessor() {
31598 // Three-consumer coherence pin: the
31599 // [`AplicacaoSpec::validate_membros`] pre-flight
31600 // `self.membros().is_empty()` refusal probe (which must trip
31601 // [`AplicacaoError::NoMembros`] when the accessor projects the
31602 // empty slice), the same method's per-member validate loop's
31603 // `for m in self.membros()` traversal (which must reach every
31604 // entry in the same order the accessor projects, so both the
31605 // per-entry empty-`:caixa` gate that trips
31606 // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
31607 // detection `insert_first_seen` that trips
31608 // [`AplicacaoError::MembroDuplicate`] key off the accessor's
31609 // projection), and the peer [`AplicacaoSpec::validate`]'s
31610 // `HashSet<&str>` name-set seed's
31611 // `self.membros().iter().map(Membro::nome).collect()` collect
31612 // input (which every `:contratos` `:de` / `:para` membership
31613 // lookup rejects an unknown name against) must all three key
31614 // off the lifted accessor, so any future rebrand on the typed
31615 // slot's reader shape lands at exactly one place. Pins the
31616 // three-site coherence by exercising each production consumer
31617 // end-to-end: (1) the `NoMembros` refusal under the empty
31618 // slice, (2) the `MembroCaixaEmpty` refusal fires on the
31619 // second entry of a two-member cohort whose head is valid but
31620 // tail has an empty `:caixa` (which requires the loop to
31621 // reach the second entry through the accessor), and (3) the
31622 // `MembroDuplicate` refusal fires on the second entry of a
31623 // two-member cohort that shares a `:caixa` name (which
31624 // requires the loop to reach both entries through the
31625 // accessor for the dedup HashSet's second insert to collide).
31626 //
31627 // Peer of the sibling M2
31628 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
31629 // (bc92bce) coherence pin on the per-`:supervisor` static-
31630 // child-list axis and the sibling M3
31631 // `validate_placement_reads_through_lifted_clusters_accessor`
31632 // (a6e18d7) coherence pin on the per-`:placement` distribution-
31633 // target-list axis — extends the slice-return-accessor
31634 // multi-consumer coherence discipline onto the outermost M3
31635 // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
31636
31637 // (1) Pre-flight `.is_empty()` probe: the empty slice must
31638 // trip `NoMembros`.
31639 let mut spec = three_member_spec();
31640 spec.membros = Vec::new();
31641 assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
31642 assert!(
31643 spec.membros().is_empty(),
31644 "the pre-flight refusal input must be the empty slice per \
31645 the accessor's projection",
31646 );
31647
31648 // (2) Per-member validate loop: a two-member cohort with an
31649 // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
31650 // the tail — the loop must reach the second entry through
31651 // the accessor.
31652 let mut spec = three_member_spec();
31653 spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
31654 assert_eq!(
31655 spec.validate().unwrap_err(),
31656 AplicacaoError::MembroCaixaEmpty,
31657 );
31658 assert_eq!(
31659 spec.membros().len(),
31660 2,
31661 "the per-member validate loop's traversal input must be \
31662 a two-element slice per the accessor's projection",
31663 );
31664
31665 // (3) Per-member validate loop: a two-member cohort that
31666 // shares a `:caixa` name must trip `MembroDuplicate` on the
31667 // second entry — the loop must reach both entries through the
31668 // accessor for the dedup HashSet's second insert to collide.
31669 let mut spec = three_member_spec();
31670 spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
31671 match spec.validate().unwrap_err() {
31672 AplicacaoError::MembroDuplicate { caixa } => {
31673 assert_eq!(
31674 caixa, "catalog",
31675 "MembroDuplicate.caixa must carry the shared \
31676 member name verbatim",
31677 );
31678 }
31679 other => panic!("expected MembroDuplicate, got {other:?}"),
31680 }
31681 assert_eq!(
31682 spec.membros().len(),
31683 2,
31684 "the per-member validate loop's traversal input must be \
31685 a two-element slice per the accessor's projection",
31686 );
31687 }
31688
31689 #[test]
31690 fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
31691 // The canonical per-`:contratos` contract-list-slice-shape pin:
31692 // [`AplicacaoSpec::contratos`] must return the `:contratos`
31693 // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
31694 // slice-view over the same backing buffer the raw
31695 // `self.contratos.as_slice()` field access borrows from, byte-
31696 // equal across every representative fixture in the accept-set —
31697 // the empty slice (the pre-validation "internal-only mesh" shape
31698 // an Aplicacao whose members exchange no typed edges renders
31699 // through), the singleton slice (the minimal one-edge Aplicacao
31700 // shape), and multi-entry cohorts (the peer multi-edge shapes
31701 // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
31702 // of the application graph).
31703 //
31704 // Pins against a future silent detour that returned
31705 // `&Vec<WitContract>` (which would type-check but leak the
31706 // storage-side `Vec`'s grow/push/reserve surface no consumer of
31707 // the typed view reaches for), a fresh-allocated
31708 // `Vec<WitContract>` copy (which would type-check via a coercion
31709 // but silently break every downstream caller that relied on the
31710 // slice sharing the backing buffer's identity), or an out-of-
31711 // order or length-drifted projection (which would silently split
31712 // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
31713 // seed's traversal input from the `detect_sync_cycles` per-edge
31714 // adjacency-list seed's traversal input from the
31715 // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
31716 // BTreeMap grouping loop's traversal input from the
31717 // `feira app graph` per-contract print traversal's input).
31718 //
31719 // Peer of the immediately-adjacent sibling M3
31720 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
31721 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
31722 // node-list axis, the sibling M3
31723 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
31724 // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
31725 // distribution-target-list axis, and the sibling M2
31726 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
31727 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
31728 // `:supervisor` static-child-list axis — extends the slice-
31729 // return-accessor byte-equal-projection discipline onto the
31730 // outermost M3 mesh-slot type's per-Aplicacao contract-list
31731 // `Vec`-carry axis, closing the last unlifted per-
31732 // `AplicacaoSpec` `Vec`-carry axis.
31733 let fixtures: Vec<Vec<WitContract>> = vec![
31734 Vec::new(),
31735 vec![contract_http("cart", "catalog", "/products/:id")],
31736 vec![
31737 contract_http("cart", "catalog", "/products/:id"),
31738 contract_http("cart", "payment", "/charge"),
31739 ],
31740 vec![
31741 contract_http("cart", "catalog", "/products/:id"),
31742 contract_http("cart", "payment", "/charge"),
31743 contract_http("payment", "catalog", "/audit"),
31744 ],
31745 ];
31746 for contratos in fixtures {
31747 let s = AplicacaoSpec {
31748 membros: vec![
31749 membro("catalog", "^0.1"),
31750 membro("cart", "^0.1"),
31751 membro("payment", "^0.2"),
31752 ],
31753 contratos: contratos.clone(),
31754 politicas: MeshPolicy::default(),
31755 placement: Placement::default(),
31756 entrada: None,
31757 };
31758 assert_eq!(
31759 s.contratos(),
31760 contratos.as_slice(),
31761 "AplicacaoSpec::contratos must return :contratos verbatim \
31762 (got {:?}, expected {:?})",
31763 s.contratos(),
31764 contratos.as_slice(),
31765 );
31766 assert_eq!(
31767 s.contratos(),
31768 s.contratos.as_slice(),
31769 "AplicacaoSpec::contratos accessor and \
31770 .contratos.as_slice() field access must byte-equal — \
31771 the accessor is the substrate-primitive typed dispatch \
31772 every downstream contract-list consumer must route \
31773 through",
31774 );
31775 assert_eq!(
31776 s.contratos().len(),
31777 s.contratos.len(),
31778 "AplicacaoSpec::contratos().len() must byte-equal \
31779 self.contratos.len() — a length-drift would silently \
31780 split the paired per-edge validate-loop's traversal \
31781 input from the sync-cycle adjacency-list seed's \
31782 traversal input from the cilium_network_policies \
31783 per-`(:de, :para)` BTreeMap grouping loop's traversal \
31784 input from the `feira app graph` per-contract print \
31785 traversal's input",
31786 );
31787 }
31788 }
31789
31790 #[test]
31791 fn validate_reads_through_lifted_contratos_accessor() {
31792 // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
31793 // per-`:contratos` validate-loop's `for c in self.contratos()`
31794 // traversal (which must reach every entry in the same order the
31795 // accessor projects, so both the per-entry
31796 // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
31797 // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
31798 // dedup `HashSet` insert key off the accessor's projection),
31799 // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
31800 // `for c in self.contratos()` adjacency-list seed (which drives
31801 // the sync-subgraph deadlock-detection gate via
31802 // [`AplicacaoError::SyncCycle`]), and the peer
31803 // [`caixa_mesh::cilium_network_policies`]'s
31804 // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
31805 // grouping loop (which drives the per-CNP fan-out) must all
31806 // three key off the lifted accessor, so any future rebrand on
31807 // the typed slot's reader shape lands at exactly one place. Pins
31808 // the three-site coherence by exercising the two caixa-core
31809 // production consumers end-to-end: (1) the empty-`:contratos`
31810 // slice must validate without a per-edge diagnostic (the
31811 // per-edge loop is a no-op under the empty projection), (2) the
31812 // `ContratoMemberMissing` refusal fires on the second entry of a
31813 // two-edge cohort whose head references a valid member but tail
31814 // references a phantom name (which requires the loop to reach
31815 // the second entry through the accessor), and (3) the
31816 // `SyncCycle` refusal fires on a self-referential two-edge
31817 // cohort through the sync-cycle detector's peer projection
31818 // (which requires the detector to iterate the accessor's
31819 // projection to add the back-edge to its adjacency list).
31820 //
31821 // Peer of the sibling M3
31822 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
31823 // three-consumer coherence pin on the per-`:membros` node-list
31824 // axis and the sibling M3
31825 // `validate_placement_reads_through_lifted_clusters_accessor`
31826 // (a6e18d7) coherence pin on the per-`:placement` distribution-
31827 // target-list axis — extends the slice-return-accessor multi-
31828 // consumer coherence discipline onto the outermost M3 mesh-slot
31829 // type's per-Aplicacao contract-list `Vec`-carry axis.
31830
31831 // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
31832 // and no per-edge diagnostic surfaces. Validate succeeds on
31833 // the well-formed `:membros` head.
31834 let mut spec = three_member_spec();
31835 spec.contratos = Vec::new();
31836 assert!(
31837 spec.validate().is_ok(),
31838 "empty :contratos must validate — the per-edge loop is a \
31839 no-op under the accessor's empty projection",
31840 );
31841 assert!(
31842 spec.contratos().is_empty(),
31843 "the per-edge validate loop's traversal input must be the \
31844 empty slice per the accessor's projection",
31845 );
31846
31847 // (2) Per-edge validate loop: a two-edge cohort whose tail
31848 // references a phantom `:para` member must trip
31849 // `ContratoMemberMissing` on the tail — the loop must reach
31850 // the second entry through the accessor for the membership
31851 // lookup to fail on the phantom name.
31852 let mut spec = three_member_spec();
31853 spec.contratos = vec![
31854 contract_http("cart", "catalog", "/products/:id"),
31855 contract_http("cart", "phantom", "/x"),
31856 ];
31857 let err = spec.validate().unwrap_err();
31858 assert!(
31859 matches!(
31860 err,
31861 AplicacaoError::ContratoMemberMissing { ref caixa }
31862 if caixa == "phantom"
31863 ),
31864 "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
31865 );
31866 assert_eq!(
31867 spec.contratos().len(),
31868 2,
31869 "the per-edge validate loop's traversal input must be \
31870 a two-element slice per the accessor's projection",
31871 );
31872
31873 // (3) Sync-cycle detector: a two-edge synchronous cohort
31874 // whose second edge closes the sync-subgraph back onto the
31875 // first must trip [`AplicacaoError::ContratoCycle`] — the
31876 // detector must iterate the accessor's projection to add
31877 // both edges to its adjacency list, so a length-drift on
31878 // the accessor's projection would silently disagree with
31879 // the sync-cycle detector on which edge closes the loop.
31880 // Peer projection to the `validate` per-edge loop above:
31881 // the sync-cycle detector routes through the same lifted
31882 // accessor, so a rebrand of the reader shape lands at one
31883 // place. Uses a two-edge cohort (cart → catalog → cart)
31884 // because the per-edge `ContratoSelfLoop` gate fires before
31885 // the sync-cycle detector on a single self-referential edge
31886 // (`cart → cart`) — the cycle-detector's input must be a
31887 // multi-edge cohort for its per-edge traversal input to be
31888 // observably wider than the per-edge validate loop's input.
31889 let mut spec = three_member_spec();
31890 spec.contratos = vec![
31891 contract_http("cart", "catalog", "/products/:id"),
31892 contract_http("catalog", "cart", "/callback"),
31893 ];
31894 let err = spec.validate().unwrap_err();
31895 assert!(
31896 matches!(err, AplicacaoError::ContratoCycle { .. }),
31897 "expected ContratoCycle from the sync-cycle detector on a \
31898 two-edge back-edge cohort, got {err:?}",
31899 );
31900 assert_eq!(
31901 spec.contratos().len(),
31902 2,
31903 "the sync-cycle detector's traversal input must be a \
31904 two-element slice per the accessor's projection",
31905 );
31906 }
31907
31908 #[test]
31909 fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
31910 // The canonical per-`:politicas` outer-composite-reference-shape
31911 // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
31912 // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
31913 // the same backing storage the raw `&self.politicas` field
31914 // access borrows from, byte-equal across every representative
31915 // fixture in the accept-set — the default `MeshPolicy` (the
31916 // author-empty "no policy on any axis" shape whose
31917 // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
31918 // shapes carrying one axis at a time
31919 // (`{mtls_required, timeout, retries, circuit_breaker,
31920 // rate_limit}` — the minimal five-axis fan-out over the
31921 // per-axis lifted accessor family every downstream mesh-artifact
31922 // emitter dispatches on), and the multi-axis composite (the
31923 // canonical `three_member_spec` fixture's `{timeout, retries,
31924 // mtls_required}` triple — the load-bearing shape every
31925 // Aplicacao-scoped fixture in this suite constructs).
31926 //
31927 // Pins against a future silent detour that returned a fresh-
31928 // cloned `MeshPolicy` copy (which would type-check via a `Clone`
31929 // impl but silently break every downstream caller that relied
31930 // on the reference sharing the composite's backing identity), a
31931 // reference to an operator-resolved overlay (the future
31932 // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
31933 // acknowledges — its resolution must land at exactly this
31934 // accessor body, not silently divert the raw slot away from a
31935 // second consumer), or an axis-shuffled projection (a future
31936 // detour that swapped `timeout` and `retries` through the
31937 // accessor would silently split the paired `validate_politicas`
31938 // per-axis bracket-dispatch's traversal input from the peer
31939 // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
31940 // emitter's fan-out input from the peer
31941 // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
31942 // overlay emitter's fan-out input).
31943 //
31944 // Peer of the sibling M3
31945 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
31946 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
31947 // node-list `Vec`-carry axis and the sibling M3
31948 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
31949 // (0dcc926) `&[WitContract]` byte-equal pin on the per-
31950 // `:contratos` edge-list `Vec`-carry axis — extends the outer-
31951 // accessor byte-equal-projection discipline onto the outermost
31952 // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
31953 // reference axis, the first `&Composite`-return accessor on the
31954 // outer [`AplicacaoSpec`] type.
31955 let fixtures: Vec<MeshPolicy> = vec![
31956 MeshPolicy::default(),
31957 MeshPolicy {
31958 mtls_required: Some(true),
31959 ..MeshPolicy::default()
31960 },
31961 MeshPolicy {
31962 mtls_required: Some(false),
31963 ..MeshPolicy::default()
31964 },
31965 MeshPolicy {
31966 timeout: Some(Duration::from_secs(30)),
31967 ..MeshPolicy::default()
31968 },
31969 MeshPolicy {
31970 retries: Some(3),
31971 ..MeshPolicy::default()
31972 },
31973 MeshPolicy {
31974 circuit_breaker: Some(CircuitBreaker {
31975 max_failures: 5,
31976 window: Duration::from_secs(30),
31977 }),
31978 ..MeshPolicy::default()
31979 },
31980 MeshPolicy {
31981 rate_limit: Some(RateLimit {
31982 rate: 100,
31983 window: Duration::from_secs(1),
31984 }),
31985 ..MeshPolicy::default()
31986 },
31987 MeshPolicy {
31988 timeout: Some(Duration::from_secs(30)),
31989 retries: Some(3),
31990 mtls_required: Some(true),
31991 ..MeshPolicy::default()
31992 },
31993 ];
31994 for politicas in fixtures {
31995 let s = AplicacaoSpec {
31996 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
31997 contratos: Vec::new(),
31998 politicas: politicas.clone(),
31999 placement: Placement::default(),
32000 entrada: None,
32001 };
32002 assert_eq!(
32003 *s.politicas(),
32004 politicas,
32005 "AplicacaoSpec::politicas must return :politicas verbatim \
32006 (got {:?}, expected {:?})",
32007 s.politicas(),
32008 politicas,
32009 );
32010 assert!(
32011 std::ptr::eq(s.politicas(), &s.politicas),
32012 "AplicacaoSpec::politicas accessor and &self.politicas \
32013 field access must borrow the same backing storage — \
32014 the accessor is the substrate-primitive typed dispatch \
32015 every downstream mesh-policy composite consumer must \
32016 route through, and a reference-identity split would \
32017 silently break every consumer that relied on the \
32018 borrow sharing the composite's storage",
32019 );
32020 assert_eq!(
32021 s.politicas().is_empty(),
32022 s.politicas.is_empty(),
32023 "AplicacaoSpec::politicas().is_empty() must byte-equal \
32024 self.politicas.is_empty() — an emptiness-drift would \
32025 silently split the paired `validate_politicas` \
32026 per-axis bracket-dispatch's seed from the peer \
32027 caixa-mesh CNP mTLS-overlay emitter's key from the \
32028 peer caixa-mesh HTTPRoute timeout+retry overlay \
32029 emitter's key",
32030 );
32031 }
32032 }
32033
32034 #[test]
32035 fn validate_politicas_reads_through_lifted_politicas_accessor() {
32036 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
32037 // per-axis bracket-dispatch seed (`let p = self.politicas();`,
32038 // followed by the per-axis fan-out `p.timeout()` /
32039 // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
32040 // the lifted axis-level accessor family) must key off the
32041 // lifted outer accessor, so any future rebrand on the typed
32042 // slot's outer-composite reader shape lands at exactly one
32043 // place. Pins the multi-axis coherence by exercising each
32044 // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
32045 // a `Some(Duration::ZERO)` timeout under the outer accessor's
32046 // reference projection, (2) `PolicyRetriesZero` fires on a
32047 // `Some(0)` retries under the same projection, and (3) an
32048 // empty [`MeshPolicy::default`] passes `validate_politicas` —
32049 // the outer accessor's reference-projection reaches every
32050 // per-axis branch without silently short-circuiting any.
32051 //
32052 // Peer of the sibling M3
32053 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
32054 // three-consumer coherence pin on the per-`:membros` node-list
32055 // axis and the sibling M3
32056 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
32057 // three-consumer coherence pin on the per-`:contratos`
32058 // edge-list axis — extends the multi-consumer coherence
32059 // discipline onto the outermost M3 mesh-slot type's per-
32060 // Aplicacao mesh-policy composite-reference axis, the first
32061 // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
32062 // type.
32063
32064 // (1) `PolicyTimeoutZero` refusal under the outer accessor's
32065 // reference projection: a `Some(Duration::ZERO)` timeout must
32066 // trip the zero-floor gate. The bracket-dispatch's first arm
32067 // reads `p.timeout()` on the reference returned by the outer
32068 // accessor.
32069 let mut spec = three_member_spec();
32070 spec.politicas.timeout = Some(Duration::ZERO);
32071 spec.politicas.retries = None;
32072 spec.politicas.circuit_breaker = None;
32073 spec.politicas.rate_limit = None;
32074 assert_eq!(
32075 spec.validate().unwrap_err(),
32076 AplicacaoError::PolicyTimeoutZero,
32077 );
32078 assert!(
32079 std::ptr::eq(spec.politicas(), &spec.politicas),
32080 "the `validate_politicas` per-axis bracket-dispatch's \
32081 traversal input must be the same backing composite the \
32082 accessor's reference projection borrows from",
32083 );
32084
32085 // (2) `PolicyRetriesZero` refusal under the outer accessor's
32086 // reference projection: a `Some(0)` retries must trip the
32087 // zero-floor gate. The bracket-dispatch's second arm reads
32088 // `p.retries()` on the reference returned by the outer accessor.
32089 let mut spec = three_member_spec();
32090 spec.politicas.timeout = None;
32091 spec.politicas.retries = Some(0);
32092 spec.politicas.circuit_breaker = None;
32093 spec.politicas.rate_limit = None;
32094 assert_eq!(
32095 spec.validate().unwrap_err(),
32096 AplicacaoError::PolicyRetriesZero,
32097 );
32098
32099 // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
32100 // — every per-axis arm short-circuits on `None`, so the outer
32101 // accessor's reference projection reaches the fall-through
32102 // `Ok(())` without any per-axis refusal firing.
32103 let mut spec = three_member_spec();
32104 spec.politicas = MeshPolicy::default();
32105 assert!(
32106 spec.validate().is_ok(),
32107 "an empty `MeshPolicy` must pass `validate_politicas` — \
32108 every per-axis arm short-circuits on `None` under the \
32109 outer accessor's reference projection",
32110 );
32111 assert!(
32112 spec.politicas().is_empty(),
32113 "the outer accessor's reference projection must be the \
32114 empty composite per the `MeshPolicy::default()` fixture",
32115 );
32116 }
32117
32118 #[test]
32119 #[allow(clippy::too_many_lines)]
32120 fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
32121 // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
32122 // per-axis bracket-dispatch's `:timeout` and `:retries` arms
32123 // must both key off the lifted axis-level accessors
32124 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
32125 // the peer `:circuit-breaker` / `:rate-limit` arms already
32126 // routing through [`MeshPolicy::circuit_breaker`] /
32127 // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
32128 // per axis on the substrate primitive" shape at the fan-out
32129 // (four axes, four accessors, no raw-field-access site
32130 // anywhere on the bracket-dispatch). Pins the per-axis
32131 // coherence at the accept-set boundaries the bracket carves:
32132 // 1. accessor byte-equal to raw field on every representative
32133 // accept-set value (`None`, sub-cap, at-cap, past-cap
32134 // sentinel) — a future accessor drift that no longer
32135 // shipped the raw slot verbatim would surface here,
32136 // 2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
32137 // routed through the accessor's projection, proving the
32138 // first arm reads through the accessor rather than a
32139 // silent-detour peer-axis field access,
32140 // 3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
32141 // through the accessor's projection, proving the second
32142 // arm reads through the accessor,
32143 // 4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
32144 // passes validate under the accessor projection (paired
32145 // with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
32146 // sibling axis), pinning the upper-boundary accept-arm
32147 // also routes through the accessor.
32148 //
32149 // Peer of the sibling M3
32150 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
32151 // outer-composite-reference coherence pin (which asserts the
32152 // `let p = self.politicas()` seed); extends the discipline onto
32153 // the per-axis fan-out layer that consumes the seed's
32154 // reference. Same shape as
32155 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
32156 // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
32157 // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
32158 // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
32159
32160 // (1) Accessor byte-equal to raw field on the `:timeout` axis
32161 // across the accept-set boundaries the bracket dispatch's
32162 // three-arm gate carves out
32163 // ([`crate::render::require_positive_canonical_bounded_duration`]
32164 // — zero-floor + canonical-form + upper-cap).
32165 for timeout in [
32166 None,
32167 Some(Duration::ZERO),
32168 Some(Duration::from_millis(1)),
32169 Some(POLICY_TIMEOUT_MAX),
32170 ] {
32171 let p = MeshPolicy {
32172 timeout,
32173 ..MeshPolicy::default()
32174 };
32175 assert_eq!(
32176 p.timeout(),
32177 p.timeout,
32178 "MeshPolicy::timeout accessor must byte-equal the raw \
32179 .timeout field across every accept-set boundary the \
32180 validate_politicas :timeout arm carves out — a drift \
32181 here would silently split the validate bracket's arm \
32182 from the peer caixa-mesh HTTPRoute timeout-overlay \
32183 emitter's read",
32184 );
32185 }
32186
32187 // (2) Accessor byte-equal to raw field on the `:retries` axis
32188 // across the accept-set boundaries the bracket dispatch's
32189 // two-arm gate carves out
32190 // ([`crate::render::require_positive_bounded_u32`] — zero-floor
32191 // + upper-cap).
32192 for retries in [
32193 None,
32194 Some(0u32),
32195 Some(1u32),
32196 Some(POLICY_RETRIES_MAX),
32197 Some(POLICY_RETRIES_MAX + 1),
32198 Some(u32::MAX),
32199 ] {
32200 let p = MeshPolicy {
32201 retries,
32202 ..MeshPolicy::default()
32203 };
32204 assert_eq!(
32205 p.retries(),
32206 p.retries,
32207 "MeshPolicy::retries accessor must byte-equal the raw \
32208 .retries field across every accept-set boundary the \
32209 validate_politicas :retries arm carves out — a drift \
32210 here would silently split the validate bracket's arm \
32211 from the peer caixa-mesh HTTPRoute retry-overlay \
32212 emitter's read",
32213 );
32214 }
32215
32216 // (3) `PolicyTimeoutZero` fires on the accessor-projected
32217 // zero-floor boundary. A silent detour that no longer read
32218 // through `p.timeout()` (a peer-axis field read, an accidental
32219 // Option::and-then chain that collapsed the None arm to Some,
32220 // an accessor rebrand that clamped the return through the
32221 // upper cap) would fail to refuse here.
32222 let mut spec = three_member_spec();
32223 spec.politicas.timeout = Some(Duration::ZERO);
32224 spec.politicas.retries = None;
32225 spec.politicas.circuit_breaker = None;
32226 spec.politicas.rate_limit = None;
32227 assert_eq!(
32228 spec.politicas().timeout(),
32229 Some(Duration::ZERO),
32230 "the accessor projection must reflect the fixture's \
32231 `Some(Duration::ZERO)` :timeout verbatim",
32232 );
32233 assert_eq!(
32234 spec.validate().unwrap_err(),
32235 AplicacaoError::PolicyTimeoutZero,
32236 "the validate_politicas :timeout zero-floor arm must fire \
32237 through the lifted accessor's projection — a silent \
32238 detour to a peer-axis field would fail to refuse",
32239 );
32240
32241 // (4) `PolicyRetriesZero` fires on the accessor-projected
32242 // zero-floor boundary on the sibling `:retries` axis.
32243 let mut spec = three_member_spec();
32244 spec.politicas.timeout = None;
32245 spec.politicas.retries = Some(0);
32246 spec.politicas.circuit_breaker = None;
32247 spec.politicas.rate_limit = None;
32248 assert_eq!(
32249 spec.politicas().retries(),
32250 Some(0),
32251 "the accessor projection must reflect the fixture's \
32252 `Some(0)` :retries verbatim",
32253 );
32254 assert_eq!(
32255 spec.validate().unwrap_err(),
32256 AplicacaoError::PolicyRetriesZero,
32257 "the validate_politicas :retries zero-floor arm must fire \
32258 through the lifted accessor's projection — a silent \
32259 detour to a peer-axis field would fail to refuse",
32260 );
32261
32262 // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
32263 // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
32264 // must pass validate under the accessor projection — pins the
32265 // upper-boundary accept-arm also routes through the lifted
32266 // accessor (a drift that clamped or short-circuited at the
32267 // upper boundary would fail the whole-spec validate here).
32268 let mut spec = three_member_spec();
32269 spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
32270 spec.politicas.retries = Some(POLICY_RETRIES_MAX);
32271 spec.politicas.circuit_breaker = None;
32272 spec.politicas.rate_limit = None;
32273 assert_eq!(
32274 spec.politicas().timeout(),
32275 Some(POLICY_TIMEOUT_MAX),
32276 "the accessor projection must reflect the fixture's \
32277 at-cap :timeout verbatim",
32278 );
32279 assert_eq!(
32280 spec.politicas().retries(),
32281 Some(POLICY_RETRIES_MAX),
32282 "the accessor projection must reflect the fixture's \
32283 at-cap :retries verbatim",
32284 );
32285 assert!(
32286 spec.validate().is_ok(),
32287 "at-cap :timeout + :retries must pass validate under the \
32288 accessor projection — the upper-boundary accept-arm on \
32289 both axes routes through the lifted accessor",
32290 );
32291 }
32292
32293 #[test]
32294 fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
32295 // The canonical per-`:placement` outer-composite-reference-shape
32296 // pin: [`AplicacaoSpec::placement`] must return the `:placement`
32297 // typed `Placement` verbatim as a `&Placement` reference over the
32298 // same backing storage the raw `&self.placement` field access
32299 // borrows from, byte-equal across every representative fixture in
32300 // the accept-set — the default `Placement` (the substrate seed
32301 // shape whose [`PlacementStrategy::default`] evaluates to
32302 // `SingleNode` with an empty `:clusters` pool and both
32303 // optional-scalar axes `None`), and every canonical strategy /
32304 // cluster-pool / optional-scalar combination the
32305 // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
32306 // three [`PlacementStrategy`] variants — `SingleNode`,
32307 // `Replicated`, `Sharded` — cross-projected with a non-empty
32308 // `:clusters` pool and, on the `Sharded` arm, a non-empty
32309 // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
32310 // canonical `three_member_spec` `Replicated` fixture's
32311 // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
32312 //
32313 // Pins against a future silent detour that returned a fresh-
32314 // cloned `Placement` copy (which would type-check via a `Clone`
32315 // impl but silently break every downstream caller that relied on
32316 // the reference sharing the composite's backing identity), a
32317 // reference to an operator-resolved overlay (the future per-
32318 // cluster `:placement-overrides` slot MESH-COMPOSITION §V
32319 // acknowledges — its resolution must land at exactly this
32320 // accessor body, not silently divert the raw slot away from a
32321 // second consumer), or an axis-shuffled projection (a future
32322 // detour that swapped `clusters` and `affinity` through the
32323 // accessor would silently split the paired `validate_placement`
32324 // per-axis bracket-dispatch's traversal input from the peer
32325 // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
32326 // programs.yaml distribution-annotation emitter's fan-out input
32327 // from the peer `feira app graph` per-Aplicacao print line's
32328 // input).
32329 //
32330 // Peer of the sibling M3
32331 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
32332 // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
32333 // outer mesh-policy composite-reference axis, and of the sibling
32334 // slice-return `aplicacao_spec_membros_returns_membros_slice_
32335 // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
32336 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
32337 // across_permutations` (0dcc926) `&[WitContract]` pins — extends
32338 // the outer-accessor byte-equal-projection discipline onto the
32339 // outermost M3 mesh-slot type's per-Aplicacao distribution
32340 // composite-reference axis, the second `&Composite`-return
32341 // accessor on the outer [`AplicacaoSpec`] type.
32342 let fixtures: Vec<Placement> = vec![
32343 Placement::default(),
32344 Placement {
32345 estrategia: PlacementStrategy::SingleNode,
32346 clusters: vec!["rio".into()],
32347 affinity: None,
32348 shard_key: None,
32349 },
32350 Placement {
32351 estrategia: PlacementStrategy::Replicated,
32352 clusters: vec!["rio".into(), "mar".into()],
32353 affinity: None,
32354 shard_key: None,
32355 },
32356 Placement {
32357 estrategia: PlacementStrategy::Replicated,
32358 clusters: vec!["rio".into(), "mar".into()],
32359 affinity: Some("data-locality".into()),
32360 shard_key: None,
32361 },
32362 Placement {
32363 estrategia: PlacementStrategy::Sharded,
32364 clusters: vec!["rio".into(), "mar".into()],
32365 affinity: None,
32366 shard_key: Some("tenantId".into()),
32367 },
32368 Placement {
32369 estrategia: PlacementStrategy::Sharded,
32370 clusters: vec!["rio".into(), "mar".into(), "sol".into()],
32371 affinity: Some("low-latency".into()),
32372 shard_key: Some("metadata.tenantId".into()),
32373 },
32374 ];
32375 for placement in fixtures {
32376 let s = AplicacaoSpec {
32377 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
32378 contratos: Vec::new(),
32379 politicas: MeshPolicy::default(),
32380 placement: placement.clone(),
32381 entrada: None,
32382 };
32383 assert_eq!(
32384 *s.placement(),
32385 placement,
32386 "AplicacaoSpec::placement must return :placement verbatim \
32387 (got {:?}, expected {:?})",
32388 s.placement(),
32389 placement,
32390 );
32391 assert!(
32392 std::ptr::eq(s.placement(), &s.placement),
32393 "AplicacaoSpec::placement accessor and &self.placement \
32394 field access must borrow the same backing storage — the \
32395 accessor is the substrate-primitive typed dispatch every \
32396 downstream distribution-composite consumer must route \
32397 through, and a reference-identity split would silently \
32398 break every consumer that relied on the borrow sharing \
32399 the composite's storage",
32400 );
32401 assert_eq!(
32402 s.placement().estrategia(),
32403 s.placement.estrategia,
32404 "AplicacaoSpec::placement().estrategia() must byte-equal \
32405 self.placement.estrategia — a strategy-drift would \
32406 silently split the paired `validate_placement` \
32407 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
32408 peer caixa-mesh programs.yaml `placement.estrategia` \
32409 emitter's key from the peer `feira app graph` printer's \
32410 strategy label",
32411 );
32412 assert_eq!(
32413 s.placement().clusters(),
32414 s.placement.clusters.as_slice(),
32415 "AplicacaoSpec::placement().clusters() must byte-equal \
32416 self.placement.clusters — a cluster-pool drift would \
32417 silently split the paired `validate_placement` \
32418 pre-flight `.is_empty()` refusal probe's traversal from \
32419 the peer caixa-mesh programs.yaml `placement.clusters` \
32420 emitter's fan-out from the peer `feira app graph` \
32421 printer's cluster list",
32422 );
32423 }
32424 }
32425
32426 #[test]
32427 fn validate_placement_reads_through_lifted_placement_accessor() {
32428 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
32429 // per-axis bracket-dispatch seed (`let p = self.placement();`,
32430 // followed by the per-axis fan-out `p.clusters()` /
32431 // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
32432 // lifted axis-level accessor family) must key off the lifted
32433 // outer accessor, so any future rebrand on the typed slot's
32434 // outer-composite reader shape lands at exactly one place. Pins
32435 // the multi-axis coherence by exercising each per-axis refusal
32436 // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
32437 // `:clusters` pool under the outer accessor's reference
32438 // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
32439 // strategy with a `None` `:shard-key` under the same projection,
32440 // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
32441 // with a `Some` `:shard-key` under the same projection, and
32442 // (4) the canonical `three_member_spec` `Replicated` fixture
32443 // passes `validate_placement` under the outer accessor's
32444 // reference projection — the accessor's reference-projection
32445 // reaches every per-axis branch (cluster-pool refusal, `Sharded`
32446 // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
32447 // without silently short-circuiting any.
32448 //
32449 // Peer of the sibling M3
32450 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
32451 // (534dc21) multi-axis coherence pin on the per-`:politicas`
32452 // outer mesh-policy composite-reference axis — extends the
32453 // multi-consumer coherence discipline onto the outermost M3
32454 // mesh-slot type's per-Aplicacao distribution composite-
32455 // reference axis, the second `&Composite`-return accessor on
32456 // the outer [`AplicacaoSpec`] type.
32457
32458 // (1) `PlacementWithoutClusters` refusal under the outer
32459 // accessor's reference projection: an empty `:clusters` pool
32460 // must trip the pre-flight refusal probe. The bracket-dispatch's
32461 // first arm reads `p.clusters()` on the reference returned by
32462 // the outer accessor.
32463 let mut spec = three_member_spec();
32464 spec.placement.clusters = Vec::new();
32465 assert_eq!(
32466 spec.validate().unwrap_err(),
32467 AplicacaoError::PlacementWithoutClusters {
32468 estrategia: PlacementStrategy::Replicated,
32469 },
32470 );
32471 assert!(
32472 std::ptr::eq(spec.placement(), &spec.placement),
32473 "the `validate_placement` per-axis bracket-dispatch's \
32474 traversal input must be the same backing composite the \
32475 accessor's reference projection borrows from",
32476 );
32477
32478 // (2) `ShardedWithoutKey` refusal under the outer accessor's
32479 // reference projection: a `Sharded` strategy with a `None`
32480 // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
32481 // The bracket-dispatch's third arm reads `p.estrategia()` for
32482 // the match scrutinee then `p.shard_key()` for the cascade
32483 // scrutinee, both on the reference returned by the outer
32484 // accessor.
32485 let mut spec = three_member_spec();
32486 spec.placement.estrategia = PlacementStrategy::Sharded;
32487 spec.placement.shard_key = None;
32488 assert_eq!(
32489 spec.validate().unwrap_err(),
32490 AplicacaoError::ShardedWithoutKey,
32491 );
32492
32493 // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
32494 // reference projection: a non-`Sharded` strategy with a `Some`
32495 // `:shard-key` must trip the declared-but-inert refusal. The
32496 // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
32497 // + `p.estrategia()` for the diagnostic on the reference
32498 // returned by the outer accessor.
32499 let mut spec = three_member_spec();
32500 spec.placement.estrategia = PlacementStrategy::Replicated;
32501 spec.placement.shard_key = Some("tenantId".into());
32502 assert_eq!(
32503 spec.validate().unwrap_err(),
32504 AplicacaoError::ShardKeyOnNonSharded {
32505 estrategia: PlacementStrategy::Replicated,
32506 shard_key: "tenantId".into(),
32507 },
32508 );
32509
32510 // (4) Canonical `three_member_spec` `Replicated` fixture passes
32511 // `validate_placement` — every per-axis arm reaches the fall-
32512 // through `Ok(())` without any per-axis refusal firing under the
32513 // outer accessor's reference projection.
32514 let spec = three_member_spec();
32515 assert!(
32516 spec.validate().is_ok(),
32517 "the canonical Replicated placement fixture must pass \
32518 `validate_placement` — every per-axis arm short-circuits on \
32519 valid input under the outer accessor's reference projection",
32520 );
32521 assert_eq!(
32522 spec.placement().estrategia(),
32523 PlacementStrategy::Replicated,
32524 "the outer accessor's reference projection must be the \
32525 canonical Replicated fixture's strategy",
32526 );
32527 assert_eq!(
32528 spec.placement().clusters(),
32529 &["rio", "mar"],
32530 "the outer accessor's reference projection must be the \
32531 canonical Replicated fixture's cluster pool",
32532 );
32533 }
32534
32535 #[test]
32536 fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
32537 // The canonical per-`:entrada` outer-composite-optional-
32538 // reference-shape pin: [`AplicacaoSpec::entrada`] must return
32539 // the `:entrada` typed `Option<Entrada>` verbatim as an
32540 // `Option<&Entrada>` reference over the same backing storage
32541 // the raw `self.entrada.as_ref()` field access borrows from,
32542 // byte-equal across every representative fixture in the
32543 // accept-set — the author-omitted `None` shape (the
32544 // "internal-only mesh" partition every downstream external-
32545 // gateway emitter treats as "emit nothing"), the minimal
32546 // singleton `:entrada` composite (host + destination + empty
32547 // paths + default port), the paths-carrying composite (the
32548 // canonical `three_member_spec` fixture's ["/api" "/health"]
32549 // path-list shape every HTTPRoute per-rule fan-out emitter
32550 // reads), and the non-default port composite (the canonical
32551 // custom-port shape the port-fallback resolver reads).
32552 //
32553 // Pins against a future silent detour that returned a fresh-
32554 // cloned `Entrada` copy (which would type-check via a `Clone`
32555 // impl but silently break every downstream caller that
32556 // relied on the reference sharing the composite's backing
32557 // identity), a reference to an operator-resolved overlay
32558 // (the future per-cluster `:entrada-overrides` slot the
32559 // MESH-COMPOSITION §V federation roadmap acknowledges — its
32560 // resolution must land at exactly this accessor body, not
32561 // silently divert the raw slot away from a second consumer),
32562 // a `None` → `Some(Entrada::default)` cluster-default
32563 // projection (which would collapse the load-bearing
32564 // "author-omitted `:entrada` ⇒ internal-only mesh" partition
32565 // the peer `gateway_routes` early-return + `feira app graph`
32566 // internal-only-mesh partition both read), or an axis-
32567 // shuffled projection (a future detour that swapped
32568 // `host` and `para` through the accessor would silently
32569 // split the paired `validate` per-`:entrada` shape-and-
32570 // membership gate's traversal input from the peer
32571 // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
32572 // fan-out input from the peer `feira app graph` external-
32573 // gateway summary line).
32574 //
32575 // Peer of the sibling M3
32576 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
32577 // (534dc21) `&MeshPolicy` byte-equal pin on the per-
32578 // `:politicas` outer mesh-policy composite-reference axis
32579 // and of the sibling M3
32580 // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
32581 // (9abb8f0) `&Placement` byte-equal pin on the per-
32582 // `:placement` outer distribution-composite composite-
32583 // reference axis — extends the outer-accessor byte-equal-
32584 // projection discipline onto the last unlifted outermost M3
32585 // mesh-slot type's per-Aplicacao external-gateway composite-
32586 // reference axis, the third and final `&Composite`-return
32587 // accessor on the outer [`AplicacaoSpec`] type.
32588 let fixtures: Vec<Option<Entrada>> = vec![
32589 None,
32590 Some(Entrada {
32591 host: "checkout.quero.cloud".into(),
32592 para: "cart".into(),
32593 paths: Vec::new(),
32594 port: DEFAULT_SERVICO_PORT,
32595 }),
32596 Some(Entrada {
32597 host: "checkout.quero.cloud".into(),
32598 para: "cart".into(),
32599 paths: vec!["/api".into(), "/health".into()],
32600 port: DEFAULT_SERVICO_PORT,
32601 }),
32602 Some(Entrada {
32603 host: "checkout.quero.cloud".into(),
32604 para: "cart".into(),
32605 paths: vec!["/api".into()],
32606 port: 9443,
32607 }),
32608 ];
32609 for entrada in fixtures {
32610 let s = AplicacaoSpec {
32611 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
32612 contratos: Vec::new(),
32613 politicas: MeshPolicy::default(),
32614 placement: Placement::default(),
32615 entrada: entrada.clone(),
32616 };
32617 assert_eq!(
32618 s.entrada(),
32619 entrada.as_ref(),
32620 "AplicacaoSpec::entrada must return :entrada verbatim \
32621 (got {:?}, expected {:?})",
32622 s.entrada(),
32623 entrada.as_ref(),
32624 );
32625 match (s.entrada(), s.entrada.as_ref()) {
32626 (Some(a), Some(b)) => assert!(
32627 std::ptr::eq(a, b),
32628 "AplicacaoSpec::entrada accessor and \
32629 self.entrada.as_ref() field access must borrow \
32630 the same backing storage — the accessor is the \
32631 substrate-primitive typed dispatch every \
32632 downstream external-gateway composite consumer \
32633 must route through, and a reference-identity \
32634 split would silently break every consumer that \
32635 relied on the borrow sharing the composite's \
32636 storage",
32637 ),
32638 (None, None) => {}
32639 _ => panic!(
32640 "AplicacaoSpec::entrada presence bit must byte-\
32641 equal self.entrada.is_some() — a presence-bit \
32642 drift would silently split the paired `validate` \
32643 per-`:entrada` shape-and-membership gate's \
32644 traversal head from the peer \
32645 caixa-mesh gateway_routes early-return partition \
32646 from the peer `feira app graph` internal-only-\
32647 mesh partition",
32648 ),
32649 }
32650 assert_eq!(
32651 s.entrada().is_some(),
32652 s.entrada.is_some(),
32653 "AplicacaoSpec::entrada().is_some() must byte-equal \
32654 self.entrada.is_some() — a presence-bit drift would \
32655 silently split every downstream `Option<&Entrada>` \
32656 consumer's partition on the internal-only-mesh arm",
32657 );
32658 }
32659 }
32660
32661 #[test]
32662 fn validate_reads_through_lifted_entrada_accessor() {
32663 // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
32664 // per-`:entrada` shape-and-membership gate (`if let Some(e) =
32665 // self.entrada() { … }`, followed by the per-axis fan-out
32666 // `validate_entrada_para(&e.para)` /
32667 // `EntradaMemberMissing` membership lookup /
32668 // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
32669 // per-`e.paths` `validate_entrada_path` traversal) must key
32670 // off the lifted outer accessor, so any future rebrand on
32671 // the typed slot's outer-composite reader shape lands at
32672 // exactly one place. Pins the multi-axis coherence by
32673 // exercising each per-axis refusal end-to-end: (1) the
32674 // author-omitted `None` shape short-circuits past every
32675 // per-`:entrada` refusal (the internal-only mesh partition
32676 // the accessor's `None` arm names), (2) `EntradaMemberMissing`
32677 // fires on a well-shaped but phantom `:para` under the outer
32678 // accessor's reference projection, and (3) the canonical
32679 // `three_member_spec` `:entrada` fixture passes `validate`
32680 // under the outer accessor's reference projection.
32681 //
32682 // Peer of the sibling M3
32683 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
32684 // (534dc21) multi-axis coherence pin on the per-`:politicas`
32685 // outer mesh-policy composite-reference axis and the sibling
32686 // M3
32687 // [`validate_placement_reads_through_lifted_placement_accessor`]
32688 // (9abb8f0) multi-axis coherence pin on the per-`:placement`
32689 // outer distribution-composite composite-reference axis —
32690 // extends the multi-consumer coherence discipline onto the
32691 // last unlifted outermost M3 mesh-slot type's per-Aplicacao
32692 // external-gateway composite-reference axis, the third and
32693 // final `&Composite`-return accessor on the outer
32694 // [`AplicacaoSpec`] type.
32695
32696 // (1) `None` :entrada — the internal-only-mesh partition
32697 // short-circuits past every per-`:entrada` refusal. The outer
32698 // accessor's reference projection reaches the fall-through
32699 // `Ok(())` on the `None` arm without any per-axis refusal
32700 // firing.
32701 let mut spec = three_member_spec();
32702 spec.entrada = None;
32703 assert!(
32704 spec.validate().is_ok(),
32705 "an author-omitted `:entrada` must pass `validate` — the \
32706 internal-only-mesh partition short-circuits past every \
32707 per-`:entrada` refusal under the outer accessor's \
32708 reference projection",
32709 );
32710 assert!(
32711 spec.entrada().is_none(),
32712 "the outer accessor's reference projection must name the \
32713 internal-only-mesh partition per the `None` fixture",
32714 );
32715
32716 // (2) `EntradaMemberMissing` refusal under the outer accessor's
32717 // reference projection: a well-shaped but phantom `:para` must
32718 // trip the membership-lookup refusal. The gate's second arm
32719 // reads `e.para` on the reference returned by the outer
32720 // accessor.
32721 let mut spec = three_member_spec();
32722 if let Some(e) = spec.entrada.as_mut() {
32723 e.para = "phantom".into();
32724 }
32725 assert_eq!(
32726 spec.validate().unwrap_err(),
32727 AplicacaoError::EntradaMemberMissing {
32728 para: "phantom".into(),
32729 },
32730 );
32731 match (spec.entrada(), spec.entrada.as_ref()) {
32732 (Some(a), Some(b)) => assert!(
32733 std::ptr::eq(a, b),
32734 "the `validate` per-`:entrada` gate's traversal head \
32735 must be the same backing composite the accessor's \
32736 reference projection borrows from",
32737 ),
32738 _ => panic!("fixture must carry Some(:entrada)"),
32739 }
32740
32741 // (3) Canonical `three_member_spec` `:entrada` fixture passes
32742 // `validate` — every per-axis arm reaches the fall-through
32743 // `Ok(())` without any per-axis refusal firing under the
32744 // outer accessor's reference projection.
32745 let spec = three_member_spec();
32746 assert!(
32747 spec.validate().is_ok(),
32748 "the canonical `:entrada` fixture must pass `validate` — \
32749 every per-axis arm short-circuits on valid input under \
32750 the outer accessor's reference projection",
32751 );
32752 assert!(
32753 spec.entrada().is_some(),
32754 "the outer accessor's reference projection must be the \
32755 canonical `:entrada` fixture's composite",
32756 );
32757 }
32758
32759 #[test]
32760 fn membro_names_matches_inline_membros_projection() {
32761 // Substrate-primitive ≡ inline-projection pin on
32762 // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
32763 // must be byte-for-byte the set the pre-lift inline
32764 // `self.membros().iter().map(Membro::nome).collect()` builder
32765 // produced, on every membership shape the three
32766 // Servico-name-*reference* axes (`:contratos :de`, `:contratos
32767 // :para`, `:entrada :para`) resolve against. Pins the
32768 // projection so a future rebrand of the node-identity axis
32769 // lands at the primitive rather than diverging between the
32770 // per-`:contratos` membership arms still inline at `validate`
32771 // and the lifted `validate_entrada` gate.
32772 for membros in [
32773 vec![],
32774 vec![membro("cart", "^0.1")],
32775 vec![
32776 membro("catalog", "^0.1"),
32777 membro("cart", "^0.1"),
32778 membro("payment", "^0.2"),
32779 ],
32780 ] {
32781 let mut spec = three_member_spec();
32782 spec.membros = membros;
32783 let inline: std::collections::HashSet<&str> =
32784 spec.membros().iter().map(Membro::nome).collect();
32785 assert_eq!(
32786 spec.membro_names(),
32787 inline,
32788 "the lifted membership oracle must discriminate the \
32789 same node set as the pre-lift inline projection",
32790 );
32791 }
32792 }
32793
32794 #[test]
32795 fn validate_entrada_matches_gate_on_every_per_axis_shape() {
32796 // Per-slot-gate ≡ validate equivalence pin on the lifted
32797 // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
32798 // must discriminate the same set as [`AplicacaoSpec::validate`]
32799 // on every `:entrada`-covered input, so a future consumer that
32800 // re-validates the one slot (the M4 admission webhook
32801 // re-checking `:entrada` after a gateway-host patch) accepts
32802 // exactly what `feira build` accepts and surfaces the same
32803 // diagnostic on the same input. Covers each of the five gated
32804 // axes plus the two clean-pass shapes (`None` — the
32805 // internal-only-mesh partition — and the canonical fixture).
32806 //
32807 // Peer of the sibling per-slot equivalence pins
32808 // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
32809 // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
32810 // `:politicas` slot's compound entry gate, extended here onto
32811 // the `:entrada` slot's newly-named per-slot gate.
32812 /// One `:entrada` equivalence case: a label, the per-axis
32813 /// mutation applied to the canonical fixture's composite, and
32814 /// the diagnostic both the per-slot gate and `validate` must
32815 /// surface on it (`None` = clean pass).
32816 type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
32817
32818 let cases: &[EntradaCase] = &[
32819 (
32820 ":para shape — empty",
32821 |e| e.para = String::new(),
32822 Some(AplicacaoError::EntradaParaEmpty),
32823 ),
32824 (
32825 ":para membership — well-shaped phantom",
32826 |e| e.para = "phantom".into(),
32827 Some(AplicacaoError::EntradaMemberMissing {
32828 para: "phantom".into(),
32829 }),
32830 ),
32831 (
32832 ":host emptiness",
32833 |e| e.host = String::new(),
32834 Some(AplicacaoError::EmptyEntradaHost),
32835 ),
32836 (
32837 ":port structural floor",
32838 |e| e.port = 0,
32839 Some(AplicacaoError::EntradaPortZero),
32840 ),
32841 (
32842 ":paths per-entry emptiness",
32843 |e| e.paths = vec![String::new()],
32844 Some(AplicacaoError::EntradaPathEmpty),
32845 ),
32846 (
32847 ":paths leading-slash grammar",
32848 |e| e.paths = vec!["api/cart".into()],
32849 Some(AplicacaoError::EntradaPathNotAbsolute {
32850 path: "api/cart".into(),
32851 }),
32852 ),
32853 (
32854 ":paths set-not-multiset",
32855 |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
32856 Some(AplicacaoError::EntradaPathDuplicate {
32857 path: "/api/cart".into(),
32858 }),
32859 ),
32860 ("clean pass — canonical fixture", |_| {}, None),
32861 ];
32862 for (label, mutate, expected) in cases {
32863 let mut spec = three_member_spec();
32864 mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
32865 assert_eq!(
32866 spec.validate_entrada().err(),
32867 *expected,
32868 "per-slot gate disagreed with the expected diagnostic on {label}",
32869 );
32870 assert_eq!(
32871 spec.validate().err(),
32872 *expected,
32873 "`validate` disagreed with the per-slot gate on {label}",
32874 );
32875 }
32876
32877 // The `None` arm is the internal-only-mesh partition: a clean
32878 // pass through both the per-slot gate and `validate`, not a
32879 // refusal.
32880 let mut spec = three_member_spec();
32881 spec.entrada = None;
32882 assert_eq!(spec.validate_entrada().err(), None);
32883 assert_eq!(spec.validate().err(), None);
32884 }
32885
32886 #[test]
32887 fn validate_entrada_resolves_membership_through_own_oracle() {
32888 // Self-containment pin on the lifted per-slot gate:
32889 // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
32890 // against the oracle *it* builds through
32891 // [`AplicacaoSpec::membro_names`], not one threaded down from
32892 // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
32893 // longer contains the `:entrada :para` target must trip
32894 // `EntradaMemberMissing` when the per-slot gate is called
32895 // directly — the shape a future single-slot re-validator
32896 // (the M4 admission webhook) reaches the axis through, without
32897 // re-walking `:membros` / `:contratos` / the sync-cycle
32898 // detector first. Same self-contained posture
32899 // [`AplicacaoSpec::detect_sync_cycles`] already carries for
32900 // the M4 per-edge policy resolver.
32901 let mut spec = three_member_spec();
32902 spec.membros.retain(|m| m.nome() != "cart");
32903 assert_eq!(
32904 spec.validate_entrada().unwrap_err(),
32905 AplicacaoError::EntradaMemberMissing {
32906 para: "cart".into(),
32907 },
32908 "the per-slot gate must resolve `:para` against the oracle \
32909 it builds itself, with no membership set threaded in",
32910 );
32911 assert!(
32912 !spec.membro_names().contains("cart"),
32913 "fixture must have dropped the `:entrada :para` target \
32914 from the graph's node set",
32915 );
32916 }
32917
32918 #[test]
32919 fn validate_contratos_matches_gate_on_every_per_axis_shape() {
32920 // Per-slot-gate ≡ validate equivalence pin on the lifted
32921 // [`AplicacaoSpec::validate_contratos`]: the named per-slot
32922 // gate must discriminate the same set as
32923 // [`AplicacaoSpec::validate`] on every `:contratos`-covered
32924 // input, so a future consumer that re-validates the one slot
32925 // (the M4 admission webhook re-checking `:contratos` after a
32926 // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
32927 // `:politicas` override MESH-COMPOSITION §III.2 #3
32928 // acknowledges — which resolves an effective per-edge
32929 // [`MeshPolicy`] and must re-check the edge's identity closure
32930 // before it can key a per-edge override off the endpoint
32931 // tuple) accepts exactly what `feira build` accepts and
32932 // surfaces the same diagnostic on the same input. Covers each
32933 // of the six gated axes (`:de`/`:para` per-arm shape,
32934 // per-arm graph-membership, structural self-loop, `:wit`
32935 // emptiness) plus the clean-pass canonical fixture; the
32936 // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
32937 // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
32938 // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
32939 // `target:` carriers depend on library implementation
32940 // details are pinned separately below with a `matches!`
32941 // predicate on the arm identity plus the mirror equivalence
32942 // between the two entry points.
32943 //
32944 // Peer of the sibling per-slot equivalence pins
32945 // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
32946 // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
32947 // `:politicas` slot's compound entry gate, and
32948 // `validate_entrada_matches_gate_on_every_per_axis_shape`
32949 // (20cd523) on the `:entrada` slot's per-slot gate — extended
32950 // here onto the `:contratos` slot's newly-named per-slot gate,
32951 // closing the last unlifted per-slot gate on the M3 mesh-slot
32952 // family.
32953 /// One `:contratos` equivalence case: a label, the per-axis
32954 /// mutation applied to the canonical fixture's spec, and the
32955 /// diagnostic both the per-slot gate and `validate` must
32956 /// surface on it (`None` = clean pass).
32957 type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
32958
32959 let cases: &[ContratoCase] = &[
32960 (
32961 ":de shape — empty",
32962 |s| s.contratos[0].de = String::new(),
32963 Some(AplicacaoError::ContratoCaixaEmpty {
32964 slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
32965 }),
32966 ),
32967 (
32968 ":para shape — empty",
32969 |s| s.contratos[0].para = String::new(),
32970 Some(AplicacaoError::ContratoCaixaEmpty {
32971 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
32972 }),
32973 ),
32974 (
32975 ":de membership — well-shaped phantom",
32976 |s| s.contratos[0].de = "phantom".into(),
32977 Some(AplicacaoError::ContratoMemberMissing {
32978 caixa: "phantom".into(),
32979 }),
32980 ),
32981 (
32982 ":para membership — well-shaped phantom",
32983 |s| s.contratos[0].para = "phantom".into(),
32984 Some(AplicacaoError::ContratoMemberMissing {
32985 caixa: "phantom".into(),
32986 }),
32987 ),
32988 (
32989 "structural self-loop",
32990 |s| s.contratos[0].para = "cart".into(),
32991 Some(AplicacaoError::ContratoSelfLoop {
32992 caixa: "cart".into(),
32993 wit: "wasi:http/proxy".into(),
32994 }),
32995 ),
32996 (
32997 ":wit emptiness",
32998 |s| s.contratos[0].wit = String::new(),
32999 Some(AplicacaoError::EmptyWit {
33000 de: "cart".into(),
33001 para: "catalog".into(),
33002 }),
33003 ),
33004 ("clean pass — canonical fixture", |_| {}, None),
33005 ];
33006 for (label, mutate, expected) in cases {
33007 let mut spec = three_member_spec();
33008 mutate(&mut spec);
33009 assert_eq!(
33010 spec.validate_contratos().err(),
33011 *expected,
33012 "per-slot gate disagreed with the expected diagnostic on {label}",
33013 );
33014 assert_eq!(
33015 spec.validate().err(),
33016 *expected,
33017 "`validate` disagreed with the per-slot gate on {label}",
33018 );
33019 }
33020 }
33021
33022 #[test]
33023 fn validate_contratos_matches_gate_on_reason_carrying_arms() {
33024 // Companion pin to
33025 // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
33026 // the per-slot gate ≡ `validate` equivalence on the three
33027 // `:contratos` refusal arms whose diagnostic carries a
33028 // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
33029 // and [`AplicacaoError::ContratoWrongTarget`] via the paired
33030 // `is_dns_1123_label` / `WitContract::target` shape helpers,
33031 // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
33032 // library-formatted `target:` scalar). Value equality between
33033 // the per-slot gate and `validate` outputs pins the full
33034 // `Option<AplicacaoError>` (including reason-strings), and the
33035 // per-arm `matches!` predicate pins the arm-discriminator
33036 // identity on the specific `Contrato*` variant. Split from
33037 // the primary equivalence pin so each pin body stays under
33038 // [`clippy::too_many_lines`], the same shape the peer
33039 // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
33040 // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
33041 // carries on the `:politicas` slot's compound entry gate.
33042 type ContratoReasonCase = (
33043 &'static str,
33044 fn(&mut AplicacaoSpec),
33045 fn(&AplicacaoError) -> bool,
33046 );
33047 let cases: &[ContratoReasonCase] = &[
33048 (
33049 ":de shape — DNS-1123 invalid",
33050 |s| s.contratos[0].de = "Cart".into(),
33051 |err| {
33052 matches!(
33053 err,
33054 AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
33055 if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
33056 )
33057 },
33058 ),
33059 (
33060 ":wit target-shape mismatch — payload on capability arm",
33061 |s| s.contratos[0].wit = "wasi:junk/nope".into(),
33062 |err| {
33063 matches!(
33064 err,
33065 AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
33066 if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
33067 )
33068 },
33069 ),
33070 (
33071 "whole-edge dedup — six-axis identity collision",
33072 |s| {
33073 let dup = s.contratos[0].clone();
33074 s.contratos.push(dup);
33075 },
33076 |err| {
33077 matches!(
33078 err,
33079 AplicacaoError::ContratoDuplicate { de, para, wit, .. }
33080 if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
33081 )
33082 },
33083 ),
33084 ];
33085 for (label, mutate, arm_matches) in cases {
33086 let mut spec = three_member_spec();
33087 mutate(&mut spec);
33088 let per_slot = spec.validate_contratos().err();
33089 let gate = spec.validate().err();
33090 assert_eq!(
33091 per_slot, gate,
33092 "per-slot gate and `validate` must return byte-equal \
33093 `Option<AplicacaoError>` on {label} (including \
33094 library-owned reason strings)",
33095 );
33096 let err = per_slot
33097 .as_ref()
33098 .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
33099 assert!(
33100 arm_matches(err),
33101 "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
33102 );
33103 }
33104 }
33105
33106 #[test]
33107 fn validate_contratos_resolves_membership_through_own_oracle() {
33108 // Self-containment pin on the lifted per-slot gate:
33109 // [`AplicacaoSpec::validate_contratos`] resolves each edge's
33110 // `:de` / `:para` against the oracle *it* builds through
33111 // [`AplicacaoSpec::membro_names`], not one threaded down from
33112 // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
33113 // longer contains a `:contratos` edge's endpoint must trip
33114 // `ContratoMemberMissing` when the per-slot gate is called
33115 // directly — the shape a future single-slot re-validator
33116 // (the M4 admission webhook re-checking `:contratos` after a
33117 // per-`(:de, :para)` edge patch, the M4 per-edge policy
33118 // resolver on the `:politicas` override axis) reaches the
33119 // axis through, without re-walking `:membros` / `:entrada` /
33120 // `:placement` / `:politicas` first. Same self-contained
33121 // posture the peer per-slot gates
33122 // [`AplicacaoSpec::detect_sync_cycles`] and
33123 // [`AplicacaoSpec::validate_entrada`] already carry for the
33124 // same M4 consumers.
33125 let mut spec = three_member_spec();
33126 spec.membros.retain(|m| m.nome() != "catalog");
33127 assert_eq!(
33128 spec.validate_contratos().unwrap_err(),
33129 AplicacaoError::ContratoMemberMissing {
33130 caixa: "catalog".into(),
33131 },
33132 "the per-slot gate must resolve `:de` / `:para` against \
33133 the oracle it builds itself, with no membership set \
33134 threaded in",
33135 );
33136 assert!(
33137 !spec.membro_names().contains("catalog"),
33138 "fixture must have dropped the `:contratos` edge's \
33139 `:para` target from the graph's node set",
33140 );
33141 }
33142
33143 #[test]
33144 fn validate_contratos_folds_cycle_axis_matches_gate() {
33145 // Fold-into-per-slot-gate equivalence pin on the
33146 // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
33147 // surfaces byte-equal through both
33148 // [`AplicacaoSpec::validate_contratos`] and
33149 // [`AplicacaoSpec::validate`] on a fixture whose only defect is
33150 // a synchronous-edge cycle in `:contratos`. Pins the fold that
33151 // moved the cross-edge cycle axis onto the per-slot gate — a
33152 // future silent regression that de-folded the axis back to the
33153 // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
33154 // a peer per-slot gate lift that skipped the cross-axis half of
33155 // the [`MeshPolicy::validate`]-analogous discipline) would
33156 // surface here as `Some(ContratoCycle)` from `validate` and
33157 // `None` from `validate_contratos`.
33158 //
33159 // Cycle fixture is the same shape as the peer
33160 // [`rejects_three_node_synchronous_cycle`] test carries: a
33161 // clean 3-cycle over the HTTP subgraph (catalog → cart →
33162 // payment → catalog), so the per-entry cascade (shape +
33163 // membership + self-loop + `:wit` emptiness + WIT-target +
33164 // whole-edge dedup) passes cleanly and the sole surviving
33165 // refusal shape is the cross-edge cycle axis. The `cycle`
33166 // vector is normalized to a sorted body set for the equality
33167 // compare (the traversal path's starting node depends on
33168 // BTreeMap iteration order, which is deterministic but is not
33169 // the load-bearing property this pin covers).
33170 //
33171 // Peer of the sibling per-slot ≡ `validate` equivalence pins
33172 // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
33173 // (per-entry axes) and
33174 // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
33175 // (parser-owned reason arms) already carry on the six
33176 // per-entry axes — this extends the discipline onto the
33177 // cross-edge cycle axis newly folded into the per-slot gate,
33178 // matching the peer per-slot compound gate
33179 // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
33180 // both per-axis and cross-axis surfaces on `:politicas`.
33181 let mut spec = three_member_spec();
33182 spec.contratos = vec![
33183 contract_http("catalog", "cart", "/x"),
33184 contract_http("cart", "payment", "/y"),
33185 contract_http("payment", "catalog", "/z"),
33186 ];
33187 let per_slot_err = spec.validate_contratos().unwrap_err();
33188 let gate_err = spec.validate().unwrap_err();
33189 assert_eq!(
33190 per_slot_err, gate_err,
33191 "the per-slot gate and `validate` must return byte-equal \
33192 `AplicacaoError::ContratoCycle` on a cycle-only fixture \
33193 — the fold pins the cross-edge axis onto the per-slot \
33194 gate the same way the peer `validate_politicas` fold \
33195 pinned the `:politicas` cross-axis surface",
33196 );
33197 match per_slot_err {
33198 AplicacaoError::ContratoCycle { ref cycle } => {
33199 assert_eq!(
33200 cycle.first(),
33201 cycle.last(),
33202 "cycle traversal must close on the back-edge \
33203 target — the diagnostic shape the peer \
33204 `rejects_three_node_synchronous_cycle` pins",
33205 );
33206 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
33207 assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
33208 assert!(body.contains("cart"));
33209 assert!(body.contains("catalog"));
33210 assert!(body.contains("payment"));
33211 }
33212 other => panic!("expected ContratoCycle, got {other:?}"),
33213 }
33214 }
33215
33216 #[test]
33217 fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
33218 // Diagnostic-ordering pin on the fold: a `:contratos` fixture
33219 // carrying *both* a per-entry defect (a self-loop, the
33220 // structural-self-edge arm on the per-entry cascade — chosen
33221 // because it never masks or is masked by the cycle diagnostic
33222 // on the peer arms) *and* a would-be synchronous-edge cycle in
33223 // the remaining edges must surface the per-entry diagnostic
33224 // first through both [`AplicacaoSpec::validate_contratos`] and
33225 // [`AplicacaoSpec::validate`] — pinning the fold's canonical
33226 // per-entry-before-cross-edge dispatch ordering, byte-equal to
33227 // the pre-fold `validate`-side sequence
33228 // (`validate_contratos()? → detect_sync_cycles()?`) the
33229 // dispatch encoded verbatim. A silent regression that reversed
33230 // the ordering inside the fold would surface here as a cycle
33231 // diagnostic on a fixture carrying an earlier per-entry defect
33232 // — masking the narrower "this edge is degenerate" arm behind
33233 // the coarser "this graph deadlocks" arm.
33234 //
33235 // Peer of the diagnostic-ordering property the pre-fold
33236 // dispatch encoded at the [`AplicacaoSpec::validate`]
33237 // altitude (`validate_contratos()? → detect_sync_cycles()?`),
33238 // now enforced inside the per-slot gate's own body, so a future
33239 // consumer that reaches only the per-slot gate (the M4
33240 // admission webhook re-checking `:contratos` after a per-edge
33241 // patch) inherits the ordering property by construction.
33242 let mut spec = three_member_spec();
33243 // The three-member fixture already has cart → catalog and
33244 // cart → payment; adding catalog → cart closes a 2-cycle on
33245 // the HTTP subgraph.
33246 spec.contratos
33247 .push(contract_http("catalog", "cart", "/refresh"));
33248 // Add a self-loop on `payment` — the per-entry structural-
33249 // self-edge arm — which must surface first.
33250 spec.contratos
33251 .push(contract_http("payment", "payment", "/loop"));
33252 let per_slot_err = spec.validate_contratos().unwrap_err();
33253 let gate_err = spec.validate().unwrap_err();
33254 assert_eq!(
33255 per_slot_err, gate_err,
33256 "per-slot gate and `validate` must agree on the ordering \
33257 fixture's surfaced diagnostic — a divergence here means \
33258 the fold reshaped one dispatch's ordering without the \
33259 other",
33260 );
33261 assert!(
33262 matches!(
33263 per_slot_err,
33264 AplicacaoError::ContratoSelfLoop { ref caixa, .. }
33265 if caixa == "payment"
33266 ),
33267 "the per-entry structural-self-edge arm must fire before \
33268 the cross-edge cycle arm — pinning the fold's per-entry-\
33269 before-cross-edge dispatch ordering byte-equal to the \
33270 pre-fold `validate_contratos()? → detect_sync_cycles()?` \
33271 sequence; got {per_slot_err:?}",
33272 );
33273 }
33274
33275 #[test]
33276 fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
33277 // Self-containment pin on the folded cross-edge cycle axis:
33278 // [`AplicacaoSpec::validate_contratos`] surfaces
33279 // [`AplicacaoError::ContratoCycle`] directly against `&self`
33280 // without depending on the peer per-slot gates
33281 // ([`AplicacaoSpec::validate_membros`],
33282 // [`AplicacaoSpec::validate_entrada`],
33283 // [`AplicacaoSpec::validate_placement`],
33284 // [`AplicacaoSpec::validate_politicas`]) running first — the
33285 // shape a future single-slot re-validator (the M4 admission
33286 // webhook re-checking `:contratos` after a per-`(:de, :para)`
33287 // edge patch, the per-edge policy resolver MESH-COMPOSITION
33288 // §III.2 #3 acknowledges) reaches *both* structural axes on
33289 // the slot through one call. A spec with a per-`:politicas`
33290 // refusal shape (zero `:timeout`, the first per-axis arm the
33291 // peer [`MeshPolicy::validate`] gate covers) AND a
33292 // synchronous-edge cycle in `:contratos` must:
33293 //
33294 // - surface [`AplicacaoError::ContratoCycle`] through the
33295 // per-slot gate `validate_contratos` directly (proves the
33296 // cycle axis reaches the per-slot altitude without the
33297 // peer `:politicas` gate running first);
33298 // - surface [`AplicacaoError::ContratoCycle`] through
33299 // `validate` (which reaches `validate_contratos` before
33300 // `validate_politicas` per the fixed dispatch order), so
33301 // the fold's cross-slot ordering (`:membros` →
33302 // `:contratos` → `:entrada` → `:placement` → `:politicas`)
33303 // is byte-equal to the pre-fold dispatch's ordering.
33304 //
33305 // Same self-contained-on-`&self` posture the peer per-slot
33306 // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
33307 // [`AplicacaoSpec::validate_contratos`] per-entry axis
33308 // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
33309 // (f03a154) already carry — extended here onto the newly-
33310 // folded cross-edge cycle axis. Peer of the sibling per-slot
33311 // self-containment pins
33312 // `validate_entrada_resolves_membership_through_own_oracle`
33313 // and `validate_contratos_resolves_membership_through_own_oracle`
33314 // on the per-entry membership axis — extends the discipline
33315 // onto the cross-edge cycle axis of the same per-slot gate.
33316 let mut spec = three_member_spec();
33317 // Poison `:politicas` — zero-`:timeout` trips the first per-
33318 // axis arm the [`MeshPolicy::validate`] gate covers, so any
33319 // dispatch that reached `:politicas` would surface a
33320 // `:politicas` diagnostic instead of `ContratoCycle`.
33321 spec.politicas.timeout = Some(Duration::from_secs(0));
33322 // Close a synchronous-edge cycle on the HTTP subgraph.
33323 spec.contratos
33324 .push(contract_http("catalog", "cart", "/refresh"));
33325 let per_slot_err = spec.validate_contratos().unwrap_err();
33326 assert!(
33327 matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
33328 "the per-slot gate must surface `ContratoCycle` directly \
33329 against `&self` — a peer per-slot gate's regression \
33330 would surface a non-`ContratoCycle` diagnostic here; \
33331 got {per_slot_err:?}",
33332 );
33333 let gate_err = spec.validate().unwrap_err();
33334 assert!(
33335 matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
33336 "`validate`'s five-slot dispatch must reach the fold's \
33337 cross-edge cycle axis on `:contratos` before the peer \
33338 `:politicas` gate — a dispatch-order regression would \
33339 surface a `:politicas` diagnostic here; got {gate_err:?}",
33340 );
33341 // Sanity: the poisoned `:politicas` alone would trip
33342 // [`MeshPolicy::validate`] under the peer per-slot gate, so
33343 // the cycle-first surfacing above is a real ordering property,
33344 // not a case where the `:politicas` axis silently accepts the
33345 // fixture.
33346 let mut politicas_only = three_member_spec();
33347 politicas_only.politicas.timeout = Some(Duration::from_secs(0));
33348 assert!(
33349 politicas_only.validate_politicas().is_err(),
33350 "the poisoned `:politicas` fixture must trip the peer \
33351 per-slot gate on its own — otherwise the self-contained \
33352 cycle-first surfacing above would not be an ordering \
33353 property",
33354 );
33355 }
33356
33357 #[test]
33358 fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
33359 // Fail-before-pass-after equivalence pin on the lifted
33360 // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
33361 // both arms (`:de` phantom and `:para` phantom) must fire the
33362 // `AplicacaoError::ContratoMemberMissing` diagnostic with a
33363 // `caixa` carrier byte-equal to the offending accessor's
33364 // projection, and `:de` must fire before `:para` when both
33365 // arms would trip on the same call — preserving the canonical
33366 // edge-direction order the peer per-arm shape gate
33367 // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
33368 // diagnostic, and every peer per-arm ordering in
33369 // [`AplicacaoSpec::validate_contratos`] already carry.
33370 //
33371 // Two-endpoint oracle covers exactly enough graph nodes to
33372 // exercise each arm in isolation: the `:de` arm fires when
33373 // the source is off-oracle and the destination is on-oracle,
33374 // the `:para` arm fires when the source is on-oracle and the
33375 // destination is off-oracle, and the `:de`-before-`:para`
33376 // ordering falls out from a probe where *both* endpoints are
33377 // off-oracle — the diagnostic's `caixa` field must byte-equal
33378 // the source, not the destination, pinning the primitive's
33379 // arm ordering as `:de` first.
33380 let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
33381 names.insert("cart");
33382 names.insert("catalog");
33383
33384 // `:de` phantom, `:para` on-oracle
33385 let de_phantom = contract_http("phantom-de", "catalog", "/x");
33386 let err = de_phantom.require_endpoints_in(&names).unwrap_err();
33387 assert_eq!(
33388 err,
33389 AplicacaoError::ContratoMemberMissing {
33390 caixa: de_phantom.source().to_string(),
33391 },
33392 "the `:de` phantom arm must fire ContratoMemberMissing \
33393 with `caixa` byte-equal to `WitContract::source` — a \
33394 bypass here (a raw `.de.clone()` regression, a divergent \
33395 accessor on a per-CR alias table) would silently split \
33396 the primitive's diagnostic from the substrate-primitive \
33397 scalar accessor every downstream consumer routes through",
33398 );
33399
33400 // `:de` on-oracle, `:para` phantom
33401 let para_phantom = contract_http("cart", "phantom-para", "/x");
33402 let err = para_phantom.require_endpoints_in(&names).unwrap_err();
33403 assert_eq!(
33404 err,
33405 AplicacaoError::ContratoMemberMissing {
33406 caixa: para_phantom.destination().to_string(),
33407 },
33408 "the `:para` phantom arm must fire ContratoMemberMissing \
33409 with `caixa` byte-equal to `WitContract::destination` — \
33410 symmetric callee-side pin to the `:de` arm above",
33411 );
33412
33413 // Both endpoints off-oracle: the `:de` arm must fire first,
33414 // pinning the primitive's canonical edge-direction order.
33415 let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
33416 let err = both_phantom.require_endpoints_in(&names).unwrap_err();
33417 assert_eq!(
33418 err,
33419 AplicacaoError::ContratoMemberMissing {
33420 caixa: both_phantom.source().to_string(),
33421 },
33422 "when both endpoints are off-oracle, the `:de` arm must \
33423 fire before the `:para` arm — preserving byte-equal \
33424 ordering with the pre-lift inline cascade in \
33425 `validate_contratos` and with every peer per-arm \
33426 ordering the sibling per-edge substrate primitives \
33427 already carry",
33428 );
33429
33430 // Both endpoints on-oracle: clean pass.
33431 let clean = contract_http("cart", "catalog", "/x");
33432 clean.require_endpoints_in(&names).unwrap();
33433 }
33434
33435 #[test]
33436 fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
33437 // Convergence pin: the whole-spec end-to-end route through
33438 // [`AplicacaoSpec::validate_contratos`] must reach the
33439 // per-edge substrate primitive
33440 // [`WitContract::require_endpoints_in`] on every membership
33441 // arm — the diagnostic fired at the per-slot altitude must
33442 // byte-equal the diagnostic the primitive fires when called
33443 // directly on the same edge and the same oracle. Pins the
33444 // primitive as the sole load-bearing gate on the membership
33445 // axis, so any future silent detour that re-inlined the twin
33446 // `if !names.contains(...)` cascade back into the per-slot
33447 // gate (a rebase-artifact regression, an M4 admission-webhook
33448 // consumer that bypassed the primitive) would surface here as
33449 // a byte-equal miss between the two dispatches.
33450 //
33451 // Same equivalence-pin discipline the peer
33452 // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
33453 // pin already carries on the per-slot gate ≡ `validate` axis,
33454 // extended here onto the per-slot gate ≡ per-edge primitive
33455 // axis at one altitude deeper.
33456 for phantom_edge in [
33457 contract_http("phantom-de", "catalog", "/x"),
33458 contract_http("cart", "phantom-para", "/x"),
33459 ] {
33460 let mut spec = three_member_spec();
33461 spec.contratos.push(phantom_edge.clone());
33462 let per_slot_err = spec.validate_contratos().unwrap_err();
33463 let primitive_err = phantom_edge
33464 .require_endpoints_in(&spec.membro_names())
33465 .unwrap_err();
33466 assert_eq!(
33467 per_slot_err, primitive_err,
33468 "the per-slot gate must reach the per-edge substrate \
33469 primitive on every membership arm — a bypass here \
33470 would silently split the two dispatches on the \
33471 same edge + same oracle input",
33472 );
33473 // And the diagnostic's `caixa` carrier must byte-equal
33474 // the offending accessor's projection at both altitudes,
33475 // pinning the accessor routing across the whole-spec
33476 // path.
33477 let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
33478 panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
33479 };
33480 let expected = if spec.membro_names().contains(phantom_edge.source()) {
33481 phantom_edge.destination()
33482 } else {
33483 phantom_edge.source()
33484 };
33485 assert_eq!(
33486 caixa, expected,
33487 "the whole-spec ContratoMemberMissing.caixa carrier \
33488 must byte-equal the offending edge's accessor \
33489 projection — a bypass here would silently split \
33490 the wrap envelope's `caixa` field from the \
33491 substrate-primitive scalar accessor every \
33492 downstream consumer routes through",
33493 );
33494 }
33495 }
33496
33497 #[test]
33498 fn port_for_destination_reads_through_lifted_entrada_accessor() {
33499 // Peer coherence pin: the
33500 // [`AplicacaoSpec::port_for_destination`] per-destination
33501 // L4-port fallback resolver's composite-projection seed
33502 // (`self.entrada().filter(…).map_or(…)`) must key off the
33503 // lifted outer accessor. Pins the coherence by exercising
33504 // the resolver end-to-end: (1) the `None` `:entrada` shape
33505 // falls through to `DEFAULT_SERVICO_PORT` under the outer
33506 // accessor's reference projection, (2) a non-matching
33507 // destination falls through to `DEFAULT_SERVICO_PORT` under
33508 // the outer accessor's reference projection, and (3) the
33509 // matching destination resolves to the `:entrada :port`
33510 // value under the outer accessor's reference projection.
33511 //
33512 // Peer of the sibling
33513 // [`validate_reads_through_lifted_entrada_accessor`] multi-
33514 // consumer coherence pin on the same per-`:entrada` outer-
33515 // composite axis — extends the multi-consumer coherence
33516 // discipline onto the second per-`:entrada` production
33517 // consumer, the L4-port fallback resolver.
33518
33519 // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
33520 // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
33521 // arm under the outer accessor's reference projection.
33522 let mut spec = three_member_spec();
33523 spec.entrada = None;
33524 assert_eq!(
33525 spec.port_for_destination("cart"),
33526 DEFAULT_SERVICO_PORT,
33527 "the port-fallback resolver must fall through to \
33528 DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
33529 under the outer accessor's reference projection",
33530 );
33531
33532 // (2) Non-matching destination — the resolver's `filter(…)`
33533 // arm rejects a mismatched destination and falls through
33534 // to `DEFAULT_SERVICO_PORT` under the outer accessor's
33535 // reference projection.
33536 let mut spec = three_member_spec();
33537 if let Some(e) = spec.entrada.as_mut() {
33538 e.para = "cart".into();
33539 e.port = 9443;
33540 }
33541 assert_eq!(
33542 spec.port_for_destination("catalog"),
33543 DEFAULT_SERVICO_PORT,
33544 "the port-fallback resolver must fall through to \
33545 DEFAULT_SERVICO_PORT on a non-matching destination \
33546 under the outer accessor's reference projection",
33547 );
33548
33549 // (3) Matching destination — the resolver's `map_or(…)` arm
33550 // returns the `:entrada :port` value under the outer
33551 // accessor's reference projection.
33552 let mut spec = three_member_spec();
33553 if let Some(e) = spec.entrada.as_mut() {
33554 e.para = "cart".into();
33555 e.port = 9443;
33556 }
33557 assert_eq!(
33558 spec.port_for_destination("cart"),
33559 9443,
33560 "the port-fallback resolver must return the \
33561 `:entrada :port` value on a matching destination \
33562 under the outer accessor's reference projection",
33563 );
33564 }
33565
33566 #[test]
33567 fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
33568 // The canonical per-`:politicas` `:mtls-required` mTLS-
33569 // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
33570 // must return the `:politicas :mtls-required` typed bool
33571 // verbatim as an `Option<bool>`, byte-equal to the raw field
33572 // access across every value in the three-way accept-set —
33573 // `None` (cluster default applies), `Some(true)` (mTLS
33574 // handshake enforced — the sandboxing-by-default arm the
33575 // MeshPolicy's docstring names), `Some(false)` (handshake
33576 // skipped — the explicit debug-edge opt-out).
33577 //
33578 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
33579 // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
33580 // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
33581 // shape — first `Option<Copy-T>`-return accessor on the M3
33582 // mesh-slot family. Pins against a future silent detour that
33583 // re-derived the toggle from a peer axis (an accidental
33584 // `.circuit_breaker.is_some()` collapse that assumed mTLS on
33585 // whenever a breaker is set), a `None` → `Some(false)` cluster-
33586 // default projection (the canonical `Option<bool>` → `bool`
33587 // collapse footgun the surrounding `is_empty()` predicate
33588 // guards on the peer emptiness axis), or a `Some(true)` /
33589 // `Some(false)` variant swap that landed on one consumer
33590 // without the other.
33591 for required in [None, Some(true), Some(false)] {
33592 let p = MeshPolicy {
33593 mtls_required: required,
33594 ..MeshPolicy::default()
33595 };
33596 assert_eq!(
33597 p.mtls_required(),
33598 required,
33599 "MeshPolicy::mtls_required must return :politicas \
33600 :mtls-required verbatim (got {:?}, expected {required:?})",
33601 p.mtls_required(),
33602 );
33603 assert_eq!(
33604 p.mtls_required(),
33605 p.mtls_required,
33606 "MeshPolicy::mtls_required must byte-equal the raw \
33607 .mtls_required field access across every value in the \
33608 three-way accept-set",
33609 );
33610 }
33611 }
33612
33613 #[test]
33614 fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
33615 // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
33616 // arm must key off [`MeshPolicy::mtls_required`], not the raw
33617 // `.mtls_required` field access. Structurally: toggling ONLY
33618 // the `mtls_required` slot on an otherwise-default MeshPolicy
33619 // must flip `is_empty()` from `true` (all-`None`) to `false`
33620 // (one axis carries a value); the flip must be observed for
33621 // both `Some(true)` and `Some(false)` since the emptiness
33622 // semantic reads "any axis carries a value" — not "any axis
33623 // carries a truthy value" — the same non-collapsing shape the
33624 // sibling M2 [`crate::LimitsSpec::is_empty`] /
33625 // [`crate::BehaviorSpec::is_empty`] predicates carry on their
33626 // peer `Option<T>`-typed slot surfaces.
33627 //
33628 // Pins against a future silent detour that re-derived the
33629 // emptiness predicate off a peer axis (an accidental
33630 // `.rate_limit.is_none()`-only chain that dropped the
33631 // `mtls_required` arm entirely), a `mtls_required == Some(_)`
33632 // collapse to a truthy-only check (which would silently
33633 // classify `Some(false)` as empty), or an accessor-side
33634 // detour that no longer names the substrate-primitive typed
33635 // dispatch (an accidental `self.mtls_required.unwrap_or(false)
33636 // == false` fallback in the accessor that would silently
33637 // classify both `None` and `Some(false)` as the same value).
33638 //
33639 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
33640 // (7cd2a28) accessor-composition pin on the sibling optional-
33641 // scalar axis — same "the emptiness / shape-gate predicate
33642 // must route through the substrate-primitive typed dispatch"
33643 // discipline extended onto the peer per-`:politicas` emptiness
33644 // predicate.
33645 let empty = MeshPolicy::default();
33646 assert!(
33647 empty.is_empty(),
33648 "MeshPolicy::default() must be is_empty() — every axis \
33649 defaults to None",
33650 );
33651 for required in [Some(true), Some(false)] {
33652 let p = MeshPolicy {
33653 mtls_required: required,
33654 ..MeshPolicy::default()
33655 };
33656 assert!(
33657 !p.is_empty(),
33658 "MeshPolicy::is_empty must return false when \
33659 :mtls-required is {required:?} — the emptiness \
33660 predicate reads \"any axis carries a value\", not \
33661 \"any axis carries a truthy value\"",
33662 );
33663 assert_eq!(
33664 p.mtls_required().is_none(),
33665 p.is_empty(),
33666 "when :mtls-required is the only set axis, \
33667 is_empty() must equal mtls_required().is_none() — \
33668 the accessor and the emptiness predicate must \
33669 route through the same substrate-primitive typed \
33670 dispatch on the :mtls-required arm",
33671 );
33672 }
33673 }
33674
33675 #[test]
33676 fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
33677 // The by-copy pin: [`MeshPolicy::mtls_required`] returns
33678 // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
33679 // accessor must return by value, not by reference. Peer of the
33680 // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
33681 // borrow-invariant pin on the sibling `Option<String>` slot,
33682 // but extended onto the peer `Option<bool>` copy-invariant
33683 // shape — the accessor's returned `Option<bool>` must outlive
33684 // `&self` (multiple calls must return equal values from a
33685 // dropped-`&self` copy, since the returned Option carries no
33686 // borrow), and calling the accessor twice on the same
33687 // MeshPolicy must yield the same `Option<bool>` verbatim
33688 // (idempotent, no side effects on `&self`).
33689 //
33690 // Pins against a future silent detour that returned
33691 // `Option<&bool>` (which would type-check but silently break
33692 // every downstream caller — [`single_field_overlay`]'s first
33693 // parameter is `Option<T: Clone>`, and `&bool` would fold to a
33694 // detached copy at the call site), an accidental
33695 // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
33696 // would also type-check but return `Option<&bool>`), or a
33697 // one-arm-only accessor that reads `Some(*b)` in the Some arm
33698 // but reads a fresh Default::default() in the None arm.
33699 for required in [None, Some(true), Some(false)] {
33700 let p = MeshPolicy {
33701 mtls_required: required,
33702 ..MeshPolicy::default()
33703 };
33704 let first = p.mtls_required();
33705 let second = p.mtls_required();
33706 assert_eq!(
33707 first, second,
33708 "MeshPolicy::mtls_required must be idempotent — two \
33709 successive calls on the same &self must return the \
33710 same Option<bool>",
33711 );
33712 assert_eq!(
33713 first, required,
33714 "MeshPolicy::mtls_required must return :politicas \
33715 :mtls-required verbatim by copy — got {first:?}, \
33716 expected {required:?}",
33717 );
33718 }
33719 }
33720
33721 #[test]
33722 fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
33723 // The canonical per-`:politicas` `:retries` transient-failure-
33724 // retry-budget scalar pin: [`MeshPolicy::retries`] must return
33725 // the `:politicas :retries` typed `u32` verbatim as an
33726 // `Option<u32>`, byte-equal to the raw field access across every
33727 // representative value in the accept-set — `None` (cluster
33728 // default applies — typically "no retries beyond a single
33729 // dispatch attempt" the caixa-mesh `retry_overlay` builder
33730 // documents), `Some(1)` (the lower boundary of the
33731 // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
33732 // `AplicacaoSpec::validate_politicas` gate carves out on the
33733 // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
33734 // (the upper boundary the same gate carves out on the sibling
33735 // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
33736 // past-the-guard sentinel that pins the accessor doesn't perform
33737 // a silent bounds-collapse at the return path).
33738 //
33739 // Sibling of the peer per-`:politicas`
33740 // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
33741 // sibling `Option<Copy-T>` optional-scalar axis, extended to the
33742 // peer per-`:politicas` `Option<u32>` shape — second
33743 // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
33744 // Pins against a future silent detour that re-derived the retry
33745 // cap from a peer axis (an accidental `.circuit_breaker
33746 // .as_ref().map(|b| b.max_failures)` collapse that read the
33747 // breaker's max-failure count as a retry budget), a
33748 // `None → Some(0)` cluster-default projection (which would
33749 // silently re-introduce the `PolicyRetriesZero` refusal case at
33750 // the emit boundary), or a bounds-collapsing accessor that
33751 // clamped the return through `POLICY_RETRIES_MAX` (the
33752 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
33753 // must ship the raw slot verbatim so a validate-time gate
33754 // regression surfaces at the emit boundary rather than being
33755 // silently absorbed).
33756 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
33757 let p = MeshPolicy {
33758 retries,
33759 ..MeshPolicy::default()
33760 };
33761 assert_eq!(
33762 p.retries(),
33763 retries,
33764 "MeshPolicy::retries must return :politicas :retries \
33765 verbatim (got {:?}, expected {retries:?})",
33766 p.retries(),
33767 );
33768 assert_eq!(
33769 p.retries(),
33770 p.retries,
33771 "MeshPolicy::retries must byte-equal the raw .retries \
33772 field access across every value in the accept-set",
33773 );
33774 }
33775 }
33776
33777 #[test]
33778 fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
33779 // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
33780 // must key off [`MeshPolicy::retries`], not the raw `.retries`
33781 // field access. Structurally: toggling ONLY the `retries` slot
33782 // on an otherwise-default MeshPolicy must flip `is_empty()`
33783 // from `true` (all-`None`) to `false` (one axis carries a
33784 // value); the flip must be observed for every value in the
33785 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
33786 // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
33787 // the emptiness semantic reads "any axis carries a value" —
33788 // not "any axis carries a value the validate gate accepts" —
33789 // the same non-collapsing shape the peer M2
33790 // [`crate::LimitsSpec::is_empty`] /
33791 // [`crate::BehaviorSpec::is_empty`] predicates carry.
33792 //
33793 // Pins against a future silent detour that re-derived the
33794 // emptiness predicate off a peer axis (an accidental
33795 // `.rate_limit.is_none()`-only chain that dropped the
33796 // `retries` arm entirely), a `retries == Some(_)` collapse
33797 // that key-off a validate-gate-clamped bounds check (which
33798 // would silently classify a past-the-guard `Some(u32::MAX)`
33799 // as empty because it fails the `1..=POLICY_RETRIES_MAX`
33800 // check), or an accessor-side detour that no longer names the
33801 // substrate-primitive typed dispatch.
33802 //
33803 // Sibling of the peer per-`:politicas`
33804 // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
33805 // pin on the sibling `Option<Copy-T>` optional-scalar axis —
33806 // same "the emptiness predicate must route through the
33807 // substrate-primitive typed dispatch" discipline extended onto
33808 // the peer per-`:politicas` `Option<u32>` axis.
33809 let empty = MeshPolicy::default();
33810 assert!(
33811 empty.is_empty(),
33812 "MeshPolicy::default() must be is_empty() — every axis \
33813 defaults to None",
33814 );
33815 for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
33816 let p = MeshPolicy {
33817 retries,
33818 ..MeshPolicy::default()
33819 };
33820 assert!(
33821 !p.is_empty(),
33822 "MeshPolicy::is_empty must return false when \
33823 :retries is {retries:?} — the emptiness \
33824 predicate reads \"any axis carries a value\", not \
33825 \"any axis carries a value the validate gate \
33826 accepts\"",
33827 );
33828 assert_eq!(
33829 p.retries().is_none(),
33830 p.is_empty(),
33831 "when :retries is the only set axis, is_empty() \
33832 must equal retries().is_none() — the accessor and \
33833 the emptiness predicate must route through the same \
33834 substrate-primitive typed dispatch on the :retries \
33835 arm",
33836 );
33837 }
33838 }
33839
33840 #[test]
33841 fn mesh_policy_retries_projects_option_u32_by_copy() {
33842 // The by-copy pin: [`MeshPolicy::retries`] returns
33843 // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
33844 // accessor must return by value, not by reference. Sibling of
33845 // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
33846 // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
33847 // extended onto the sibling `Option<u32>` copy-invariant
33848 // shape — the accessor's returned `Option<u32>` must outlive
33849 // `&self` (multiple calls must return equal values from a
33850 // dropped-`&self` copy, since the returned Option carries no
33851 // borrow), and calling the accessor twice on the same
33852 // MeshPolicy must yield the same `Option<u32>` verbatim
33853 // (idempotent, no side effects on `&self`).
33854 //
33855 // Pins against a future silent detour that returned
33856 // `Option<&u32>` (which would type-check but silently break
33857 // every downstream caller — [`crate::render::single_field_overlay`]'s
33858 // first parameter is `Option<T: Clone>`, and `&u32` would
33859 // fold to a detached copy at the call site), an accidental
33860 // `Option::as_ref()` projection (`self.retries.as_ref()` would
33861 // also type-check but return `Option<&u32>`), or a one-arm-
33862 // only accessor that reads `Some(*n)` in the Some arm but
33863 // reads a fresh `Default::default()` (`0_u32`) in the None
33864 // arm.
33865 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
33866 let p = MeshPolicy {
33867 retries,
33868 ..MeshPolicy::default()
33869 };
33870 let first = p.retries();
33871 let second = p.retries();
33872 assert_eq!(
33873 first, second,
33874 "MeshPolicy::retries must be idempotent — two \
33875 successive calls on the same &self must return the \
33876 same Option<u32>",
33877 );
33878 assert_eq!(
33879 first, retries,
33880 "MeshPolicy::retries must return :politicas :retries \
33881 verbatim by copy — got {first:?}, expected {retries:?}",
33882 );
33883 }
33884 }
33885
33886 #[test]
33887 fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
33888 // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
33889 // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
33890 // return the `:politicas :timeout` typed [`Duration`] verbatim
33891 // as an `Option<Duration>`, byte-equal to the raw field access
33892 // across every representative value in the accept-set — `None`
33893 // (cluster default applies — typically the gateway class's
33894 // implementation-side per-request wall-clock cap the caixa-mesh
33895 // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
33896 // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
33897 // set the surrounding `AplicacaoSpec::validate_politicas` gate
33898 // carves out on the sibling `PolicyTimeoutZero` /
33899 // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
33900 // (the upper boundary the same gate carves out on the sibling
33901 // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
33902 // (a past-the-guard sentinel that pins the accessor doesn't
33903 // perform a silent bounds-collapse into `None` on the zero-
33904 // Duration arm — validate rejects zero but the accessor must
33905 // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
33906 // past-the-guard sentinel that pins the accessor doesn't
33907 // perform a silent bounds-collapse at the return path).
33908 //
33909 // Sibling of the peer per-`:politicas`
33910 // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
33911 // `Option<u32>` optional-scalar axis and the peer per-
33912 // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
33913 // pin on the sibling `Option<bool>` optional-scalar axis,
33914 // extended onto the peer per-`:politicas` `Option<Duration>`
33915 // shape — third `Option<Copy-T>`-return accessor on the M3
33916 // mesh-slot family. Pins against a future silent detour that
33917 // re-derived the per-call cap from a peer axis (an accidental
33918 // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
33919 // read the breaker's rolling-window duration as a per-call
33920 // deadline), a `None → Some(Duration::MAX)` cluster-default
33921 // projection (which would silently re-introduce the
33922 // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
33923 // blocking" arm at the emit boundary), or a bounds-collapsing
33924 // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
33925 // (the `AplicacaoSpec::validate` gate owns the bounds; the
33926 // accessor must ship the raw slot verbatim so a validate-time
33927 // gate regression surfaces at the emit boundary rather than
33928 // being silently absorbed).
33929 for timeout in [
33930 None,
33931 Some(Duration::from_millis(1)),
33932 Some(POLICY_TIMEOUT_MAX),
33933 Some(Duration::ZERO),
33934 Some(Duration::MAX),
33935 ] {
33936 let p = MeshPolicy {
33937 timeout,
33938 ..MeshPolicy::default()
33939 };
33940 assert_eq!(
33941 p.timeout(),
33942 timeout,
33943 "MeshPolicy::timeout must return :politicas :timeout \
33944 verbatim (got {:?}, expected {timeout:?})",
33945 p.timeout(),
33946 );
33947 assert_eq!(
33948 p.timeout(),
33949 p.timeout,
33950 "MeshPolicy::timeout must byte-equal the raw .timeout \
33951 field access across every value in the accept-set",
33952 );
33953 }
33954 }
33955
33956 #[test]
33957 fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
33958 // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
33959 // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
33960 // field access. Structurally: toggling ONLY the `timeout` slot
33961 // on an otherwise-default MeshPolicy must flip `is_empty()`
33962 // from `true` (all-`None`) to `false` (one axis carries a
33963 // value); the flip must be observed for every value in the
33964 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
33965 // gate accepts (`Some(Duration::from_millis(1))`,
33966 // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
33967 // reads "any axis carries a value" — not "any axis carries a
33968 // value the validate gate accepts" — the same non-collapsing
33969 // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
33970 // [`crate::BehaviorSpec::is_empty`] predicates carry.
33971 //
33972 // Pins against a future silent detour that re-derived the
33973 // emptiness predicate off a peer axis (an accidental
33974 // `.rate_limit.is_none()`-only chain that dropped the
33975 // `timeout` arm entirely), a `timeout == Some(_)` collapse
33976 // that key-off a validate-gate-clamped bounds check (which
33977 // would silently classify a past-the-guard `Some(Duration::MAX)`
33978 // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
33979 // check), or an accessor-side detour that no longer names the
33980 // substrate-primitive typed dispatch.
33981 //
33982 // Sibling of the peer per-`:politicas`
33983 // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
33984 // the sibling `Option<u32>` optional-scalar axis and the peer
33985 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
33986 // accessor-composition pin on the sibling `Option<bool>`
33987 // optional-scalar axis — same "the emptiness predicate must
33988 // route through the substrate-primitive typed dispatch"
33989 // discipline extended onto the peer per-`:politicas`
33990 // `Option<Duration>` axis.
33991 let empty = MeshPolicy::default();
33992 assert!(
33993 empty.is_empty(),
33994 "MeshPolicy::default() must be is_empty() — every axis \
33995 defaults to None",
33996 );
33997 for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
33998 let p = MeshPolicy {
33999 timeout,
34000 ..MeshPolicy::default()
34001 };
34002 assert!(
34003 !p.is_empty(),
34004 "MeshPolicy::is_empty must return false when \
34005 :timeout is {timeout:?} — the emptiness \
34006 predicate reads \"any axis carries a value\", not \
34007 \"any axis carries a value the validate gate \
34008 accepts\"",
34009 );
34010 assert_eq!(
34011 p.timeout().is_none(),
34012 p.is_empty(),
34013 "when :timeout is the only set axis, is_empty() \
34014 must equal timeout().is_none() — the accessor and \
34015 the emptiness predicate must route through the same \
34016 substrate-primitive typed dispatch on the :timeout \
34017 arm",
34018 );
34019 }
34020 }
34021
34022 #[test]
34023 fn mesh_policy_timeout_projects_option_duration_by_copy() {
34024 // The by-copy pin: [`MeshPolicy::timeout`] returns
34025 // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
34026 // and the accessor must return by value, not by reference.
34027 // Sibling of the peer per-`:politicas`
34028 // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
34029 // sibling `Option<u32>` optional-scalar axis and the peer
34030 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
34031 // by-copy pin on the sibling `Option<bool>` optional-scalar
34032 // axis, extended onto the peer per-`:politicas`
34033 // `Option<Duration>` copy-invariant shape — the accessor's
34034 // returned `Option<Duration>` must outlive `&self` (multiple
34035 // calls must return equal values from a dropped-`&self`
34036 // copy, since the returned Option carries no borrow), and
34037 // calling the accessor twice on the same MeshPolicy must
34038 // yield the same `Option<Duration>` verbatim (idempotent, no
34039 // side effects on `&self`).
34040 //
34041 // Pins against a future silent detour that returned
34042 // `Option<&Duration>` (which would type-check but silently
34043 // break every downstream caller — [`crate::render::single_field_overlay`]'s
34044 // first parameter is `Option<T: Clone>`, and `&Duration`
34045 // would fold to a detached copy at the call site), an
34046 // accidental `Option::as_ref()` projection
34047 // (`self.timeout.as_ref()` would also type-check but return
34048 // `Option<&Duration>`), or a one-arm-only accessor that
34049 // reads `Some(*d)` in the Some arm but reads a fresh
34050 // `Default::default()` (`Duration::ZERO`) in the None arm
34051 // (which would silently re-classify every unset `:timeout`
34052 // as the `PolicyTimeoutZero`-refused zero-Duration value at
34053 // the accessor boundary).
34054 for timeout in [
34055 None,
34056 Some(Duration::from_millis(1)),
34057 Some(POLICY_TIMEOUT_MAX),
34058 Some(Duration::ZERO),
34059 Some(Duration::MAX),
34060 ] {
34061 let p = MeshPolicy {
34062 timeout,
34063 ..MeshPolicy::default()
34064 };
34065 let first = p.timeout();
34066 let second = p.timeout();
34067 assert_eq!(
34068 first, second,
34069 "MeshPolicy::timeout must be idempotent — two \
34070 successive calls on the same &self must return the \
34071 same Option<Duration>",
34072 );
34073 assert_eq!(
34074 first, timeout,
34075 "MeshPolicy::timeout must return :politicas :timeout \
34076 verbatim by copy — got {first:?}, expected {timeout:?}",
34077 );
34078 }
34079 }
34080
34081 #[test]
34082 fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
34083 // The canonical per-`:politicas` `:rate-limit` Envoy-
34084 // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
34085 // [`MeshPolicy::rate_limit`] must return the `:politicas
34086 // :rate-limit` typed [`RateLimit`] verbatim as an
34087 // `Option<RateLimit>`, byte-equal to the raw field access
34088 // across every representative value in the accept-set — `None`
34089 // (cluster default applies — no per-Aplicacao rate declaration,
34090 // the gateway-class per-listener default arm the future caixa-
34091 // mesh `local_rate_limit_overlay` emitter documents),
34092 // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
34093 // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
34094 // accept-set the surrounding
34095 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
34096 // sibling `PolicyRateLimitZero` refusal, paired with the
34097 // canonical-window "1 second" arm of the three-unit
34098 // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
34099 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
34100 // (the upper boundary the same gate carves out on the sibling
34101 // `PolicyRateLimitExceedsCap` refusal, paired with the
34102 // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
34103 // (a past-the-guard sentinel that pins the accessor doesn't
34104 // perform a silent bounds-collapse into `None` on the
34105 // zero-rate/zero-window arm — validate rejects zero but the
34106 // accessor must ship the raw slot verbatim so a validate-time
34107 // gate regression surfaces at the emit boundary rather than
34108 // being silently absorbed), and
34109 // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
34110 // (a past-the-guard sentinel that pins the accessor doesn't
34111 // perform a silent bounds-collapse at the return path).
34112 //
34113 // First `Option<Copy-composite-T>`-return accessor pin on the
34114 // M3 mesh-slot family (peer of the sibling per-`:politicas`
34115 // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
34116 // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
34117 // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
34118 // Copy accessor pins, extended onto the peer per-`:politicas`
34119 // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
34120 // and the accessor returns by value). Pins against a future
34121 // silent detour that re-derived the rate declaration from a
34122 // peer axis (an accidental
34123 // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
34124 // collapse that read the breaker's trip threshold + rolling
34125 // window as a rate declaration), a `None → Some(default())`
34126 // cluster-default projection (which would silently re-
34127 // introduce a "cluster default is 0/s" arm the emit boundary
34128 // would take as "declared but inert" — the canonical
34129 // declared-but-inert footgun the sibling
34130 // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
34131 // amplification-shape axis), a bounds-collapsing accessor
34132 // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
34133 // clamped `rl.window` through [`is_canonical_rate_limit_window`]
34134 // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
34135 // accessor must ship the raw slot verbatim), or a
34136 // by-reference detour (`Option<&RateLimit>`) that broke every
34137 // downstream consumer keying off `Option<RateLimit>` by-copy.
34138 for rl in [
34139 None,
34140 Some(RateLimit {
34141 rate: 1,
34142 window: Duration::from_secs(1),
34143 }),
34144 Some(RateLimit {
34145 rate: POLICY_RATE_LIMIT_MAX,
34146 window: Duration::from_secs(3600),
34147 }),
34148 Some(RateLimit {
34149 rate: 0,
34150 window: Duration::ZERO,
34151 }),
34152 Some(RateLimit {
34153 rate: u32::MAX,
34154 window: Duration::MAX,
34155 }),
34156 ] {
34157 let p = MeshPolicy {
34158 rate_limit: rl,
34159 ..MeshPolicy::default()
34160 };
34161 assert_eq!(
34162 p.rate_limit(),
34163 rl,
34164 "MeshPolicy::rate_limit must return :politicas :rate-limit \
34165 verbatim (got {:?}, expected {rl:?})",
34166 p.rate_limit(),
34167 );
34168 assert_eq!(
34169 p.rate_limit(),
34170 p.rate_limit,
34171 "MeshPolicy::rate_limit must byte-equal the raw \
34172 .rate_limit field access across every value in the \
34173 accept-set",
34174 );
34175 }
34176 }
34177
34178 #[test]
34179 fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
34180 // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
34181 // must key off [`MeshPolicy::rate_limit`], not the raw
34182 // `.rate_limit` field access. Structurally: toggling ONLY the
34183 // `rate_limit` slot on an otherwise-default MeshPolicy must
34184 // flip `is_empty()` from `true` (all-`None`) to `false` (one
34185 // axis carries a value); the flip must be observed for every
34186 // representative value in the accept-set the surrounding
34187 // [`AplicacaoSpec::validate_politicas`] gate accepts
34188 // (`Some(RateLimit { rate: 1, window: 1s })`,
34189 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
34190 // since the emptiness semantic reads "any axis carries a
34191 // value" — not "any axis carries a value the validate gate
34192 // accepts" — the same non-collapsing shape the peer M2
34193 // [`crate::LimitsSpec::is_empty`] /
34194 // [`crate::BehaviorSpec::is_empty`] predicates carry.
34195 //
34196 // Pins against a future silent detour that re-derived the
34197 // emptiness predicate off a peer axis (an accidental
34198 // `.timeout.is_none()`-only chain that dropped the
34199 // `rate_limit` arm entirely — the last unlifted inline field
34200 // access on `is_empty` before this lift), a `rate_limit ==
34201 // Some(_)` collapse that key-off a validate-gate-clamped
34202 // bounds check (which would silently classify a past-the-
34203 // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
34204 // because it fails the value-shape gate), or an accessor-
34205 // side detour that no longer names the substrate-primitive
34206 // typed dispatch.
34207 //
34208 // Fourth "the emptiness predicate must route through the
34209 // substrate-primitive typed dispatch" composition pin on the
34210 // M3 mesh-slot family — closes the last unlifted composition
34211 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
34212 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
34213 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
34214 // 7073d0f is_empty-composition pins on the sibling primitive-
34215 // Copy axes, extended onto the peer per-`:politicas`
34216 // composite-Copy `Option<RateLimit>` axis).
34217 let empty = MeshPolicy::default();
34218 assert!(
34219 empty.is_empty(),
34220 "MeshPolicy::default() must be is_empty() — every axis \
34221 defaults to None",
34222 );
34223 for rl in [
34224 RateLimit {
34225 rate: 1,
34226 window: Duration::from_secs(1),
34227 },
34228 RateLimit {
34229 rate: POLICY_RATE_LIMIT_MAX,
34230 window: Duration::from_secs(3600),
34231 },
34232 ] {
34233 let p = MeshPolicy {
34234 rate_limit: Some(rl),
34235 ..MeshPolicy::default()
34236 };
34237 assert!(
34238 !p.is_empty(),
34239 "MeshPolicy::is_empty must return false when \
34240 :rate-limit is {rl:?} — the emptiness predicate \
34241 reads \"any axis carries a value\", not \"any axis \
34242 carries a value the validate gate accepts\"",
34243 );
34244 assert_eq!(
34245 p.rate_limit().is_none(),
34246 p.is_empty(),
34247 "when :rate-limit is the only set axis, is_empty() \
34248 must equal rate_limit().is_none() — the accessor \
34249 and the emptiness predicate must route through the \
34250 same substrate-primitive typed dispatch on the \
34251 :rate-limit arm",
34252 );
34253 }
34254 }
34255
34256 #[test]
34257 fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
34258 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
34259 // `:rate-limit` value-shape gate must key off
34260 // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
34261 // field bind. Structurally: a `MeshPolicy` whose only set
34262 // axis is a `Some(RateLimit { rate: 0, .. })` must surface
34263 // the `PolicyRateLimitZero` refusal exactly, and the same
34264 // MeshPolicy with the rate at the canonical lower boundary
34265 // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
34266 // The pair jointly pins the accessor + validate-gate
34267 // composition: any future silent detour that had the accessor
34268 // omit the `Some(RateLimit { rate: 0, .. })` arm (a
34269 // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
34270 // silently absorb the `PolicyRateLimitZero` refusal at the
34271 // accessor boundary — the composition pin catches that at
34272 // caixa-core build time.
34273 //
34274 // Sibling of the peer [`validate_politicas`]
34275 // `:mtls-required` / `:retries` / `:timeout` composition pins
34276 // on the sibling primitive-Copy optional-scalar axes — same
34277 // "the validate / shape-gate predicate must route through the
34278 // substrate-primitive typed dispatch" discipline extended
34279 // onto the peer per-`:politicas` composite-Copy
34280 // `Option<RateLimit>` axis. Second composition-with-accessor
34281 // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
34282 // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
34283 let mut spec = three_member_spec();
34284 spec.politicas = MeshPolicy {
34285 rate_limit: Some(RateLimit {
34286 rate: 0,
34287 window: Duration::from_secs(1),
34288 }),
34289 ..MeshPolicy::default()
34290 };
34291 assert!(
34292 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
34293 "validate_politicas must reject rate == 0 with \
34294 PolicyRateLimitZero — the accessor and the validate gate \
34295 must route through the same substrate-primitive typed \
34296 dispatch on the :rate-limit zero-floor arm",
34297 );
34298 spec.politicas = MeshPolicy {
34299 rate_limit: Some(RateLimit {
34300 rate: 1,
34301 window: Duration::from_secs(1),
34302 }),
34303 ..MeshPolicy::default()
34304 };
34305 assert!(
34306 spec.validate().is_ok(),
34307 "validate_politicas must accept rate == 1 (the canonical \
34308 lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
34309 set) with a canonical 1s window",
34310 );
34311 }
34312
34313 #[test]
34314 fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
34315 // The canonical per-`:politicas` `:circuit-breaker` Envoy-
34316 // `outlier_detection`-mesh consecutive-failure-ejection scalar
34317 // pin: [`MeshPolicy::circuit_breaker`] must return the
34318 // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
34319 // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
34320 // raw field access across every representative value in the
34321 // accept-set — `None` (cluster default applies — no
34322 // per-Aplicacao breaker declaration, the gateway-class per-
34323 // listener default arm the future caixa-mesh
34324 // `outlier_detection_overlay` emitter documents),
34325 // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
34326 // (the lower boundary of the accept-set the surrounding
34327 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
34328 // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
34329 // refusals),
34330 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
34331 // (the upper boundary the same gate carves out on the sibling
34332 // `PolicyBreakerMaxFailuresExceedsCap` /
34333 // `PolicyBreakerWindowExceedsCap` refusals),
34334 // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
34335 // (a past-the-guard sentinel that pins the accessor doesn't
34336 // perform a silent bounds-collapse into `None` on the
34337 // zero-failures/zero-window arm — validate rejects zero but
34338 // the accessor must ship the raw slot verbatim so a validate-
34339 // time gate regression surfaces at the emit boundary rather
34340 // than being silently absorbed), and
34341 // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
34342 // (a past-the-guard sentinel that pins the accessor doesn't
34343 // perform a silent bounds-collapse at the return path).
34344 //
34345 // Second `Option<Copy-composite-T>`-return accessor pin on the
34346 // M3 mesh-slot family (peer of the sibling per-`:politicas`
34347 // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
34348 // composite-Copy accessor pin, and of the sibling per-
34349 // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
34350 // [`MeshPolicy::retries`] bdfb399 /
34351 // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
34352 // accessor pins). Pins against a future silent detour that
34353 // re-derived the breaker declaration from a peer axis (an
34354 // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
34355 // collapse that read the rate-limit's bucket capacity + refill
34356 // period as a breaker declaration), a `None → Some(default())`
34357 // cluster-default projection (which would silently re-
34358 // introduce the `PolicyBreakerZeroFailures` /
34359 // `PolicyBreakerZeroWindow` refusal cases at the emit
34360 // boundary), a bounds-collapsing accessor that clamped
34361 // `cb.max_failures` through
34362 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
34363 // through [`POLICY_BREAKER_WINDOW_MAX`] (the
34364 // [`AplicacaoSpec::validate`] gate owns the bounds; the
34365 // accessor must ship the raw slot verbatim), or a
34366 // by-reference detour (`Option<&CircuitBreaker>`) that broke
34367 // every downstream consumer keying off `Option<CircuitBreaker>`
34368 // by-copy.
34369 for cb in [
34370 None,
34371 Some(CircuitBreaker {
34372 max_failures: 1,
34373 window: Duration::from_millis(1),
34374 }),
34375 Some(CircuitBreaker {
34376 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
34377 window: POLICY_BREAKER_WINDOW_MAX,
34378 }),
34379 Some(CircuitBreaker {
34380 max_failures: 0,
34381 window: Duration::ZERO,
34382 }),
34383 Some(CircuitBreaker {
34384 max_failures: u32::MAX,
34385 window: Duration::MAX,
34386 }),
34387 ] {
34388 let p = MeshPolicy {
34389 circuit_breaker: cb,
34390 ..MeshPolicy::default()
34391 };
34392 assert_eq!(
34393 p.circuit_breaker(),
34394 cb,
34395 "MeshPolicy::circuit_breaker must return :politicas \
34396 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
34397 p.circuit_breaker(),
34398 );
34399 assert_eq!(
34400 p.circuit_breaker(),
34401 p.circuit_breaker,
34402 "MeshPolicy::circuit_breaker must byte-equal the raw \
34403 .circuit_breaker field access across every value in \
34404 the accept-set",
34405 );
34406 }
34407 }
34408
34409 #[test]
34410 fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
34411 // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
34412 // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
34413 // `.circuit_breaker` field access. Structurally: toggling ONLY
34414 // the `circuit_breaker` slot on an otherwise-default MeshPolicy
34415 // must flip `is_empty()` from `true` (all-`None`) to `false`
34416 // (one axis carries a value); the flip must be observed for
34417 // every representative value in the accept-set the surrounding
34418 // [`AplicacaoSpec::validate_politicas`] gate accepts
34419 // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
34420 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
34421 // since the emptiness semantic reads "any axis carries a
34422 // value" — not "any axis carries a value the validate gate
34423 // accepts" — the same non-collapsing shape the peer M2
34424 // [`crate::LimitsSpec::is_empty`] /
34425 // [`crate::BehaviorSpec::is_empty`] predicates carry.
34426 //
34427 // Pins against a future silent detour that re-derived the
34428 // emptiness predicate off a peer axis (an accidental
34429 // `.rate_limit.is_none()`-only chain that dropped the
34430 // `circuit_breaker` arm entirely — the last unlifted inline
34431 // field access on `is_empty` before this lift), a
34432 // `circuit_breaker == Some(_)` collapse that key-off a
34433 // validate-gate-clamped bounds check (which would silently
34434 // classify a past-the-guard `Some(CircuitBreaker { max_failures:
34435 // 0, window: 0s })` as empty because it fails the value-shape
34436 // gate), or an accessor-side detour that no longer names the
34437 // substrate-primitive typed dispatch.
34438 //
34439 // Fifth "the emptiness predicate must route through the
34440 // substrate-primitive typed dispatch" composition pin on the
34441 // M3 mesh-slot family — closes the last unlifted composition
34442 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
34443 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
34444 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
34445 // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
34446 // composition pins on the sibling primitive-Copy + composite-
34447 // Copy axes, extended onto the peer per-`:politicas`
34448 // composite-Copy `Option<CircuitBreaker>` axis).
34449 let empty = MeshPolicy::default();
34450 assert!(
34451 empty.is_empty(),
34452 "MeshPolicy::default() must be is_empty() — every axis \
34453 defaults to None",
34454 );
34455 for cb in [
34456 CircuitBreaker {
34457 max_failures: 1,
34458 window: Duration::from_millis(1),
34459 },
34460 CircuitBreaker {
34461 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
34462 window: POLICY_BREAKER_WINDOW_MAX,
34463 },
34464 ] {
34465 let p = MeshPolicy {
34466 circuit_breaker: Some(cb),
34467 ..MeshPolicy::default()
34468 };
34469 assert!(
34470 !p.is_empty(),
34471 "MeshPolicy::is_empty must return false when \
34472 :circuit-breaker is {cb:?} — the emptiness predicate \
34473 reads \"any axis carries a value\", not \"any axis \
34474 carries a value the validate gate accepts\"",
34475 );
34476 assert_eq!(
34477 p.circuit_breaker().is_none(),
34478 p.is_empty(),
34479 "when :circuit-breaker is the only set axis, \
34480 is_empty() must equal circuit_breaker().is_none() — \
34481 the accessor and the emptiness predicate must route \
34482 through the same substrate-primitive typed dispatch \
34483 on the :circuit-breaker arm",
34484 );
34485 }
34486 }
34487
34488 #[test]
34489 fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
34490 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
34491 // `:circuit-breaker` value-shape gate must key off
34492 // [`MeshPolicy::circuit_breaker`], not the raw
34493 // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
34494 // whose only set axis is a `Some(CircuitBreaker { max_failures:
34495 // 0, .. })` must surface the `PolicyBreakerZeroFailures`
34496 // refusal exactly, and the same MeshPolicy with the breaker at
34497 // the canonical lower boundary
34498 // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
34499 // pass validate. The pair jointly pins the accessor +
34500 // validate-gate composition: any future silent detour that had
34501 // the accessor omit the `Some(CircuitBreaker { max_failures:
34502 // 0, .. })` arm (a
34503 // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
34504 // collapse) would silently absorb the
34505 // `PolicyBreakerZeroFailures` refusal at the accessor
34506 // boundary — the composition pin catches that at caixa-core
34507 // build time.
34508 //
34509 // Sibling of the peer [`validate_politicas`]
34510 // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
34511 // composition pins on the sibling primitive-Copy + composite-
34512 // Copy optional-scalar axes — same "the validate / shape-gate
34513 // predicate must route through the substrate-primitive typed
34514 // dispatch" discipline extended onto the peer per-`:politicas`
34515 // composite-Copy `Option<CircuitBreaker>` axis. Second
34516 // composition-with-accessor pin on the M3 mesh-slot
34517 // `Option<CircuitBreaker>` arm alongside the
34518 // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
34519 let mut spec = three_member_spec();
34520 spec.politicas = MeshPolicy {
34521 circuit_breaker: Some(CircuitBreaker {
34522 max_failures: 0,
34523 window: Duration::from_millis(1),
34524 }),
34525 ..MeshPolicy::default()
34526 };
34527 assert!(
34528 matches!(
34529 spec.validate(),
34530 Err(AplicacaoError::PolicyBreakerZeroFailures)
34531 ),
34532 "validate_politicas must reject max_failures == 0 with \
34533 PolicyBreakerZeroFailures — the accessor and the validate \
34534 gate must route through the same substrate-primitive \
34535 typed dispatch on the :circuit-breaker zero-floor arm",
34536 );
34537 spec.politicas = MeshPolicy {
34538 circuit_breaker: Some(CircuitBreaker {
34539 max_failures: 1,
34540 window: Duration::from_millis(1),
34541 }),
34542 ..MeshPolicy::default()
34543 };
34544 assert!(
34545 spec.validate().is_ok(),
34546 "validate_politicas must accept a CircuitBreaker at the \
34547 canonical lower boundary (max_failures = 1, window = \
34548 1ms) — the accessor and the validate gate must route \
34549 through the same substrate-primitive typed dispatch on \
34550 the :circuit-breaker arm",
34551 );
34552 }
34553
34554 #[test]
34555 fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
34556 // The canonical per-`:politicas :circuit-breaker` `:max-failures`
34557 // Envoy-outlier-detection trip-threshold scalar pin:
34558 // [`CircuitBreaker::max_failures`] must return the
34559 // `:politicas :circuit-breaker :max-failures` typed `u32`
34560 // verbatim, byte-equal to the raw field access across every
34561 // representative value in the accept-set — `1` (the lower
34562 // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
34563 // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
34564 // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
34565 // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
34566 // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
34567 // refusal), `0` (a past-the-guard sentinel that pins the accessor
34568 // doesn't perform a silent bounds-collapse into `1` on the zero
34569 // arm — validate rejects zero but the accessor must ship the
34570 // raw slot verbatim so a validate-time gate regression surfaces
34571 // at the emit boundary rather than being silently absorbed),
34572 // `u32::MAX` (a past-the-guard sentinel that pins the accessor
34573 // doesn't perform a silent bounds-collapse through
34574 // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
34575 //
34576 // First sub-struct required-scalar accessor pin on the M3
34577 // mesh-slot family — sibling in shape to the peer per-`:membros`
34578 // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
34579 // (a40b0e3) required-`String`-carry accessor pins and the peer
34580 // per-`:contratos` [`WitContract::source`] /
34581 // [`WitContract::destination`] (7f0fd43) required-`String`-carry
34582 // accessor pins, extended onto the peer per-`CircuitBreaker`
34583 // required-`u32` scalar-value axis. Pins against a future silent
34584 // detour that re-derived the trip threshold from a peer axis (an
34585 // accidental `self.window.as_secs() as u32` collapse that read
34586 // the breaker's rolling-window duration as a failure count), a
34587 // `0 → 1` cluster-default projection (which would silently absorb
34588 // the `PolicyBreakerZeroFailures` refusal case at the accessor
34589 // boundary), or a bounds-collapsing accessor that clamped the
34590 // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
34591 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
34592 // must ship the raw slot verbatim).
34593 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
34594 let cb = CircuitBreaker {
34595 max_failures,
34596 window: Duration::from_secs(60),
34597 };
34598 assert_eq!(
34599 cb.max_failures(),
34600 max_failures,
34601 "CircuitBreaker::max_failures must return :politicas \
34602 :circuit-breaker :max-failures verbatim (got {}, \
34603 expected {max_failures})",
34604 cb.max_failures(),
34605 );
34606 assert_eq!(
34607 cb.max_failures(),
34608 cb.max_failures,
34609 "CircuitBreaker::max_failures must byte-equal the raw \
34610 .max_failures field access across every value in the \
34611 u32 accept-set",
34612 );
34613 }
34614 }
34615
34616 #[test]
34617 fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
34618 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
34619 // `:circuit-breaker :max-failures` zero-floor arm must key off
34620 // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
34621 // field access. Structurally: a `CircuitBreaker { max_failures:
34622 // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
34623 // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
34624 // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
34625 // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
34626 // pass validate. The pair jointly pins the accessor +
34627 // validate-gate composition: any future silent detour that had
34628 // the accessor return a fresh `1` on the zero arm (a
34629 // `.max_failures().max(1)` collapse) would silently absorb the
34630 // `PolicyBreakerZeroFailures` refusal at the accessor boundary
34631 // and the validate gate would accept a struct-literal
34632 // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
34633 // catches that at caixa-core build time.
34634 //
34635 // Peer of the sibling per-`:politicas`
34636 // [`MeshPolicy::mtls_required`] (c0110f1) /
34637 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
34638 // (7073d0f) accessor-composition pins on the sibling optional-
34639 // scalar axes — same "the validate / shape-gate predicate must
34640 // route through the substrate-primitive typed dispatch"
34641 // discipline extended onto the peer per-`CircuitBreaker`
34642 // required-scalar composition axis.
34643 let mut spec = three_member_spec();
34644 spec.politicas = MeshPolicy {
34645 circuit_breaker: Some(CircuitBreaker {
34646 max_failures: 0,
34647 window: Duration::from_secs(60),
34648 }),
34649 ..MeshPolicy::default()
34650 };
34651 assert!(
34652 matches!(
34653 spec.validate(),
34654 Err(AplicacaoError::PolicyBreakerZeroFailures)
34655 ),
34656 "validate_politicas must reject max_failures == 0 with \
34657 PolicyBreakerZeroFailures — the accessor and the validate \
34658 gate must route through the same substrate-primitive typed \
34659 dispatch on the :max-failures zero-floor arm",
34660 );
34661 spec.politicas = MeshPolicy {
34662 circuit_breaker: Some(CircuitBreaker {
34663 max_failures: 1,
34664 window: Duration::from_secs(60),
34665 }),
34666 ..MeshPolicy::default()
34667 };
34668 assert!(
34669 spec.validate().is_ok(),
34670 "validate_politicas must accept max_failures == 1 (the \
34671 lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
34672 accept-set)",
34673 );
34674 }
34675
34676 #[test]
34677 fn circuit_breaker_max_failures_projects_u32_by_copy() {
34678 // The by-copy pin: [`CircuitBreaker::max_failures`] returns
34679 // `u32` by copy — `u32` is `Copy` and the accessor must return
34680 // by value, not by reference. Peer of the sibling
34681 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
34682 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
34683 // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
34684 // optional-scalar axes, extended onto the peer
34685 // per-`CircuitBreaker` required-`u32` copy-invariant shape —
34686 // the accessor's returned `u32` must outlive `&self` (multiple
34687 // calls must return equal values from a dropped-`&self` copy,
34688 // since the returned scalar carries no borrow), and calling
34689 // the accessor twice on the same CircuitBreaker must yield the
34690 // same `u32` verbatim (idempotent, no side effects on `&self`).
34691 //
34692 // Pins against a future silent detour that returned `&u32`
34693 // (which would type-check but silently break every downstream
34694 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
34695 // first parameter is `u32`, and `&u32` would fold to a detached
34696 // copy at the call site with a `*` deref the sibling accessors
34697 // don't need), an accidental `.max_failures.wrapping_add(0)`
34698 // detour that returned a fresh copy through an arithmetic
34699 // no-op (breaking a future `const fn` regression), or a
34700 // one-arm-only accessor that returned a saturating value on
34701 // some sentinel input (breaking the pass-through invariant the
34702 // sibling required-scalar accessors carry).
34703 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
34704 let cb = CircuitBreaker {
34705 max_failures,
34706 window: Duration::from_secs(60),
34707 };
34708 let first = cb.max_failures();
34709 let second = cb.max_failures();
34710 assert_eq!(
34711 first, second,
34712 "CircuitBreaker::max_failures must be idempotent — two \
34713 successive calls on the same &self must return the \
34714 same u32",
34715 );
34716 assert_eq!(
34717 first, max_failures,
34718 "CircuitBreaker::max_failures must return :politicas \
34719 :circuit-breaker :max-failures verbatim by copy — \
34720 got {first}, expected {max_failures}",
34721 );
34722 }
34723 }
34724
34725 #[test]
34726 fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
34727 // The canonical per-`:politicas :circuit-breaker` `:window`
34728 // Envoy-outlier-detection rolling-observation-interval scalar
34729 // pin: [`CircuitBreaker::window`] must return the
34730 // `:politicas :circuit-breaker :window` typed `Duration`
34731 // verbatim, byte-equal to the raw field access across every
34732 // representative value in the accept-set — `Duration::from_millis(1)`
34733 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
34734 // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
34735 // gate carves out on the sibling `PolicyBreakerZeroWindow`
34736 // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
34737 // same gate carves out on the sibling
34738 // `PolicyBreakerWindowExceedsCap` refusal),
34739 // `Duration::ZERO` (a past-the-guard sentinel that pins the
34740 // accessor doesn't perform a silent bounds-collapse into
34741 // `Duration::from_millis(1)` on the zero arm — validate rejects
34742 // zero but the accessor must ship the raw slot verbatim so a
34743 // validate-time gate regression surfaces at the emit boundary
34744 // rather than being silently absorbed),
34745 // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
34746 // far above the 1h cap — that pins the accessor doesn't perform
34747 // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
34748 // at the return path).
34749 //
34750 // Second sub-struct required-scalar accessor pin on the M3
34751 // mesh-slot family — sibling in shape to the just-landed
34752 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
34753 // (3a74062) required-`u32` accessor pin on the peer
34754 // per-`CircuitBreaker` required-axis, extended onto the
34755 // per-sub-struct required-`Duration` axis. Pins against a
34756 // future silent detour that re-derived the observation window
34757 // from a peer axis (an accidental
34758 // `Duration::from_secs(self.max_failures as u64)` collapse that
34759 // read the breaker's trip count as an observation-interval
34760 // duration), a `Duration::ZERO → Duration::from_millis(1)`
34761 // cluster-default projection (which would silently absorb the
34762 // `PolicyBreakerZeroWindow` refusal case at the accessor
34763 // boundary), or a bounds-collapsing accessor that clamped the
34764 // return through `POLICY_BREAKER_WINDOW_MAX` (the
34765 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
34766 // must ship the raw slot verbatim).
34767 for window in [
34768 Duration::from_millis(1),
34769 POLICY_BREAKER_WINDOW_MAX,
34770 Duration::ZERO,
34771 Duration::from_secs(86_400),
34772 ] {
34773 let cb = CircuitBreaker {
34774 max_failures: 5,
34775 window,
34776 };
34777 assert_eq!(
34778 cb.window(),
34779 window,
34780 "CircuitBreaker::window must return :politicas \
34781 :circuit-breaker :window verbatim (got {:?}, \
34782 expected {window:?})",
34783 cb.window(),
34784 );
34785 assert_eq!(
34786 cb.window(),
34787 cb.window,
34788 "CircuitBreaker::window must byte-equal the raw \
34789 .window field access across every value in the \
34790 Duration accept-set",
34791 );
34792 }
34793 }
34794
34795 #[test]
34796 fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
34797 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
34798 // `:circuit-breaker :window` zero-floor arm must key off
34799 // [`CircuitBreaker::window`], not the raw `.window` field
34800 // access. Structurally: a `CircuitBreaker { window:
34801 // Duration::ZERO, .. }` embedded in a
34802 // `:politicas :circuit-breaker` slot must surface the
34803 // `PolicyBreakerZeroWindow` refusal exactly, and a
34804 // `CircuitBreaker { window: Duration::from_millis(1), .. }`
34805 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
34806 // accept-set) must pass validate. The pair jointly pins the
34807 // accessor + validate-gate composition: any future silent
34808 // detour that had the accessor return a fresh
34809 // `Duration::from_millis(1)` on the zero arm (a
34810 // `.window().max(Duration::from_millis(1))` collapse) would
34811 // silently absorb the `PolicyBreakerZeroWindow` refusal at the
34812 // accessor boundary and the validate gate would accept a
34813 // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
34814 // — the composition pin catches that at caixa-core build time.
34815 //
34816 // Peer of the sibling per-`CircuitBreaker`
34817 // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
34818 // pin on the peer required-scalar `:max-failures` axis — same
34819 // "the validate / shape-gate predicate must route through the
34820 // substrate-primitive typed dispatch" discipline extended onto
34821 // the peer per-`CircuitBreaker` required-`Duration` composition
34822 // axis.
34823 let mut spec = three_member_spec();
34824 spec.politicas = MeshPolicy {
34825 circuit_breaker: Some(CircuitBreaker {
34826 max_failures: 5,
34827 window: Duration::ZERO,
34828 }),
34829 ..MeshPolicy::default()
34830 };
34831 assert!(
34832 matches!(
34833 spec.validate(),
34834 Err(AplicacaoError::PolicyBreakerZeroWindow)
34835 ),
34836 "validate_politicas must reject window == Duration::ZERO \
34837 with PolicyBreakerZeroWindow — the accessor and the \
34838 validate gate must route through the same substrate-\
34839 primitive typed dispatch on the :window zero-floor arm",
34840 );
34841 spec.politicas = MeshPolicy {
34842 circuit_breaker: Some(CircuitBreaker {
34843 max_failures: 5,
34844 window: Duration::from_millis(1),
34845 }),
34846 ..MeshPolicy::default()
34847 };
34848 assert!(
34849 spec.validate().is_ok(),
34850 "validate_politicas must accept window == \
34851 Duration::from_millis(1) (the lower boundary of the \
34852 1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
34853 );
34854 }
34855
34856 #[test]
34857 fn circuit_breaker_window_projects_duration_by_copy() {
34858 // The by-copy pin: [`CircuitBreaker::window`] returns
34859 // `Duration` by copy — `Duration` is `Copy` and the accessor
34860 // must return by value, not by reference. Peer of the sibling
34861 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
34862 // (3a74062) by-copy pin on the peer required-scalar
34863 // `:max-failures` axis, extended onto the peer
34864 // per-`CircuitBreaker` required-`Duration` copy-invariant shape
34865 // — the accessor's returned `Duration` must outlive `&self`
34866 // (multiple calls must return equal values from a
34867 // dropped-`&self` copy, since the returned scalar carries no
34868 // borrow), and calling the accessor twice on the same
34869 // CircuitBreaker must yield the same `Duration` verbatim
34870 // (idempotent, no side effects on `&self`).
34871 //
34872 // Pins against a future silent detour that returned
34873 // `&Duration` (which would type-check but silently break every
34874 // downstream `Duration`-by-value consumer —
34875 // [`crate::render::require_positive_canonical_bounded_duration`]'s
34876 // first parameter is `Duration`, and `&Duration` would fold to
34877 // a detached copy at the call site with a `*` deref the sibling
34878 // accessors don't need), an accidental `.window + Duration::ZERO`
34879 // detour that returned a fresh copy through an arithmetic
34880 // no-op (breaking a future `const fn` regression), or a
34881 // one-arm-only accessor that returned a saturating value on
34882 // some sentinel input (breaking the pass-through invariant the
34883 // sibling required-scalar accessors carry).
34884 for window in [
34885 Duration::from_millis(1),
34886 POLICY_BREAKER_WINDOW_MAX,
34887 Duration::ZERO,
34888 Duration::from_secs(86_400),
34889 ] {
34890 let cb = CircuitBreaker {
34891 max_failures: 5,
34892 window,
34893 };
34894 let first = cb.window();
34895 let second = cb.window();
34896 assert_eq!(
34897 first, second,
34898 "CircuitBreaker::window must be idempotent — two \
34899 successive calls on the same &self must return the \
34900 same Duration",
34901 );
34902 assert_eq!(
34903 first, window,
34904 "CircuitBreaker::window must return :politicas \
34905 :circuit-breaker :window verbatim by copy — \
34906 got {first:?}, expected {window:?}",
34907 );
34908 }
34909 }
34910
34911 #[test]
34912 fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
34913 // Apex-identity pair-invariant pin composing both substrate-
34914 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
34915 // and [`WitContract::destination`] — at the emit-side call shape
34916 // every per-`(:de, :para)` CNP L4 port reader now takes. The
34917 // invariant, evaluated per-edge:
34918 //
34919 // spec.port_for_destination(c.destination()) == expected_port
34920 //
34921 // where `expected_port` is `entrada.port` when
34922 // `c.destination() == entrada.destination()` and
34923 // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
34924 // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
34925 // pin on the per-`:entrada` axis — that pin encodes the apex
34926 // ingress L4 identity via `entrada.destination()`; this pin
34927 // encodes the per-edge L4 identity via `c.destination()`, and
34928 // both compose on the same substrate-primitive resolver so a
34929 // future refactor that silently split either accessor's apex
34930 // behavior surfaces at caixa-core build time.
34931 let mut spec = three_member_spec();
34932 if let Some(e) = spec.entrada.as_mut() {
34933 e.para = "cart".into();
34934 e.port = 8443;
34935 }
34936 let apex_contract = WitContract {
34937 de: "checkout".into(),
34938 para: "cart".into(),
34939 wit: "wasi:http/proxy".into(),
34940 endpoint: Some("/hello".into()),
34941 subject: None,
34942 slot: None,
34943 };
34944 assert_eq!(
34945 spec.port_for_destination(apex_contract.destination()),
34946 8443,
34947 "`spec.port_for_destination(c.destination())` must equal \
34948 `entrada.port` when the contract callee names the ingress \
34949 apex — the CNP per-edge L4 port and the HTTPRoute apex \
34950 backendRef port share this substrate-primitive resolver.",
34951 );
34952 let non_apex_contract = WitContract {
34953 de: "cart".into(),
34954 para: "payment".into(),
34955 wit: "wasi:http/proxy".into(),
34956 endpoint: Some("/charge".into()),
34957 subject: None,
34958 slot: None,
34959 };
34960 assert_eq!(
34961 spec.port_for_destination(non_apex_contract.destination()),
34962 DEFAULT_SERVICO_PORT,
34963 "`spec.port_for_destination(c.destination())` must fall back \
34964 to the substrate-canonical port floor when the contract \
34965 callee is not the ingress apex — the resolver's non-apex \
34966 arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
34967 );
34968 }
34969
34970 #[test]
34971 fn membro_key_consts_are_lower_camel_case_shape() {
34972 // Shape-pin: every `MEMBRO_KEY_*` const must be a
34973 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
34974 // `kebab-case` hyphens, no leading colon, no `PascalCase`
34975 // leading capital, no whitespace / dots) — the canonical shape
34976 // the `#[serde(rename_all = "camelCase")]` derive produces on
34977 // [`Membro`]. A future flip to a non-camelCase attribute at
34978 // the derive surfaces both here (this test fails on the
34979 // stale-constant shape) and at
34980 // `membro_serde_keys_match_lifted_membro_key_consts` (that test
34981 // fails on the mismatch between const and derive). Peer with
34982 // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
34983 // on the sibling `SupervisorSpec` top-level axis.
34984 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
34985 assert!(
34986 !key.is_empty(),
34987 "MEMBRO_KEY_* must be non-empty (got {key:?})"
34988 );
34989 let first = key.chars().next().unwrap();
34990 assert!(
34991 first.is_ascii_lowercase(),
34992 "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
34993 (got {key:?}, leads with {first:?})",
34994 );
34995 assert!(
34996 key.chars().all(|c| c.is_ascii_alphanumeric()),
34997 "MEMBRO_KEY_* must be ASCII-alphanumeric only \
34998 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
34999 );
35000 }
35001 }
35002
35003 // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
35004
35005 #[test]
35006 fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
35007 // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
35008 // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
35009 // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
35010 // keys the `#[serde(rename_all = "camelCase")]` attribute on
35011 // [`WitContract`] emits for the required-triad. The three
35012 // sibling payload-arm keys already pin under
35013 // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
35014 // `STORE_FIELD_NAME` — pin all six alongside so a future
35015 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
35016 // verbatim-field-name flip at the derive attribute (any of which
35017 // would silently break every downstream JSON consumer that
35018 // reaches for one of the six via `Value::get(...)`) surfaces
35019 // here as a build-time test failure at `aplicacao.rs`, not as an
35020 // apply-time `.get(<stale-canonical-const>)` returning `None`
35021 // far from the derive-attr drift's commit. Peer with the sibling
35022 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
35023 // pin on the M3 `:membros` per-entry axis — same discipline the
35024 // `Membro` per-entry lift established, extended here to the
35025 // sibling M3 `WitContract` per-`:contratos` entry axis, the last
35026 // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
35027 // axis on the Aplicacao surface without a lifted serde-key peer.
35028 let c = WitContract {
35029 de: "cart".into(),
35030 para: "catalog".into(),
35031 wit: "wasi:http/proxy".into(),
35032 endpoint: Some("/lookup".into()),
35033 subject: None,
35034 slot: None,
35035 };
35036 let json = serde_json::to_string(&c).unwrap();
35037 for key in [
35038 crate::CONTRATO_KEY_DE,
35039 crate::CONTRATO_KEY_PARA,
35040 crate::CONTRATO_KEY_WIT,
35041 WitTarget::HTTP_FIELD_NAME,
35042 ] {
35043 let quoted = format!("\"{key}\"");
35044 assert!(
35045 json.contains("ed),
35046 "serialized WitContract must carry the lifted \
35047 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
35048 {quoted} verbatim in the JSON emission (got: {json})",
35049 );
35050 }
35051
35052 // Pin the two remaining payload-arm keys by round-tripping a
35053 // `WitContract` under each payload-shape (pub-sub, store) — the
35054 // required-triad appears on every emission but the payload arms
35055 // only surface when their `Option<String>` field is `Some`.
35056 let pubsub = WitContract {
35057 de: "cart".into(),
35058 para: "events".into(),
35059 wit: "nats:pub-sub".into(),
35060 endpoint: None,
35061 subject: Some("orders.placed".into()),
35062 slot: None,
35063 };
35064 let pubsub_json = serde_json::to_string(&pubsub).unwrap();
35065 let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
35066 assert!(
35067 pubsub_json.contains(&pubsub_quoted),
35068 "serialized pub-sub WitContract must carry the lifted \
35069 WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
35070 verbatim in the JSON emission (got: {pubsub_json})",
35071 );
35072 let store = WitContract {
35073 de: "cart".into(),
35074 para: "sessions".into(),
35075 wit: "wasi:keyvalue/store".into(),
35076 endpoint: None,
35077 subject: None,
35078 slot: Some("cart/$id".into()),
35079 };
35080 let store_json = serde_json::to_string(&store).unwrap();
35081 let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
35082 assert!(
35083 store_json.contains(&store_quoted),
35084 "serialized store WitContract must carry the lifted \
35085 WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
35086 verbatim in the JSON emission (got: {store_json})",
35087 );
35088 }
35089
35090 #[test]
35091 fn contrato_key_consts_are_pairwise_distinct() {
35092 // Cross-axis drift-detection pin: a future collapse of the six
35093 // canonical [`WitContract`] per-entry byte-strings onto the same
35094 // value (e.g. an accidental copy-paste flip of
35095 // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
35096 // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
35097 // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
35098 // every downstream probe on one axis onto the sibling axis's
35099 // overlay entry and pass every propagation-probe test that
35100 // expected only the stale axis's value. Peer of the sibling
35101 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
35102 // widened here to the six-way axis the `WitContract`
35103 // required-triad + `WitTarget` payload-triad jointly cover.
35104 let all = [
35105 crate::CONTRATO_KEY_DE,
35106 crate::CONTRATO_KEY_PARA,
35107 crate::CONTRATO_KEY_WIT,
35108 WitTarget::HTTP_FIELD_NAME,
35109 WitTarget::PUBSUB_FIELD_NAME,
35110 WitTarget::STORE_FIELD_NAME,
35111 ];
35112 for (i, a) in all.iter().enumerate() {
35113 for b in all.iter().skip(i + 1) {
35114 assert_ne!(
35115 a, b,
35116 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
35117 must be pairwise-distinct canonical byte-sequences \
35118 — got `{a}` == `{b}`",
35119 );
35120 }
35121 }
35122 }
35123
35124 #[test]
35125 fn contrato_key_consts_are_lower_camel_case_shape() {
35126 // Shape-pin: every `CONTRATO_KEY_*` (and every peer
35127 // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
35128 // byte-sequence (no `snake_case` underscores, no `kebab-case`
35129 // hyphens, no leading colon, no `PascalCase` leading capital, no
35130 // whitespace / dots) — the canonical shape the
35131 // `#[serde(rename_all = "camelCase")]` derive produces on
35132 // [`WitContract`]. A future flip to a non-camelCase attribute at
35133 // the derive surfaces both here (this test fails on the
35134 // stale-constant shape) and at
35135 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
35136 // (that test fails on the mismatch between const and derive).
35137 // Peer with `membro_key_consts_are_lower_camel_case_shape`
35138 // (ce80ca0) on the sibling `Membro` per-entry axis.
35139 for key in [
35140 crate::CONTRATO_KEY_DE,
35141 crate::CONTRATO_KEY_PARA,
35142 crate::CONTRATO_KEY_WIT,
35143 WitTarget::HTTP_FIELD_NAME,
35144 WitTarget::PUBSUB_FIELD_NAME,
35145 WitTarget::STORE_FIELD_NAME,
35146 ] {
35147 assert!(
35148 !key.is_empty(),
35149 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
35150 non-empty (got {key:?})"
35151 );
35152 let first = key.chars().next().unwrap();
35153 assert!(
35154 first.is_ascii_lowercase(),
35155 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
35156 with an ASCII-lowercase byte (got {key:?}, leads with \
35157 {first:?})",
35158 );
35159 assert!(
35160 key.chars().all(|c| c.is_ascii_alphanumeric()),
35161 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
35162 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
35163 whitespace (got {key:?})",
35164 );
35165 }
35166 }
35167
35168 // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
35169
35170 #[test]
35171 fn entrada_serde_keys_match_lifted_entrada_key_consts() {
35172 // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
35173 // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
35174 // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
35175 // name the exact camelCase JSON keys the
35176 // `#[serde(rename_all = "camelCase")]` attribute on
35177 // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
35178 // pin that each canonical byte-sequence appears verbatim in the
35179 // JSON — a future accidental `rename_all = "snake_case"` /
35180 // `"kebab-case"` / verbatim-field-name flip at the derive
35181 // attribute (any of which would silently break every downstream
35182 // JSON consumer that reaches for one of the four consts via
35183 // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
35184 // emitter's per-Aplicacao hostname/paths/port projection, the
35185 // future `app-operator` reconciler's per-Aplicacao ingress
35186 // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
35187 // materializer's admission-time cross-check) surfaces here as
35188 // a build-time test failure at `aplicacao.rs`, not as an
35189 // apply-time `.get(<stale-canonical-const>)` returning `None`
35190 // far from the derive-attr drift's commit. Peer with the
35191 // sibling
35192 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
35193 // (ca463a4) and
35194 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
35195 // pins on the M3 collection-slot atom axes — same discipline
35196 // both collection-slot lifts established, extended here to the
35197 // singleton `:entrada` mesh-slot atom axis, the last M3
35198 // typed-struct top-level `#[serde(rename_all = "camelCase")]`
35199 // axis on the Aplicacao surface without a lifted serde-key
35200 // peer.
35201 let e = Entrada {
35202 host: "checkout.quero.cloud".into(),
35203 para: "cart".into(),
35204 paths: vec!["/cart".into()],
35205 port: 8080,
35206 };
35207 let json = serde_json::to_string(&e).unwrap();
35208 for key in [
35209 crate::ENTRADA_KEY_HOST,
35210 crate::ENTRADA_KEY_PARA,
35211 crate::ENTRADA_KEY_PATHS,
35212 crate::ENTRADA_KEY_PORT,
35213 ] {
35214 let quoted = format!("\"{key}\"");
35215 assert!(
35216 json.contains("ed),
35217 "serialized Entrada must carry the lifted ENTRADA_KEY_* \
35218 byte-sequence {quoted} verbatim in the JSON emission \
35219 (got: {json})",
35220 );
35221 }
35222 }
35223
35224 #[test]
35225 fn entrada_key_consts_are_pairwise_distinct() {
35226 // Cross-axis drift-detection pin: a future collapse of the four
35227 // canonical [`Entrada`] singleton byte-strings onto the same
35228 // value (e.g. an accidental copy-paste flip of
35229 // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
35230 // silently reroute every downstream probe on one axis onto the
35231 // sibling axis's overlay entry and pass every propagation-probe
35232 // test that expected only the stale axis's value — the
35233 // Gateway/HTTPRoute emitter would read the hostname string
35234 // where the destination-Servico name was expected (or vice
35235 // versa), the admission-webhook cross-check would compare the
35236 // wrong pair of values, and the resulting Gateway resource
35237 // would either be admitted with garbage or rejected at the
35238 // controller far from the rebrand commit's source. Peer of the
35239 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
35240 // tetrad (40cc4e5), the two-way distinct pin on the
35241 // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
35242 // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
35243 // triad (ca463a4).
35244 let all = [
35245 crate::ENTRADA_KEY_HOST,
35246 crate::ENTRADA_KEY_PARA,
35247 crate::ENTRADA_KEY_PATHS,
35248 crate::ENTRADA_KEY_PORT,
35249 ];
35250 for (i, a) in all.iter().enumerate() {
35251 for b in all.iter().skip(i + 1) {
35252 assert_ne!(
35253 a, b,
35254 "ENTRADA_KEY_* consts must be pairwise-distinct \
35255 canonical byte-sequences — got `{a}` == `{b}`",
35256 );
35257 }
35258 }
35259 }
35260
35261 #[test]
35262 fn entrada_key_consts_are_lower_camel_case_shape() {
35263 // Shape-pin: every `ENTRADA_KEY_*` const must be a
35264 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
35265 // `kebab-case` hyphens, no leading colon, no `PascalCase`
35266 // leading capital, no whitespace / dots) — the canonical shape
35267 // the `#[serde(rename_all = "camelCase")]` derive produces on
35268 // [`Entrada`]. A future flip to a non-camelCase attribute at
35269 // the derive surfaces both here (this test fails on the
35270 // stale-constant shape) and at
35271 // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
35272 // test fails on the mismatch between const and derive). Peer
35273 // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
35274 // and `contrato_key_consts_are_lower_camel_case_shape`
35275 // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
35276 // entry axes.
35277 for key in [
35278 crate::ENTRADA_KEY_HOST,
35279 crate::ENTRADA_KEY_PARA,
35280 crate::ENTRADA_KEY_PATHS,
35281 crate::ENTRADA_KEY_PORT,
35282 ] {
35283 assert!(
35284 !key.is_empty(),
35285 "ENTRADA_KEY_* must be non-empty (got {key:?})"
35286 );
35287 let first = key.chars().next().unwrap();
35288 assert!(
35289 first.is_ascii_lowercase(),
35290 "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
35291 (got {key:?}, leads with {first:?})",
35292 );
35293 assert!(
35294 key.chars().all(|c| c.is_ascii_alphanumeric()),
35295 "ENTRADA_KEY_* must be ASCII-alphanumeric only \
35296 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
35297 );
35298 }
35299 }
35300
35301 // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
35302
35303 #[test]
35304 fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
35305 // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
35306 // ([`crate::POLITICAS_KEY_TIMEOUT`] /
35307 // [`crate::POLITICAS_KEY_RETRIES`] /
35308 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
35309 // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
35310 // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
35311 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
35312 // on [`MeshPolicy`] emits. Three of the five axes
35313 // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
35314 // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
35315 // camelCase transforms — the derive-attribute is load-bearing
35316 // on those, unlike the sibling `Entrada` / `Membro` /
35317 // `WitContract` structs whose fields are all lowercase-single-
35318 // word and where the derive is a no-op on every axis.
35319 // Serialize a fully-populated [`MeshPolicy`] (every axis
35320 // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
35321 // on none of the five slots) and pin that each canonical
35322 // byte-sequence appears verbatim in the JSON — a future
35323 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
35324 // verbatim-field-name flip at the derive attribute (any of
35325 // which would silently break every downstream JSON consumer
35326 // that reaches for one of the five consts via
35327 // `Value::get(...)` — the future M4 per-edge `:politicas`
35328 // overlay projection onto Cilium `L7Rules` and Gateway API
35329 // `HTTPRoute` backend timeouts, the future
35330 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
35331 // admission-time mesh-policy cross-check, the future
35332 // `feira lint` per-`:politicas` bound-check gate) surfaces here
35333 // as a build-time test failure at `aplicacao.rs`, not as an
35334 // apply-time `.get(<stale-canonical-const>)` returning `None`
35335 // far from the derive-attr drift's commit. Peer with the
35336 // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
35337 // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
35338 // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
35339 // (ce80ca0) pins on the M3 collection-slot / singleton-slot
35340 // atom axes — same discipline every M3 sibling lift
35341 // established, extended here to the singleton `:politicas`
35342 // mesh-slot atom axis, closing the last M3 typed-struct
35343 // top-level `#[serde(rename_all = "camelCase")]` axis on the
35344 // Aplicacao surface without a lifted serde-key peer.
35345 let p = MeshPolicy {
35346 timeout: Some(Duration::from_secs(30)),
35347 retries: Some(3),
35348 circuit_breaker: Some(CircuitBreaker {
35349 max_failures: 5,
35350 window: Duration::from_secs(60),
35351 }),
35352 mtls_required: Some(true),
35353 rate_limit: Some(RateLimit {
35354 rate: 100,
35355 window: Duration::from_secs(1),
35356 }),
35357 };
35358 let json = serde_json::to_string(&p).unwrap();
35359 for key in [
35360 crate::POLITICAS_KEY_TIMEOUT,
35361 crate::POLITICAS_KEY_RETRIES,
35362 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
35363 crate::POLITICAS_KEY_MTLS_REQUIRED,
35364 crate::POLITICAS_KEY_RATE_LIMIT,
35365 ] {
35366 let quoted = format!("\"{key}\"");
35367 assert!(
35368 json.contains("ed),
35369 "serialized MeshPolicy must carry the lifted \
35370 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
35371 JSON emission (got: {json})",
35372 );
35373 }
35374 }
35375
35376 #[test]
35377 fn politicas_key_consts_are_pairwise_distinct() {
35378 // Cross-axis drift-detection pin: a future collapse of the five
35379 // canonical [`MeshPolicy`] singleton byte-strings onto the same
35380 // value (e.g. an accidental copy-paste flip of
35381 // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
35382 // would silently reroute every downstream probe on one axis
35383 // onto the sibling axis's overlay entry and pass every
35384 // propagation-probe test that expected only the stale axis's
35385 // value — the M4 per-edge `:politicas` overlay projection would
35386 // read the retry-count string where the timeout duration was
35387 // expected (or vice versa), the CR materializer's admission
35388 // cross-check would compare the wrong pair of values, and the
35389 // resulting mesh reconciler would either bind the wrong axis
35390 // or reject the resource at reconcile far from the rebrand
35391 // commit's source. Peer of the sibling four-way distinct pin
35392 // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
35393 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
35394 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
35395 // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
35396 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
35397 let all = [
35398 crate::POLITICAS_KEY_TIMEOUT,
35399 crate::POLITICAS_KEY_RETRIES,
35400 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
35401 crate::POLITICAS_KEY_MTLS_REQUIRED,
35402 crate::POLITICAS_KEY_RATE_LIMIT,
35403 ];
35404 for (i, a) in all.iter().enumerate() {
35405 for b in all.iter().skip(i + 1) {
35406 assert_ne!(
35407 a, b,
35408 "POLITICAS_KEY_* consts must be pairwise-distinct \
35409 canonical byte-sequences — got `{a}` == `{b}`",
35410 );
35411 }
35412 }
35413 }
35414
35415 #[test]
35416 fn politicas_key_consts_are_lower_camel_case_shape() {
35417 // Shape-pin: every `POLITICAS_KEY_*` const must be a
35418 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
35419 // `kebab-case` hyphens, no leading colon, no `PascalCase`
35420 // leading capital, no whitespace / dots) — the canonical shape
35421 // the `#[serde(rename_all = "camelCase")]` derive produces on
35422 // [`MeshPolicy`]. A future flip to a non-camelCase attribute
35423 // at the derive surfaces both here (this test fails on the
35424 // stale-constant shape) and at
35425 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
35426 // (that test fails on the mismatch between const and derive).
35427 // Peer with `entrada_key_consts_are_lower_camel_case_shape`
35428 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
35429 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
35430 // (ca463a4) on the sibling M3 typed-struct axes.
35431 for key in [
35432 crate::POLITICAS_KEY_TIMEOUT,
35433 crate::POLITICAS_KEY_RETRIES,
35434 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
35435 crate::POLITICAS_KEY_MTLS_REQUIRED,
35436 crate::POLITICAS_KEY_RATE_LIMIT,
35437 ] {
35438 assert!(
35439 !key.is_empty(),
35440 "POLITICAS_KEY_* must be non-empty (got {key:?})"
35441 );
35442 let first = key.chars().next().unwrap();
35443 assert!(
35444 first.is_ascii_lowercase(),
35445 "POLITICAS_KEY_* must lead with an ASCII-lowercase \
35446 byte (got {key:?}, leads with {first:?})",
35447 );
35448 assert!(
35449 key.chars().all(|c| c.is_ascii_alphanumeric()),
35450 "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
35451 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
35452 );
35453 }
35454 }
35455
35456 // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
35457
35458 #[test]
35459 fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
35460 // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
35461 // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
35462 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
35463 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
35464 // [`CircuitBreaker`] emits inside the
35465 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
35466 // two axes (`max_failures` → `maxFailures`) is a non-trivial
35467 // camelCase transform — the derive-attribute is load-bearing on
35468 // that axis, unlike the sibling `window` field where the derive
35469 // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
35470 // pin that each canonical byte-sequence appears verbatim in the
35471 // JSON — a future accidental `rename_all = "snake_case"` /
35472 // `"kebab-case"` / verbatim-field-name flip at the derive
35473 // attribute (any of which would silently break every downstream
35474 // JSON consumer that reaches for one of the two consts via
35475 // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
35476 // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
35477 // per-edge `:politicas` overlay projection onto the mesh's
35478 // per-backend consecutive-failure-counter tripping threshold, the
35479 // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
35480 // admission-time breaker cross-check, the future `feira lint`
35481 // per-`:politicas :circuit-breaker` bound-check gate) surfaces
35482 // here as a build-time test failure at `aplicacao.rs`, not as an
35483 // apply-time `.get(<stale-canonical-const>)` returning `None`
35484 // far from the derive-attr drift's commit. Peer with the sibling
35485 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
35486 // (b55cca7) parent-axis pin — that test pins the outer
35487 // sub-block key the derive on [`MeshPolicy`] emits, this test
35488 // pins the inner keys the derive on the payload type emits, so
35489 // the two together lock the whole [`MeshPolicy`] breaker-tuning
35490 // shape end-to-end at build time.
35491 let cb = CircuitBreaker {
35492 max_failures: 5,
35493 window: Duration::from_secs(60),
35494 };
35495 let json = serde_json::to_string(&cb).unwrap();
35496 for key in [
35497 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
35498 crate::CIRCUIT_BREAKER_KEY_WINDOW,
35499 ] {
35500 let quoted = format!("\"{key}\"");
35501 assert!(
35502 json.contains("ed),
35503 "serialized CircuitBreaker must carry the lifted \
35504 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
35505 in the JSON emission (got: {json})",
35506 );
35507 }
35508 }
35509
35510 #[test]
35511 fn circuit_breaker_key_consts_are_pairwise_distinct() {
35512 // Cross-axis drift-detection pin: a future collapse of the two
35513 // canonical [`CircuitBreaker`] sub-block byte-strings onto the
35514 // same value (e.g. an accidental copy-paste flip of
35515 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
35516 // `"maxFailures"`) would silently reroute every downstream
35517 // probe on one axis onto the sibling axis's overlay entry and
35518 // pass every propagation-probe test that expected only the
35519 // stale axis's value — the M4 per-edge `:politicas` overlay
35520 // projection would read the failure-count where the window
35521 // duration was expected (or vice versa), the CR materializer's
35522 // admission cross-check would compare the wrong pair of values,
35523 // and the resulting mesh reconciler would either bind the wrong
35524 // axis or reject the resource at reconcile far from the rebrand
35525 // commit's source. Peer of the sibling five-way distinct pin on
35526 // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
35527 // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
35528 // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
35529 // six-way distinct pin on the `CONTRATO_KEY_*` triad +
35530 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
35531 let all = [
35532 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
35533 crate::CIRCUIT_BREAKER_KEY_WINDOW,
35534 ];
35535 for (i, a) in all.iter().enumerate() {
35536 for b in all.iter().skip(i + 1) {
35537 assert_ne!(
35538 a, b,
35539 "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
35540 canonical byte-sequences — got `{a}` == `{b}`",
35541 );
35542 }
35543 }
35544 }
35545
35546 #[test]
35547 fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
35548 // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
35549 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
35550 // `kebab-case` hyphens, no leading colon, no `PascalCase`
35551 // leading capital, no whitespace / dots) — the canonical shape
35552 // the `#[serde(rename_all = "camelCase")]` derive produces on
35553 // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
35554 // at the derive surfaces both here (this test fails on the
35555 // stale-constant shape) and at
35556 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
35557 // (that test fails on the mismatch between const and derive).
35558 // Peer with `politicas_key_consts_are_lower_camel_case_shape`
35559 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
35560 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
35561 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
35562 // (ca463a4) on the sibling M3 typed-struct axes.
35563 for key in [
35564 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
35565 crate::CIRCUIT_BREAKER_KEY_WINDOW,
35566 ] {
35567 assert!(
35568 !key.is_empty(),
35569 "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
35570 );
35571 let first = key.chars().next().unwrap();
35572 assert!(
35573 first.is_ascii_lowercase(),
35574 "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
35575 byte (got {key:?}, leads with {first:?})",
35576 );
35577 assert!(
35578 key.chars().all(|c| c.is_ascii_alphanumeric()),
35579 "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
35580 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
35581 );
35582 }
35583 }
35584
35585 // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
35586
35587 #[test]
35588 fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
35589 // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
35590 // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
35591 // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
35592 // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
35593 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
35594 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
35595 // [`Placement`] emits. One of the four axes (`shard_key` →
35596 // `shardKey`) is a non-trivial camelCase transform — the
35597 // derive-attribute is load-bearing on that axis, unlike the
35598 // sibling `estrategia` / `clusters` / `affinity` axes whose
35599 // source-side field names carry no `_` and where the derive is a
35600 // no-op. Serialize a fully-populated [`Placement`] (both
35601 // `Option`-carrying axes `Some(_)` so
35602 // `skip_serializing_if = "Option::is_none"` fires on neither of
35603 // the two optional slots) and pin that each canonical
35604 // byte-sequence appears verbatim in the JSON — a future
35605 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
35606 // verbatim-field-name flip at the derive attribute (any of which
35607 // would silently break every downstream consumer that reaches
35608 // for one of the four consts via
35609 // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
35610 // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
35611 // aggregator's per-cluster fanout filter keying off
35612 // `placement.clusters`, the M3 shard-pool dispatch materializer
35613 // keying off `placement.shardKey`, the M3 Adaptive compression
35614 // pass weighting off `placement.affinity`, every downstream
35615 // dispatcher branching on `placement.estrategia`, the future
35616 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
35617 // admission-time placement cross-check, the future `feira lint`
35618 // per-`:placement` bound-check gate) surfaces here as a
35619 // build-time test failure at `aplicacao.rs`, not as an
35620 // apply-time `.get(<stale-canonical-const>)` returning `None`
35621 // far from the derive-attr drift's commit. Peer with the sibling
35622 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
35623 // (b55cca7),
35624 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
35625 // (468e959),
35626 // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
35627 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
35628 // (ca463a4), and
35629 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
35630 // pins on the M3 collection-slot / singleton-slot atom axes —
35631 // closes the last M3 typed-struct top-level
35632 // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
35633 // surface without a drift-detection pin.
35634 let p = Placement {
35635 estrategia: PlacementStrategy::Sharded,
35636 clusters: vec!["rio".into(), "mar".into()],
35637 affinity: Some("data-locality".into()),
35638 shard_key: Some("$tenantId".into()),
35639 };
35640 let json = serde_json::to_string(&p).unwrap();
35641 for key in [
35642 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
35643 crate::M3_PLACEMENT_KEY_CLUSTERS,
35644 crate::M3_PLACEMENT_KEY_AFFINITY,
35645 crate::M3_PLACEMENT_KEY_SHARD_KEY,
35646 ] {
35647 let quoted = format!("\"{key}\"");
35648 assert!(
35649 json.contains("ed),
35650 "serialized Placement must carry the lifted \
35651 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
35652 the JSON emission (got: {json})",
35653 );
35654 }
35655 }
35656
35657 #[test]
35658 fn m3_placement_key_consts_are_pairwise_distinct() {
35659 // Cross-axis drift-detection pin: a future collapse of the four
35660 // canonical [`Placement`] sub-block byte-strings onto the same
35661 // value (e.g. an accidental copy-paste flip of
35662 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
35663 // `"affinity"`) would silently reroute every downstream probe on
35664 // one axis onto the sibling axis's overlay entry and pass every
35665 // propagation-probe test that expected only the stale axis's
35666 // value — the M3 shard-pool dispatch materializer would read the
35667 // affinity placement-hint where the shard-selection template was
35668 // expected (or vice versa), the M3 Adaptive compression pass's
35669 // cross-check would compare the wrong pair of values, and the
35670 // resulting placement engine would either bind the wrong axis or
35671 // reject the resource at reconcile far from the rebrand commit's
35672 // source. Peer of the sibling two-way distinct pin on the
35673 // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
35674 // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
35675 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
35676 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
35677 // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
35678 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
35679 let all = [
35680 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
35681 crate::M3_PLACEMENT_KEY_CLUSTERS,
35682 crate::M3_PLACEMENT_KEY_AFFINITY,
35683 crate::M3_PLACEMENT_KEY_SHARD_KEY,
35684 ];
35685 for (i, a) in all.iter().enumerate() {
35686 for b in all.iter().skip(i + 1) {
35687 assert_ne!(
35688 a, b,
35689 "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
35690 canonical byte-sequences — got `{a}` == `{b}`",
35691 );
35692 }
35693 }
35694 }
35695
35696 #[test]
35697 fn m3_placement_key_consts_are_lower_camel_case_shape() {
35698 // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
35699 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
35700 // `kebab-case` hyphens, no leading colon, no `PascalCase`
35701 // leading capital, no whitespace / dots) — the canonical shape
35702 // the `#[serde(rename_all = "camelCase")]` derive produces on
35703 // [`Placement`]. A future flip to a non-camelCase attribute at
35704 // the derive surfaces both here (this test fails on the stale-
35705 // constant shape) and at
35706 // `placement_serde_keys_match_lifted_m3_placement_key_consts`
35707 // (that test fails on the mismatch between const and derive).
35708 // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
35709 // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
35710 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
35711 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
35712 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
35713 // (ca463a4) on the sibling M3 typed-struct axes.
35714 for key in [
35715 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
35716 crate::M3_PLACEMENT_KEY_CLUSTERS,
35717 crate::M3_PLACEMENT_KEY_AFFINITY,
35718 crate::M3_PLACEMENT_KEY_SHARD_KEY,
35719 ] {
35720 assert!(
35721 !key.is_empty(),
35722 "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
35723 );
35724 let first = key.chars().next().unwrap();
35725 assert!(
35726 first.is_ascii_lowercase(),
35727 "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
35728 byte (got {key:?}, leads with {first:?})",
35729 );
35730 assert!(
35731 key.chars().all(|c| c.is_ascii_alphanumeric()),
35732 "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
35733 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
35734 );
35735 }
35736 }
35737
35738 // ── AplicacaoSpec::port_for_destination — the substrate-canonical
35739 // destination-facing L4 port resolver every per-Aplicacao renderer
35740 // reaching for a per-destination Servico TCP port axis routes
35741 // through. The four pin tests below fix the four-way accept-set
35742 // the resolver must always honor: (:entrada-para-matches,
35743 // :entrada-para-mismatches, :entrada-none-so-fallback,
35744 // :entrada-port-non-default-honored) — drift on any arm surfaces
35745 // at caixa-core build time rather than at cluster-apply time.
35746
35747 #[test]
35748 fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
35749 // The typed `:entrada` block's `:para "cart"` matches the
35750 // queried destination, so the resolver returns the author-
35751 // declared `:port` scalar verbatim — the canonical "the
35752 // destination Servico IS the ingress apex, honor the typed
35753 // listener port" arm of the port-resolution dispatch.
35754 let mut spec = three_member_spec();
35755 if let Some(e) = spec.entrada.as_mut() {
35756 e.para = "cart".into();
35757 e.port = 9090;
35758 }
35759 assert_eq!(
35760 spec.port_for_destination("cart"),
35761 9090,
35762 "port_for_destination(entrada.para) must return entrada.port \
35763 verbatim, not the DEFAULT_SERVICO_PORT fallback"
35764 );
35765 }
35766
35767 #[test]
35768 fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
35769 // The typed `:entrada` block names `:para "cart"`, but the
35770 // queried destination is `"payment"` — a Servico that
35771 // participates in the mesh graph but is not the ingress apex.
35772 // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
35773 // canonical port floor, closing the "non-apex destination reads
35774 // the substrate default" arm. Same fixture the peer
35775 // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
35776 // pin at caixa-mesh exercises through the CNP emit-side path;
35777 // this pin exercises the shared underlying resolver directly.
35778 let spec = three_member_spec();
35779 assert_eq!(
35780 spec.port_for_destination("payment"),
35781 DEFAULT_SERVICO_PORT,
35782 "port_for_destination(non-apex-destination) must route \
35783 through the lifted DEFAULT_SERVICO_PORT canonical port floor"
35784 );
35785 }
35786
35787 #[test]
35788 fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
35789 // Internal-only Aplicacao — no `:entrada` block declared. Every
35790 // per-destination port query falls back to the lifted
35791 // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
35792 // the Aplicacao surface admits `:entrada None` (internal mesh
35793 // with no external gateway); every downstream renderer's per-
35794 // destination port axis must still resolve to a well-defined
35795 // scalar even without an ingress apex.
35796 let mut spec = three_member_spec();
35797 spec.entrada = None;
35798 assert_eq!(
35799 spec.port_for_destination("cart"),
35800 DEFAULT_SERVICO_PORT,
35801 "port_for_destination on an internal-only Aplicacao must \
35802 fall back to the lifted DEFAULT_SERVICO_PORT floor for \
35803 every destination"
35804 );
35805 assert_eq!(
35806 spec.port_for_destination("payment"),
35807 DEFAULT_SERVICO_PORT,
35808 "port_for_destination on an internal-only Aplicacao must \
35809 fall back uniformly across every destination — the fallback \
35810 is not entrada-shape-conditional"
35811 );
35812 }
35813
35814 #[test]
35815 fn port_for_destination_honors_non_default_entrada_port_verbatim() {
35816 // Structural pin against a hypothetical future refactor that
35817 // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
35818 // the resolver (a "normalize to the default when the author's
35819 // port matches the substrate default" collapse) — that would
35820 // break renderer sites that carry meaning on the emitted port
35821 // value beyond bare equality (a future per-cluster listener-
35822 // audit that keys off the author-declared port, not the
35823 // resolved-with-fallback port). Pin that a non-default
35824 // entrada.port is returned verbatim so drift here surfaces at
35825 // caixa-core build time.
35826 let mut spec = three_member_spec();
35827 if let Some(e) = spec.entrada.as_mut() {
35828 e.para = "cart".into();
35829 e.port = 8443;
35830 }
35831 assert_ne!(
35832 8443, DEFAULT_SERVICO_PORT,
35833 "test fixture must probe a port distinct from \
35834 DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
35835 );
35836 assert_eq!(
35837 spec.port_for_destination("cart"),
35838 8443,
35839 "port_for_destination(entrada.para) must return entrada.port \
35840 verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
35841 );
35842 }
35843
35844 #[test]
35845 fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
35846 // Apex-identity pair-invariant pin composing both substrate-
35847 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
35848 // and [`Entrada::destination`] — at the emit-side call shape
35849 // every per-Aplicacao renderer's ingress-apex L4 port reader
35850 // now takes. The invariant:
35851 //
35852 // spec.port_for_destination(entrada.destination()) == entrada.port
35853 //
35854 // holds by construction under today's single-destination
35855 // `:entrada` slot (`destination()` returns `entrada.para`, and
35856 // the resolver's apex arm matches `para == destination` and
35857 // returns `entrada.port`), and every downstream consumer that
35858 // composes the two accessors at the ingress apex — the
35859 // `caixa_mesh::gateway_routes` HTTPRoute per-rule
35860 // `backendRefs[0].port` emit-site path, the peer future M4 CR
35861 // materializer's admission-webhook that promotes the scalar to
35862 // a per-CR override overlay, every future per-Aplicacao snapshot
35863 // renderer's apex-facing L4 port reader — reaches through the
35864 // same composition. Pin the identity across four permutations
35865 // (`:para` × `:port` including a non-default port to exercise
35866 // the honor-verbatim arm and a non-cart `:para` to exercise
35867 // destination-agnostic identity) so a future refactor that
35868 // silently split either accessor's apex behavior surfaces at
35869 // caixa-core build time — a subtle `destination()` renaming
35870 // that returned `entrada.host.as_str()` instead of
35871 // `entrada.para.as_str()` would blow this pin loudly, closing
35872 // the last quiet failure mode the two lifts admit in composition.
35873 //
35874 // Peer discipline with the sibling caixa-mesh cross-crate pin
35875 // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
35876 // on the two-renderer pair-invariant axis; this pin encodes the
35877 // same two-consumer coherence rule at the substrate-primitive
35878 // level so the invariant survives even if every renderer is
35879 // deleted.
35880 for (para, port) in [
35881 ("cart", DEFAULT_SERVICO_PORT),
35882 ("cart", 8443u16),
35883 ("payment", 9090u16),
35884 ("catalog", 443u16),
35885 ] {
35886 let mut spec = three_member_spec();
35887 if let Some(e) = spec.entrada.as_mut() {
35888 e.para = para.into();
35889 e.port = port;
35890 }
35891 let expected_port = spec
35892 .entrada()
35893 .expect("three_member_spec carries a typed `:entrada` block")
35894 .port();
35895 let composed_port = {
35896 let entrada = spec.entrada().expect("entrada present");
35897 spec.port_for_destination(entrada.destination())
35898 };
35899 assert_eq!(
35900 composed_port, expected_port,
35901 "`spec.port_for_destination(entrada.destination())` must \
35902 equal `entrada.port` under today's single-destination \
35903 `:entrada` slot — this is the apex-identity contract \
35904 every downstream ingress-apex L4 port reader relies on. \
35905 Input :entrada :para: {para:?}, :entrada :port: {port}"
35906 );
35907 }
35908 }
35909
35910 #[test]
35911 fn port_for_destination_apex_arm_routes_through_destination_accessor() {
35912 // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
35913 // per-`:entrada` apex-arm membership probe must key off
35914 // [`Entrada::destination`], not the raw `.para` field access.
35915 // Structurally: setting ONLY the `:entrada :para` field to a
35916 // fresh non-cart destination on an otherwise-well-formed
35917 // Aplicacao must (1) leave `e.destination()` byte-equal to
35918 // `e.para.as_str()` (the accessor is byte-projective by
35919 // definition), and (2) cause the resolver's apex arm to fire
35920 // and return `entrada.port` at exactly that new destination
35921 // while every other destination string falls through to
35922 // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
35923 // membership check. Pins against a future silent detour that
35924 // (a) re-derived the apex-arm membership probe off
35925 // `e.para == destination` in `port_for_destination` instead of
35926 // `e.destination() == destination`, silently disagreeing with
35927 // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
35928 // consumers (`entrada.destination()` at
35929 // caixa-mesh/src/lib.rs:3173, `c.destination()` at
35930 // caixa-mesh/src/lib.rs:2739) that already reach through the
35931 // accessor, (b) accessor-side introduced a per-tenant alias
35932 // arm the caller was unaware of, silently rewriting an
35933 // author-declared `:para "cart"` value to a canary-aliased
35934 // form — the raw-field-access resolver would fall through to
35935 // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
35936 // while the peer emit-site consumers landed on the aliased
35937 // destination, splitting the ingress-apex L4 port at
35938 // cluster-apply time.
35939 //
35940 // Peer of the sibling
35941 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
35942 // (d0de220) composition pin on the per-`:membros` refusal-arm
35943 // axis — same "the shape-gate predicate must route through the
35944 // substrate-primitive typed dispatch" discipline extended onto
35945 // the per-`:entrada` apex-arm membership-probe axis. Closes
35946 // the last unlifted `.para` production-code read site on
35947 // `Entrada` in `caixa-core` — after this converge every
35948 // `caixa-core` `.para` field access outside the accessor's own
35949 // body and outside the `WitContract` per-`:contratos` sibling
35950 // axis is either a test-side field-setter or a doc-comment
35951 // reference.
35952 for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
35953 let mut spec = three_member_spec();
35954 if let Some(e) = spec.entrada.as_mut() {
35955 e.para = para.into();
35956 e.port = port;
35957 }
35958 let e = spec
35959 .entrada
35960 .as_ref()
35961 .expect("three_member_spec carries a typed `:entrada` block");
35962 assert_eq!(
35963 e.destination(),
35964 e.para.as_str(),
35965 "Entrada::destination must byte-equal the .para field \
35966 access — an accessor-side detour that no longer \
35967 projects the raw field would silently split this \
35968 drift-detection test from the port_for_destination \
35969 apex-arm membership probe",
35970 );
35971 assert_eq!(
35972 spec.port_for_destination(para),
35973 port,
35974 "port_for_destination must key off the accessor-projected \
35975 destination and return `entrada.port` on the apex arm — \
35976 input :entrada :para: {para:?}, :entrada :port: {port}",
35977 );
35978 assert_eq!(
35979 spec.port_for_destination("ghost-destination-never-a-member"),
35980 DEFAULT_SERVICO_PORT,
35981 "port_for_destination must fall through to \
35982 DEFAULT_SERVICO_PORT on a non-matching destination \
35983 under the accessor-projected membership check — input \
35984 :entrada :para: {para:?}, :entrada :port: {port}",
35985 );
35986 }
35987 }
35988
35989 #[test]
35990 fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
35991 // The canonical per-`:politicas :rate-limit` `:rate`
35992 // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
35993 // [`RateLimit::rate`] must return the `:politicas :rate-limit`
35994 // typed `u32` verbatim, byte-equal to the raw field access
35995 // across every representative value in the accept-set — `1` (the
35996 // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
35997 // the surrounding [`AplicacaoSpec::validate_politicas`] gate
35998 // carves out on the sibling `PolicyRateLimitZero` refusal),
35999 // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
36000 // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
36001 // `0` (a past-the-guard sentinel that pins the accessor doesn't
36002 // perform a silent bounds-collapse into `1` on the zero arm —
36003 // validate rejects zero but the accessor must ship the raw slot
36004 // verbatim so a validate-time gate regression surfaces at the
36005 // emit boundary rather than being silently absorbed), `u32::MAX`
36006 // (a past-the-guard sentinel that pins the accessor doesn't
36007 // perform a silent bounds-collapse through
36008 // `POLICY_RATE_LIMIT_MAX` at the return path).
36009 //
36010 // First sub-struct required-scalar accessor pin on the
36011 // `RateLimit` axis — sibling in shape to the peer
36012 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
36013 // required-`u32` accessor pin on the peer per-sub-struct
36014 // required-axis. Pins against a future silent detour that
36015 // re-derived the token capacity from a peer axis (an accidental
36016 // `self.window.as_secs() as u32` collapse that read the
36017 // rate-limit window duration as a token count), a `0 → 1`
36018 // cluster-default projection (which would silently absorb the
36019 // `PolicyRateLimitZero` refusal case at the accessor boundary),
36020 // or a bounds-collapsing accessor that clamped the return
36021 // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
36022 // gate owns the bounds; the accessor must ship the raw slot
36023 // verbatim).
36024 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
36025 let rl = RateLimit {
36026 rate,
36027 window: Duration::from_secs(1),
36028 };
36029 assert_eq!(
36030 rl.rate(),
36031 rate,
36032 "RateLimit::rate must return :politicas :rate-limit :rate \
36033 verbatim (got {}, expected {rate})",
36034 rl.rate(),
36035 );
36036 assert_eq!(
36037 rl.rate(),
36038 rl.rate,
36039 "RateLimit::rate must byte-equal the raw .rate field \
36040 access across every value in the u32 accept-set",
36041 );
36042 }
36043 }
36044
36045 #[test]
36046 fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
36047 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
36048 // `:rate-limit :rate` zero-floor arm must key off
36049 // [`RateLimit::rate`], not the raw `.rate` field access.
36050 // Structurally: a `RateLimit { rate: 0, window:
36051 // Duration::from_secs(1) }` embedded in a `:politicas
36052 // :rate-limit` slot must surface the `PolicyRateLimitZero`
36053 // refusal exactly, and a `RateLimit { rate: 1, window:
36054 // Duration::from_secs(1) }` (the lower boundary of the
36055 // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
36056 // The pair jointly pins the accessor + validate-gate composition:
36057 // any future silent detour that had the accessor return a fresh
36058 // `1` on the zero arm (a `.rate().max(1)` collapse) would
36059 // silently absorb the `PolicyRateLimitZero` refusal at the
36060 // accessor boundary and the validate gate would accept a
36061 // struct-literal `RateLimit { rate: 0, .. }` — the composition
36062 // pin catches that at caixa-core build time.
36063 //
36064 // Peer of the sibling per-`CircuitBreaker`
36065 // [`CircuitBreaker::max_failures`] (3a74062) /
36066 // [`CircuitBreaker::window`] (373957f) accessor-composition
36067 // pins on the peer required-scalar axes — same "the validate /
36068 // shape-gate predicate must route through the substrate-primitive
36069 // typed dispatch" discipline extended onto the peer
36070 // per-`RateLimit` required-`u32` composition axis.
36071 let mut spec = three_member_spec();
36072 spec.politicas = MeshPolicy {
36073 rate_limit: Some(RateLimit {
36074 rate: 0,
36075 window: Duration::from_secs(1),
36076 }),
36077 ..MeshPolicy::default()
36078 };
36079 assert!(
36080 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
36081 "validate_politicas must reject rate == 0 with \
36082 PolicyRateLimitZero — the accessor and the validate gate \
36083 must route through the same substrate-primitive typed \
36084 dispatch on the :rate zero-floor arm",
36085 );
36086 spec.politicas = MeshPolicy {
36087 rate_limit: Some(RateLimit {
36088 rate: 1,
36089 window: Duration::from_secs(1),
36090 }),
36091 ..MeshPolicy::default()
36092 };
36093 assert!(
36094 spec.validate().is_ok(),
36095 "validate_politicas must accept rate == 1 (the lower \
36096 boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
36097 );
36098 }
36099
36100 #[test]
36101 fn rate_limit_rate_projects_u32_by_copy() {
36102 // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
36103 // `u32` is `Copy` and the accessor must return by value, not by
36104 // reference. Peer of the sibling per-`CircuitBreaker`
36105 // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
36106 // peer required-scalar `:max-failures` axis, extended onto the
36107 // peer per-`RateLimit` required-`u32` copy-invariant shape —
36108 // the accessor's returned `u32` must outlive `&self` (multiple
36109 // calls must return equal values from a dropped-`&self` copy,
36110 // since the returned scalar carries no borrow), and calling the
36111 // accessor twice on the same RateLimit must yield the same
36112 // `u32` verbatim (idempotent, no side effects on `&self`).
36113 //
36114 // Pins against a future silent detour that returned `&u32`
36115 // (which would type-check but silently break every downstream
36116 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
36117 // first parameter is `u32`, and `&u32` would fold to a detached
36118 // copy at the call site with a `*` deref the sibling accessors
36119 // don't need), an accidental `.rate.wrapping_add(0)` detour that
36120 // returned a fresh copy through an arithmetic no-op (breaking a
36121 // future `const fn` regression), or a one-arm-only accessor
36122 // that returned a saturating value on some sentinel input
36123 // (breaking the pass-through invariant the sibling required-
36124 // scalar accessors carry).
36125 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
36126 let rl = RateLimit {
36127 rate,
36128 window: Duration::from_secs(1),
36129 };
36130 let first = rl.rate();
36131 let second = rl.rate();
36132 assert_eq!(
36133 first, second,
36134 "RateLimit::rate must be idempotent — two successive \
36135 calls on the same &self must return the same u32",
36136 );
36137 assert_eq!(
36138 first, rate,
36139 "RateLimit::rate must return :politicas :rate-limit :rate \
36140 verbatim by copy — got {first}, expected {rate}",
36141 );
36142 }
36143 }
36144
36145 #[test]
36146 fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
36147 // The canonical per-`:politicas :rate-limit` `:window`
36148 // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
36149 // pin: [`RateLimit::window`] must return the
36150 // `:politicas :rate-limit :window` typed `Duration` verbatim,
36151 // byte-equal to the raw field access across every
36152 // representative value in the accept-set — `Duration::from_secs(1)`
36153 // (the `"s"` canonical window, the lower row of
36154 // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
36155 // [`AplicacaoSpec::validate_politicas`] gate accepts via
36156 // [`is_canonical_rate_limit_window`]),
36157 // `Duration::from_secs(60)` (the `"m"` canonical window, the
36158 // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
36159 // window, the upper row), `Duration::ZERO` (a past-the-guard
36160 // sentinel that pins the accessor doesn't perform a silent
36161 // bounds-collapse into `Duration::from_secs(1)` on the zero
36162 // arm — validate rejects an off-set window through
36163 // `PolicyRateLimitWindowNotCanonical` but the accessor must
36164 // ship the raw slot verbatim so a validate-time gate
36165 // regression surfaces at the emit boundary rather than being
36166 // silently absorbed), `Duration::from_millis(500)` (a
36167 // sub-canonical past-the-guard sentinel that pins the accessor
36168 // doesn't silently normalize a non-canonical fractional
36169 // magnitude onto the nearest canonical row).
36170 //
36171 // Second sub-struct required-scalar accessor pin on the
36172 // `RateLimit` axis — sibling in shape to the just-landed
36173 // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
36174 // accessor pin on the peer per-sub-struct required-axis,
36175 // extended onto the per-`RateLimit` required-`Duration` axis.
36176 // Pins against a future silent detour that re-derived the
36177 // refill period from a peer axis (an accidental
36178 // `Duration::from_secs(self.rate as u64)` collapse that read
36179 // the rate-limit token capacity as a refill-interval
36180 // duration), a `Duration::ZERO → Duration::from_secs(1)`
36181 // canonical-default projection (which would silently absorb
36182 // the `PolicyRateLimitWindowNotCanonical` refusal case at the
36183 // accessor boundary), or a canonical-set-collapsing accessor
36184 // that clamped the return through [`rate_limit_window_unit`]
36185 // (the `AplicacaoSpec::validate` gate owns the canonical-set
36186 // membership; the accessor must ship the raw slot verbatim).
36187 for window in [
36188 Duration::from_secs(1),
36189 Duration::from_secs(60),
36190 Duration::from_secs(3600),
36191 Duration::ZERO,
36192 Duration::from_millis(500),
36193 ] {
36194 let rl = RateLimit { rate: 100, window };
36195 assert_eq!(
36196 rl.window(),
36197 window,
36198 "RateLimit::window must return :politicas :rate-limit :window \
36199 verbatim (got {:?}, expected {window:?})",
36200 rl.window(),
36201 );
36202 assert_eq!(
36203 rl.window(),
36204 rl.window,
36205 "RateLimit::window must byte-equal the raw .window field \
36206 access across every value in the Duration accept-set",
36207 );
36208 }
36209 }
36210
36211 #[test]
36212 fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
36213 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
36214 // `:rate-limit :window` canonical-set arm must key off
36215 // [`RateLimit::window`], not the raw `.window` field access.
36216 // Structurally: a `RateLimit { window: Duration::from_millis(500),
36217 // .. }` embedded in a `:politicas :rate-limit` slot must
36218 // surface the `PolicyRateLimitWindowNotCanonical` refusal
36219 // exactly (with the sub-canonical `Duration::from_millis(500)`
36220 // magnitude carried through verbatim), and a `RateLimit
36221 // { window: Duration::from_secs(1), .. }` (the lower row of
36222 // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
36223 // The pair jointly pins the accessor + validate-gate
36224 // composition: any future silent detour that had the accessor
36225 // normalize the off-set window to the nearest canonical row
36226 // (a `.window().max(Duration::from_secs(1))` collapse, or a
36227 // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
36228 // collapse) would silently absorb the
36229 // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
36230 // boundary — including a drift in the error's `window` payload
36231 // (the emit-side diagnostic reader keys off the offending
36232 // magnitude verbatim, so a normalization at the accessor
36233 // boundary would silently pin the wrong magnitude in the
36234 // refusal). The composition pin catches that at caixa-core
36235 // build time.
36236 //
36237 // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
36238 // (7f81a60) accessor-composition pin on the peer required-
36239 // scalar `:rate` axis — same "the validate / shape-gate
36240 // predicate must route through the substrate-primitive typed
36241 // dispatch, and the error payload must project through the
36242 // same accessor" discipline extended onto the peer
36243 // per-`RateLimit` required-`Duration` composition axis.
36244 let mut spec = three_member_spec();
36245 spec.politicas = MeshPolicy {
36246 rate_limit: Some(RateLimit {
36247 rate: 100,
36248 window: Duration::from_millis(500),
36249 }),
36250 ..MeshPolicy::default()
36251 };
36252 match spec.validate() {
36253 Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
36254 assert_eq!(
36255 window,
36256 Duration::from_millis(500),
36257 "PolicyRateLimitWindowNotCanonical must carry the \
36258 offending :window magnitude verbatim through the \
36259 accessor — got {window:?}, expected 500ms",
36260 );
36261 }
36262 other => panic!(
36263 "validate_politicas must reject non-canonical :window \
36264 with PolicyRateLimitWindowNotCanonical — the accessor \
36265 and the validate gate must route through the same \
36266 substrate-primitive typed dispatch on the :window \
36267 canonical-set arm; got {other:?}",
36268 ),
36269 }
36270 spec.politicas = MeshPolicy {
36271 rate_limit: Some(RateLimit {
36272 rate: 100,
36273 window: Duration::from_secs(1),
36274 }),
36275 ..MeshPolicy::default()
36276 };
36277 assert!(
36278 spec.validate().is_ok(),
36279 "validate_politicas must accept window == Duration::from_secs(1) \
36280 (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
36281 );
36282 }
36283
36284 #[test]
36285 fn rate_limit_window_projects_duration_by_copy() {
36286 // The by-copy pin: [`RateLimit::window`] returns `Duration`
36287 // by copy — `Duration` is `Copy` and the accessor must return
36288 // by value, not by reference. Peer of the sibling per-`RateLimit`
36289 // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
36290 // required-scalar `:rate` axis, extended onto the peer
36291 // per-`RateLimit` required-`Duration` copy-invariant shape —
36292 // the accessor's returned `Duration` must outlive `&self`
36293 // (multiple calls must return equal values from a
36294 // dropped-`&self` copy, since the returned scalar carries no
36295 // borrow), and calling the accessor twice on the same
36296 // RateLimit must yield the same `Duration` verbatim
36297 // (idempotent, no side effects on `&self`).
36298 //
36299 // Pins against a future silent detour that returned
36300 // `&Duration` (which would type-check but silently break every
36301 // downstream `Duration`-by-value consumer —
36302 // [`is_canonical_rate_limit_window`]'s first parameter is
36303 // `Duration`, and `&Duration` would fold to a detached copy at
36304 // the call site with a `*` deref the sibling accessors don't
36305 // need), an accidental `.window + Duration::ZERO` detour that
36306 // returned a fresh copy through an arithmetic no-op (breaking
36307 // a future `const fn` regression), or a one-arm-only accessor
36308 // that returned a canonical fallback on some sentinel input
36309 // (breaking the pass-through invariant the sibling required-
36310 // scalar accessors carry).
36311 for window in [
36312 Duration::from_secs(1),
36313 Duration::from_secs(60),
36314 Duration::from_secs(3600),
36315 Duration::ZERO,
36316 Duration::from_millis(500),
36317 ] {
36318 let rl = RateLimit { rate: 100, window };
36319 let first = rl.window();
36320 let second = rl.window();
36321 assert_eq!(
36322 first, second,
36323 "RateLimit::window must be idempotent — two successive \
36324 calls on the same &self must return the same Duration",
36325 );
36326 assert_eq!(
36327 first, window,
36328 "RateLimit::window must return :politicas :rate-limit :window \
36329 verbatim by copy — got {first:?}, expected {window:?}",
36330 );
36331 }
36332 }
36333
36334 #[test]
36335 fn placement_estrategia_default_pins_m3_canonical_value() {
36336 // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
36337 // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
36338 // active-active-across-every-named-cluster arm, the closest
36339 // canonical M3 production reference the substrate carries and
36340 // the arm the caixa-mesh `programs.yaml` fan-out already keys off
36341 // for every un-`:placement`-declared Aplicacao. Pinning the arm
36342 // here surfaces a future rebrand of the M3-canonical
36343 // distribution default (a widening to `Sharded` once the
36344 // substrate discovers hash-keyed distribution as the more
36345 // common production shape, a tightening to `SingleNode` for
36346 // stateful Erlang/OTP distributed-app-takeover semantics
36347 // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
36348 // operator pins through a future `:placement-overrides` slot)
36349 // as a deliberate test edit, not a silent contract migration.
36350 // Peer of the sibling M2 per-supervisor value pins
36351 // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
36352 // /
36353 // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
36354 // extended onto the M3 mesh-primitive-defining `:placement
36355 // :estrategia` axis.
36356 assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
36357 }
36358
36359 #[test]
36360 fn placement_strategy_default_routes_through_lifted_default() {
36361 // Composition pin: the [`Default for PlacementStrategy`] impl's
36362 // return arm must route through the substrate-canonical
36363 // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
36364 // a raw `Self::Replicated` arm. Prior to the lift the impl
36365 // carried an inline `Self::Replicated` arm with no compile-time
36366 // link back to the shared M3-canonical `Replicated` arm the
36367 // paired [`Default for Placement`] impl's struct-literal
36368 // `estrategia` field, the serde-side `#[serde(default)]` on
36369 // [`Placement::estrategia`] that resolves an author-omitted
36370 // wire-form `:placement :estrategia` scalar through the impl,
36371 // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
36372 // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
36373 // routes through [`Placement::default`] which routes through the
36374 // strategy default) all key off — so a future rebrand of the
36375 // M3-canonical distribution default would have had to be threaded
36376 // through the `Default` impl and the three peer routes in
36377 // lockstep or the four consumers would silently split. Byte-
36378 // parity against the lifted constant closes the split. Peer of
36379 // the sibling
36380 // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
36381 // /
36382 // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
36383 // composition pins on the M2 per-supervisor axes.
36384 assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
36385 }
36386
36387 #[test]
36388 fn placement_default_estrategia_routes_through_lifted_default() {
36389 // Composition pin: the [`Default for Placement`] impl's
36390 // struct-literal `estrategia` field must route through the
36391 // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
36392 // `pub const` (either directly, or via the [`PlacementStrategy::default`]
36393 // impl that the sibling
36394 // `placement_strategy_default_routes_through_lifted_default` pin
36395 // already routes onto the constant). Structurally: every
36396 // `Placement::default()` call must yield an `estrategia` field
36397 // byte-equal to the lifted constant so the two paired defaults —
36398 // the [`Default for PlacementStrategy`] impl arm and the
36399 // struct-literal default arm here — cannot silently split on any
36400 // future M3-canonical distribution-default rebrand. Peer of the
36401 // sibling M2
36402 // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
36403 // byte-parity pin on the [`Default for SupervisorSpec`]
36404 // struct-literal `estrategia` field extended onto the M3
36405 // mesh-primitive-defining slot family.
36406 assert_eq!(
36407 Placement::default().estrategia,
36408 PLACEMENT_ESTRATEGIA_DEFAULT,
36409 );
36410 }
36411
36412 #[test]
36413 fn placement_serde_default_estrategia_routes_through_lifted_default() {
36414 // Composition pin: the serde-side `#[serde(default)]` on
36415 // [`Placement::estrategia`] — the wire-format author-omitted
36416 // `:placement :estrategia` arm — must resolve onto the substrate-
36417 // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
36418 // (via the [`Default for PlacementStrategy`] impl the sibling
36419 // `placement_strategy_default_routes_through_lifted_default` pin
36420 // already routes onto the constant). Structurally: a `Placement`
36421 // deserialized from a payload that omits the `estrategia` key
36422 // must yield an `estrategia` field byte-equal to the lifted
36423 // constant, so the wire-format author-omitted arm and the
36424 // [`PlacementStrategy::default`] impl arm cannot silently split
36425 // on any future M3-canonical distribution-default rebrand. Peer
36426 // of the sibling M2
36427 // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
36428 // byte-parity pin on the wire-format author-omitted `:children
36429 // :restart` scalar extended onto the M3 mesh-primitive-defining
36430 // slot family.
36431 let omitted: Placement = serde_json::from_str("{}")
36432 .expect("Placement must deserialize with the estrategia key omitted");
36433 assert_eq!(
36434 omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
36435 "an author-omitted :placement :estrategia slot must degrade onto \
36436 the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
36437 {:?}, expected {:?})",
36438 omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
36439 );
36440 }
36441
36442 // ── contrato_target_ctors! fold pins ────────────────────────────────
36443 //
36444 // Fixture edge triple + payload-field-name label pair for every
36445 // `contrato_target_ctors!`-generated ctor pin below. Kept as
36446 // non-default `("cart", "catalog", "wasi:http/proxy")` +
36447 // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
36448 // the fixture default doesn't silently pass. Peer of the sibling
36449 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
36450 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
36451 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
36452 // `missing_entry_ctor_matches_struct_literal_wrap` /
36453 // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
36454 // four `LayoutError` constructor families each closed on their
36455 // sibling envelopes.
36456 fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
36457 (
36458 "cart".to_string(),
36459 "catalog".to_string(),
36460 "wasi:http/proxy".to_string(),
36461 WitTarget::HTTP_FIELD_NAME,
36462 )
36463 }
36464
36465 #[test]
36466 fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
36467 // Equivalence pin: the ctor produces byte-equal
36468 // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
36469 // coded struct-literal on the same edge fixture, so the fold
36470 // cannot silently drift on any future field-addition /
36471 // reordering / string-conversion tweak on the variant. Peer of
36472 // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
36473 // (17dd504) / the four `LayoutError` family equivalence pins.
36474 let (de, para, wit, expected) = contrato_target_ctor_fixture();
36475 let lifted = AplicacaoError::contrato_wrong_target(
36476 (de.clone(), para.clone(), wit.clone()),
36477 expected,
36478 );
36479 let struct_literal = AplicacaoError::ContratoWrongTarget {
36480 de,
36481 para,
36482 wit,
36483 expected,
36484 };
36485 assert_eq!(lifted, struct_literal);
36486 }
36487
36488 #[test]
36489 fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
36490 // Equivalence pin peer of the sibling
36491 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
36492 // on the paired `ContratoMissingTarget` variant of the same
36493 // four-slot envelope shape the `contrato_target_ctors!` macro
36494 // closes.
36495 let (de, para, wit, expected) = contrato_target_ctor_fixture();
36496 let lifted = AplicacaoError::contrato_missing_target(
36497 (de.clone(), para.clone(), wit.clone()),
36498 expected,
36499 );
36500 let struct_literal = AplicacaoError::ContratoMissingTarget {
36501 de,
36502 para,
36503 wit,
36504 expected,
36505 };
36506 assert_eq!(lifted, struct_literal);
36507 }
36508
36509 #[test]
36510 fn contrato_target_ctors_route_edge_triple_through_verbatim() {
36511 // Routing pin: the `(de, para, wit)` triple threads verbatim
36512 // onto same-named fields on both generated ctors, no wrapper-
36513 // side lowercase / trim / re-order. Sweeps a non-default triple
36514 // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
36515 // wrapper-side transformation surfaces here rather than at a
36516 // downstream diagnostic-shape drift. Sibling of
36517 // `entrada_host_invalid_ctor_routes_host_through_to_string`
36518 // (17dd504) on the paired triple-carrying envelope.
36519 let edge = (
36520 "cart-svc".to_string(),
36521 "catalog-v2".to_string(),
36522 "nats:pub-sub".to_string(),
36523 );
36524 let wrong =
36525 AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
36526 let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
36527 let AplicacaoError::ContratoWrongTarget {
36528 de: wde,
36529 para: wpara,
36530 wit: wwit,
36531 ..
36532 } = wrong
36533 else {
36534 panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
36535 };
36536 let AplicacaoError::ContratoMissingTarget {
36537 de: mde,
36538 para: mpara,
36539 wit: mwit,
36540 ..
36541 } = missing
36542 else {
36543 panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
36544 };
36545 assert_eq!(wde, "cart-svc");
36546 assert_eq!(wpara, "catalog-v2");
36547 assert_eq!(wwit, "nats:pub-sub");
36548 assert_eq!(mde, "cart-svc");
36549 assert_eq!(mpara, "catalog-v2");
36550 assert_eq!(mwit, "nats:pub-sub");
36551 }
36552
36553 #[test]
36554 fn contrato_target_ctors_route_expected_through_verbatim() {
36555 // Routing pin: the `expected: &'static str` label threads
36556 // verbatim (identity, not copy-and-transform) onto the
36557 // `expected` field of both variants, so the four canonical
36558 // labels [`WitTarget::HTTP_FIELD_NAME`] /
36559 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
36560 // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
36561 // pointer-equal (not merely value-equal) references — a wrapper-
36562 // side `.to_string()` / `Cow::Owned` promotion would break the
36563 // `&'static str` contract downstream consumers depend on.
36564 for label in [
36565 WitTarget::HTTP_FIELD_NAME,
36566 WitTarget::PUBSUB_FIELD_NAME,
36567 WitTarget::STORE_FIELD_NAME,
36568 WitTarget::CAPABILITY_EXPECTED,
36569 ] {
36570 let (de, para, wit, _) = contrato_target_ctor_fixture();
36571 let wrong = AplicacaoError::contrato_wrong_target(
36572 (de.clone(), para.clone(), wit.clone()),
36573 label,
36574 );
36575 let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
36576 match wrong {
36577 AplicacaoError::ContratoWrongTarget { expected, .. } => {
36578 assert!(
36579 std::ptr::eq(expected.as_ptr(), label.as_ptr())
36580 && expected.len() == label.len(),
36581 "contrato_wrong_target must thread the &'static str \
36582 label pointer-equal onto the `expected` field \
36583 (label = {label:?})",
36584 );
36585 }
36586 other => panic!("expected ContratoWrongTarget, got {other:?}"),
36587 }
36588 match missing {
36589 AplicacaoError::ContratoMissingTarget { expected, .. } => {
36590 assert!(
36591 std::ptr::eq(expected.as_ptr(), label.as_ptr())
36592 && expected.len() == label.len(),
36593 "contrato_missing_target must thread the &'static \
36594 str label pointer-equal onto the `expected` field \
36595 (label = {label:?})",
36596 );
36597 }
36598 other => panic!("expected ContratoMissingTarget, got {other:?}"),
36599 }
36600 }
36601 }
36602
36603 // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
36604 //
36605 // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
36606 // ctor pin below. Kept as non-default `("cart", "catalog")` so a
36607 // byte-equality mistake against the fixture default doesn't silently
36608 // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
36609 // triple + expected-label envelope on
36610 // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
36611 // struct_literal_wrap` (17dd504, host + reason envelope on
36612 // `entrada_host_invalid`) / the four `LayoutError` family
36613 // equivalence pins.
36614 fn contrato_empty_pair_ctor_fixture() -> (String, String) {
36615 ("cart".to_string(), "catalog".to_string())
36616 }
36617
36618 #[test]
36619 fn empty_wit_ctor_matches_struct_literal_wrap() {
36620 // Equivalence pin: the ctor produces byte-equal
36621 // `AplicacaoError::EmptyWit` to the pre-lift open-coded
36622 // struct-literal on the same edge pair, so the fold cannot
36623 // silently drift on any future field-addition / reordering /
36624 // string-conversion tweak on the variant. Peer of the sibling
36625 // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
36626 // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
36627 // (17dd504) / the four `LayoutError` family equivalence pins.
36628 let (de, para) = contrato_empty_pair_ctor_fixture();
36629 let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
36630 let struct_literal = AplicacaoError::EmptyWit { de, para };
36631 assert_eq!(lifted, struct_literal);
36632 }
36633
36634 #[test]
36635 fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
36636 // Equivalence pin peer of the sibling
36637 // `empty_wit_ctor_matches_struct_literal_wrap` above on the
36638 // paired `ContratoEndpointEmpty` variant of the same two-slot
36639 // envelope shape the `contrato_empty_pair_ctors!` macro closes.
36640 let (de, para) = contrato_empty_pair_ctor_fixture();
36641 let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
36642 let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
36643 assert_eq!(lifted, struct_literal);
36644 }
36645
36646 #[test]
36647 fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
36648 // Equivalence pin peer of the sibling
36649 // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
36650 // above on the paired `ContratoSubjectEmpty` variant of the
36651 // same two-slot envelope shape.
36652 let (de, para) = contrato_empty_pair_ctor_fixture();
36653 let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
36654 let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
36655 assert_eq!(lifted, struct_literal);
36656 }
36657
36658 #[test]
36659 fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
36660 // Equivalence pin peer of the sibling
36661 // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
36662 // above on the paired `ContratoSlotEmpty` variant of the same
36663 // two-slot envelope shape.
36664 let (de, para) = contrato_empty_pair_ctor_fixture();
36665 let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
36666 let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
36667 assert_eq!(lifted, struct_literal);
36668 }
36669
36670 #[test]
36671 fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
36672 // Routing pin: the `(de, para)` pair threads verbatim onto
36673 // same-named fields on all four generated ctors, no wrapper-
36674 // side lowercase / trim / re-order. Sweeps a non-default pair
36675 // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
36676 // transformation surfaces here rather than at a downstream
36677 // diagnostic-shape drift. Sibling of
36678 // `contrato_target_ctors_route_edge_triple_through_verbatim`
36679 // (14b81d5) on the paired triple-carrying envelope and of
36680 // `entrada_host_invalid_ctor_routes_host_through_to_string`
36681 // (17dd504) on the sibling `{ host, reason }` envelope.
36682 let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
36683 let variants: [(AplicacaoError, &'static str); 4] = [
36684 (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
36685 (
36686 AplicacaoError::contrato_endpoint_empty(edge.clone()),
36687 "ContratoEndpointEmpty",
36688 ),
36689 (
36690 AplicacaoError::contrato_subject_empty(edge.clone()),
36691 "ContratoSubjectEmpty",
36692 ),
36693 (
36694 AplicacaoError::contrato_slot_empty(edge.clone()),
36695 "ContratoSlotEmpty",
36696 ),
36697 ];
36698 for (built, label) in variants {
36699 let (de, para) = match built {
36700 AplicacaoError::EmptyWit { de, para }
36701 | AplicacaoError::ContratoEndpointEmpty { de, para }
36702 | AplicacaoError::ContratoSubjectEmpty { de, para }
36703 | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
36704 other => panic!("expected {label} pair variant, got {other:?}"),
36705 };
36706 assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
36707 assert_eq!(
36708 para, "catalog-v2",
36709 "para field on {label} must thread verbatim",
36710 );
36711 }
36712 }
36713
36714 // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
36715 //
36716 // Fixture edge pair + value + reason for every
36717 // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
36718 // as non-default `("cart", "catalog")` on the `(de, para)` pair and
36719 // fixed per-axis `<val>` / reason so a byte-equality mistake against
36720 // the fixture default doesn't silently pass. Peer of the sibling
36721 // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
36722 // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
36723 // (14b81d5, triple + expected-label envelope on
36724 // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
36725 // struct_literal_wrap` (17dd504, host + reason envelope on
36726 // `entrada_host_invalid`).
36727 fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
36728 ("cart".to_string(), "catalog".to_string())
36729 }
36730
36731 #[test]
36732 fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
36733 // Equivalence pin: the ctor produces byte-equal
36734 // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
36735 // open-coded struct-literal on the same
36736 // `(edge_pair, endpoint, reason)` triple, so the fold cannot
36737 // silently drift on any future field-addition / reordering /
36738 // string-conversion tweak on the variant. Peer of the sibling
36739 // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
36740 // (8580068) on the paired two-slot envelope of the same
36741 // `{ de, para, ... }` prefix, and of
36742 // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
36743 // (17dd504) on the sibling `{ <field>: String, reason: String }`
36744 // two-slot envelope.
36745 let (de, para) = contrato_pair_value_reason_ctor_fixture();
36746 let endpoint = "/charge";
36747 let reason = "sample reason text";
36748 let lifted =
36749 AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
36750 let struct_literal = AplicacaoError::ContratoEndpointInvalid {
36751 de,
36752 para,
36753 endpoint: endpoint.to_string(),
36754 reason: reason.to_string(),
36755 };
36756 assert_eq!(lifted, struct_literal);
36757 }
36758
36759 #[test]
36760 fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
36761 // Equivalence pin peer of the sibling
36762 // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
36763 // above on the paired `ContratoSubjectInvalid` variant of the
36764 // same four-slot envelope shape the
36765 // `contrato_pair_value_reason_ctors!` macro closes.
36766 let (de, para) = contrato_pair_value_reason_ctor_fixture();
36767 let subject = "checkout.events.charge.failed";
36768 let reason = "sample reason text";
36769 let lifted =
36770 AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
36771 let struct_literal = AplicacaoError::ContratoSubjectInvalid {
36772 de,
36773 para,
36774 subject: subject.to_string(),
36775 reason: reason.to_string(),
36776 };
36777 assert_eq!(lifted, struct_literal);
36778 }
36779
36780 #[test]
36781 fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
36782 // Equivalence pin peer of the sibling
36783 // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
36784 // above on the paired `ContratoSlotInvalid` variant of the same
36785 // four-slot envelope shape.
36786 let (de, para) = contrato_pair_value_reason_ctor_fixture();
36787 let slot = "checkout/$orderId";
36788 let reason = "sample reason text";
36789 let lifted =
36790 AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
36791 let struct_literal = AplicacaoError::ContratoSlotInvalid {
36792 de,
36793 para,
36794 slot: slot.to_string(),
36795 reason: reason.to_string(),
36796 };
36797 assert_eq!(lifted, struct_literal);
36798 }
36799
36800 #[test]
36801 fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
36802 // Equivalence pin peer of the sibling
36803 // `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
36804 // on the paired `ContratoWitInvalid` variant of the same four-
36805 // slot envelope shape the `contrato_pair_value_reason_ctors!`
36806 // macro closes. Fold pinned this test lands with the last
36807 // `{ de, para, <field>: String, reason: String }` open-coded
36808 // struct-literal inside [`WitContract::target`] rewritten to
36809 // route through the macro-generated
36810 // [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
36811 // between the ctor and the pre-lift struct-literal trips this
36812 // pin ahead of any downstream diagnostic-shape drift on the
36813 // `:contratos :wit` axis.
36814 let (de, para) = contrato_pair_value_reason_ctor_fixture();
36815 let wit = "wasi-http/proxy";
36816 let reason = "sample reason text";
36817 let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
36818 let struct_literal = AplicacaoError::ContratoWitInvalid {
36819 de,
36820 para,
36821 wit: wit.to_string(),
36822 reason: reason.to_string(),
36823 };
36824 assert_eq!(lifted, struct_literal);
36825 }
36826
36827 #[test]
36828 fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
36829 // Routing pin: the `(de, para)` pair threads verbatim onto
36830 // same-named fields on all four generated ctors, no wrapper-
36831 // side lowercase / trim / re-order. Sweeps a non-default pair
36832 // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
36833 // transformation surfaces here rather than at a downstream
36834 // diagnostic-shape drift. Sibling of
36835 // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
36836 // (8580068) on the paired two-slot envelope and of
36837 // `contrato_target_ctors_route_edge_triple_through_verbatim`
36838 // (14b81d5) on the paired triple-carrying envelope.
36839 let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
36840 let variants: [(AplicacaoError, &'static str); 4] = [
36841 (
36842 AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
36843 "ContratoEndpointInvalid",
36844 ),
36845 (
36846 AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
36847 "ContratoSubjectInvalid",
36848 ),
36849 (
36850 AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
36851 "ContratoSlotInvalid",
36852 ),
36853 (
36854 AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
36855 "ContratoWitInvalid",
36856 ),
36857 ];
36858 for (built, label) in variants {
36859 let (de, para) = match built {
36860 AplicacaoError::ContratoEndpointInvalid { de, para, .. }
36861 | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
36862 | AplicacaoError::ContratoSlotInvalid { de, para, .. }
36863 | AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
36864 other => panic!("expected {label} pair variant, got {other:?}"),
36865 };
36866 assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
36867 assert_eq!(
36868 para, "catalog-v2",
36869 "para field on {label} must thread verbatim",
36870 );
36871 }
36872 }
36873
36874 #[test]
36875 fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
36876 // Cross-arm invariance pin — the four ctors all route
36877 // `reason: impl Into<String>` verbatim onto their respective
36878 // typed variants through the shared
36879 // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
36880 // pair (`&str` literal, `format!` output) against every ctor to
36881 // pin that no per-arm wrapper transformation drifted in against
36882 // the uniform macro-generated body. Peer of
36883 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
36884 // (981060b) on the sibling two-slot envelope's cross-arm sweep.
36885 let edge = || ("cart".to_string(), "catalog".to_string());
36886 let via_literal = "literal reason text";
36887 let via_format = format!("{} reason text", "literal");
36888 assert_eq!(
36889 AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
36890 AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
36891 );
36892 assert_eq!(
36893 AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
36894 AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
36895 );
36896 assert_eq!(
36897 AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
36898 AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
36899 );
36900 assert_eq!(
36901 AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
36902 AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
36903 );
36904 }
36905
36906 // ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
36907 //
36908 // Fail-before-pass-after pins for the standalone
36909 // [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
36910 // (see the paired doc-block above the ctor definition) — the fold of
36911 // the last open-coded three-slot `{ de, para, endpoint: <val>
36912 // .to_string() }` struct-literal inside [`WitContract::target`]'s
36913 // HTTP-arm leading-slash gate onto one substrate primitive on the
36914 // envelope. A byte-mismatched ctor body would trip the equivalence
36915 // pin first, ahead of any downstream diagnostic-shape drift.
36916 //
36917 // Peer of the sibling standalone-ctor equivalence pins on the peer
36918 // one-off variants across caixa-core:
36919 // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
36920 // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
36921 // on the paired two-slot and four-slot per-`:contratos :endpoint`
36922 // envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
36923 // and `child_versao_invalid_ctor_matches_struct_literal_wrap`
36924 // (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
36925 // reason }` two- and three-slot envelopes; the
36926 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
36927 // pin on the sibling standalone `{ host, reason }` two-slot ctor.
36928 fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
36929 ("cart".to_string(), "catalog".to_string())
36930 }
36931
36932 #[test]
36933 fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
36934 // Equivalence pin: the ctor produces byte-equal
36935 // `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
36936 // open-coded struct-literal on the same `(edge_pair, endpoint)`
36937 // pair, so the fold cannot silently drift on any future
36938 // field-addition / reordering / string-conversion tweak on the
36939 // variant. Same equivalence-pin shape as the sibling
36940 // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
36941 // (8580068) on the paired two-slot envelope and
36942 // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
36943 // (14e13f1) on the paired four-slot envelope of the same
36944 // `{ de, para, ... }`-prefix `:endpoint` axis.
36945 let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
36946 let endpoint = "charge";
36947 let lifted =
36948 AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
36949 let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
36950 de,
36951 para,
36952 endpoint: endpoint.to_string(),
36953 };
36954 assert_eq!(lifted, struct_literal);
36955 }
36956
36957 #[test]
36958 fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
36959 // Routing pin on the `(de, para)` axis: sweep a non-default
36960 // pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
36961 // lowercase / trim / re-order surfaces here rather than at a
36962 // downstream diagnostic-shape drift. Peer of
36963 // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
36964 // (8580068) on the paired two-slot envelope and
36965 // `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
36966 // (14e13f1) on the paired four-slot envelope of the same
36967 // `{ de, para, ... }`-prefix `:contratos` axis.
36968 let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
36969 let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
36970 match built {
36971 AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
36972 assert_eq!(de, "cart-svc", "de field must thread verbatim");
36973 assert_eq!(para, "catalog-v2", "para field must thread verbatim");
36974 }
36975 other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
36976 }
36977 }
36978
36979 #[test]
36980 fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
36981 // Routing pin on the `endpoint: &str` axis: sweep a non-default
36982 // value (`"charge"` — no leading `/`, the exact shape the
36983 // [`WitContract::target`] HTTP-arm leading-slash gate rejects)
36984 // through the sole payload-carrier constructor axis so any
36985 // wrapper-side transformation on the `endpoint.to_string()`
36986 // one-field construction surfaces here rather than at a
36987 // downstream diagnostic-shape mismatch. Sibling of
36988 // `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
36989 // (14e13f1) on the sibling four-slot envelope's payload-carrier
36990 // routing pin.
36991 let edge = || ("cart".to_string(), "catalog".to_string());
36992 let via_literal = "charge";
36993 let via_string = String::from("charge");
36994 assert_eq!(
36995 AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
36996 AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
36997 );
36998 }
36999
37000 // ── contrato_self_loop standalone ctor pins ─────────────────────────
37001 //
37002 // Fail-before-pass-after pins for the standalone
37003 // [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
37004 // doc-block above the ctor definition) — the fold of the last
37005 // open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
37006 // <ct>.world_ref().to_string() }` struct-literal inside
37007 // [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
37008 // arm onto one substrate primitive on the [`AplicacaoError`]
37009 // envelope, projecting through the paired [`WitContract::source`] /
37010 // [`WitContract::world_ref`] scalar accessors on the substrate
37011 // primitive. A byte-mismatched ctor body would trip the equivalence
37012 // pin first, ahead of any downstream diagnostic-shape drift.
37013 //
37014 // Peer of the sibling standalone-ctor equivalence pins on the peer
37015 // one-off variants across caixa-core:
37016 // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
37017 // (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
37018 // envelope, the sibling
37019 // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
37020 // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
37021 // the paired two-slot and four-slot per-`:contratos :endpoint`
37022 // envelopes, and the sibling
37023 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
37024 // pin on the sibling standalone `{ host, reason }` two-slot ctor.
37025 fn contrato_self_loop_ctor_fixture() -> WitContract {
37026 WitContract {
37027 de: "cart".to_string(),
37028 para: "cart".to_string(),
37029 wit: "wasi:http/proxy".to_string(),
37030 endpoint: Some("/self".to_string()),
37031 subject: None,
37032 slot: None,
37033 }
37034 }
37035
37036 #[test]
37037 fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
37038 // Equivalence pin: the ctor produces byte-equal
37039 // `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
37040 // struct-literal that read the same two fields through
37041 // [`WitContract::source`] and [`WitContract::world_ref`]. Guards
37042 // any future field-addition / reordering / string-conversion
37043 // tweak on the variant. Same equivalence-pin shape as the
37044 // sibling `contrato_endpoint_not_absolute_ctor_matches_
37045 // struct_literal_wrap` (cdf1a2c) on the paired three-slot
37046 // per-`:contratos :endpoint` envelope.
37047 let contract = contrato_self_loop_ctor_fixture();
37048 let lifted = AplicacaoError::contrato_self_loop(&contract);
37049 let struct_literal = AplicacaoError::ContratoSelfLoop {
37050 caixa: contract.source().to_string(),
37051 wit: contract.world_ref().to_string(),
37052 };
37053 assert_eq!(lifted, struct_literal);
37054 }
37055
37056 #[test]
37057 fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
37058 // Routing pin sweeping non-default `caixa` and `:wit` values
37059 // (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
37060 // [`WitContract::source`] / [`WitContract::world_ref`] accessor
37061 // axes so any wrapper-side lowercase / trim / re-order surfaces
37062 // here rather than at a downstream diagnostic-shape drift.
37063 // Peer of the sibling
37064 // `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
37065 // (cdf1a2c) routing pin on the sibling three-slot envelope.
37066 let contract = WitContract {
37067 de: "catalog-v2".to_string(),
37068 para: "catalog-v2".to_string(),
37069 wit: "nats:pub-sub".to_string(),
37070 endpoint: None,
37071 subject: Some("orders.>".to_string()),
37072 slot: None,
37073 };
37074 let built = AplicacaoError::contrato_self_loop(&contract);
37075 match built {
37076 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
37077 assert_eq!(
37078 caixa, "catalog-v2",
37079 "caixa slot must thread WitContract::source() verbatim"
37080 );
37081 assert_eq!(
37082 wit, "nats:pub-sub",
37083 "wit slot must thread WitContract::world_ref() verbatim"
37084 );
37085 }
37086 other => panic!("expected ContratoSelfLoop, got {other:?}"),
37087 }
37088 }
37089
37090 #[test]
37091 fn contrato_self_loop_ctor_projects_source_field_not_destination() {
37092 // Accessor-fidelity pin: the ctor's `caixa` slot keys off the
37093 // [`WitContract::source`] accessor (matching the pre-lift open-
37094 // coded body's field selection), not [`WitContract::destination`].
37095 // Under today's `WitContract::is_self_loop()`-gated call site
37096 // the two are equal by that predicate's own contract, but a
37097 // future consumer that constructs the ctor against a not-yet-
37098 // gated candidate contract — an M4
37099 // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
37100 // checking a per-`(:de, :para)`-patched candidate before the
37101 // self-loop gate re-fires, a per-tenant per-Aplicacao overlay
37102 // resolver rejecting a self-edge introduced by a cluster-local
37103 // `:contratos` override — needs the pre-lift field selection
37104 // pinned so a silent `.destination()` swap at the ctor body
37105 // surfaces here rather than at a downstream diagnostic mis-
37106 // attribution far from the self-loop diagnostic's owner
37107 // (the `caller` side per MESH-COMPOSITION §III.1's typed edge
37108 // direction).
37109 //
37110 // Deliberately constructs a non-self-loop pair (`"cart" →
37111 // "catalog"`) so the two accessors yield distinct bytes on the
37112 // fixture — a `.destination()` swap at the ctor body would land
37113 // `"catalog"` in the `caixa` slot instead of `"cart"` and trip
37114 // the assertion here.
37115 let contract = WitContract {
37116 de: "cart".to_string(),
37117 para: "catalog".to_string(),
37118 wit: "wasi:http/proxy".to_string(),
37119 endpoint: Some("/charge".to_string()),
37120 subject: None,
37121 slot: None,
37122 };
37123 let built = AplicacaoError::contrato_self_loop(&contract);
37124 match built {
37125 AplicacaoError::ContratoSelfLoop { caixa, .. } => {
37126 assert_eq!(
37127 caixa, "cart",
37128 "caixa slot must project WitContract::source() (not destination)"
37129 );
37130 }
37131 other => panic!("expected ContratoSelfLoop, got {other:?}"),
37132 }
37133 }
37134
37135 // Pin the four-slot `{ de, para, wit, target }` per-`:contratos`
37136 // whole-edge-dedup sibling of the two-slot per-`:contratos` envelope
37137 // family — the sole per-axis ctor projecting through both
37138 // [`WitContract::edge_triple`] (on the leading `de` / `para` / `wit`
37139 // triple) and [`WitTarget::label`] (on the trailing `target` slot).
37140 // Equivalence pin locks the ctor body to the pre-lift struct-literal
37141 // shape under `PartialEq`, so any accessor-side field-selection drift
37142 // or per-arm wrapper transformation surfaces here as a build-time
37143 // test failure rather than at a downstream diagnostic-shape mismatch
37144 // far from the substrate primitive. Peer of the sibling
37145 // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe)
37146 // equivalence pin on the paired two-slot `{ caixa, wit }` per-self-
37147 // edge envelope's `WitContract`-projection ctor.
37148 #[test]
37149 fn contrato_duplicate_ctor_matches_struct_literal_wrap() {
37150 let contract = contrato_self_loop_ctor_fixture();
37151 let target = contract.target_projected();
37152 let lifted = AplicacaoError::contrato_duplicate(&contract, &target);
37153 let (de, para, wit) = contract.edge_triple();
37154 let struct_literal = AplicacaoError::ContratoDuplicate {
37155 de,
37156 para,
37157 wit,
37158 target: target.label(),
37159 };
37160 assert_eq!(lifted, struct_literal);
37161 }
37162
37163 // Routing pin sweeping a non-self-loop pair (`"cart" → "catalog"`) so
37164 // the paired [`WitContract::edge_triple`] projection's three axes
37165 // (`de`, `para`, `wit`) and the [`WitTarget::label`] projection on
37166 // the `target` axis all yield distinct bytes on the fixture — any
37167 // wrapper-side re-order / accessor-swap on the four axes surfaces
37168 // here rather than at a downstream diagnostic-shape drift. Peer of
37169 // the sibling
37170 // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
37171 // (b30edfe) routing pin on the paired two-slot envelope.
37172 #[test]
37173 fn contrato_duplicate_ctor_routes_edge_triple_and_target_label_verbatim() {
37174 let contract = WitContract {
37175 de: "cart".to_string(),
37176 para: "catalog".to_string(),
37177 wit: "wasi:http/proxy".to_string(),
37178 endpoint: Some("/charge".to_string()),
37179 subject: None,
37180 slot: None,
37181 };
37182 let target = contract.target_projected();
37183 let built = AplicacaoError::contrato_duplicate(&contract, &target);
37184 match built {
37185 AplicacaoError::ContratoDuplicate {
37186 de,
37187 para,
37188 wit,
37189 target,
37190 } => {
37191 assert_eq!(
37192 de, "cart",
37193 "de slot must thread WitContract::edge_triple().0 verbatim"
37194 );
37195 assert_eq!(
37196 para, "catalog",
37197 "para slot must thread WitContract::edge_triple().1 verbatim"
37198 );
37199 assert_eq!(
37200 wit, "wasi:http/proxy",
37201 "wit slot must thread WitContract::edge_triple().2 verbatim"
37202 );
37203 assert!(
37204 target.contains("/charge"),
37205 "target slot must project through WitTarget::label() \
37206 (got target = {target:?})"
37207 );
37208 }
37209 other => panic!("expected ContratoDuplicate, got {other:?}"),
37210 }
37211 }
37212
37213 // Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
37214 // macro definition (see the paired doc-block above the macro definition)
37215 // — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
37216 // uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
37217 // struct-literal onto one substrate primitive. The four per-variant
37218 // equivalence pins below (fail-before-pass-after by construction — a
37219 // byte-mismatched macro arm would trip its equivalence pin first) lock
37220 // each generated constructor to its struct-literal peer under
37221 // `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
37222 // [`AplicacaoSpec::validate_membros`], and
37223 // [`validate_no_self_membership`] on that variant produces a byte-equal
37224 // `AplicacaoError` to the pre-lift open-coded struct-literal. The
37225 // cross-axis pin that follows (non-default caixa name) routes the sole
37226 // constructor input axis through `.to_string()`, so the fold does not
37227 // silently collapse onto a fixed name.
37228 //
37229 // Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
37230 // and cross-axis `<macro>_route_caixa_through_to_string` pins on the
37231 // sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
37232 // `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
37233 // cross-axis pins on the peer three `AplicacaoError` sub-family folds
37234 // (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
37235 // `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
37236 // of the peer M2 `:behavior` envelope fold (67c31ec,
37237 // `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
37238 // `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
37239 // peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
37240
37241 #[test]
37242 fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
37243 assert_eq!(
37244 AplicacaoError::contrato_member_missing("cart"),
37245 AplicacaoError::ContratoMemberMissing {
37246 caixa: "cart".to_string(),
37247 },
37248 "generated contrato_member_missing ctor must produce byte-equal \
37249 AplicacaoError to the open-coded struct-literal wrap on the \
37250 same &str fixture",
37251 );
37252 }
37253
37254 #[test]
37255 fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
37256 assert_eq!(
37257 AplicacaoError::membro_versao_empty("cart"),
37258 AplicacaoError::MembroVersaoEmpty {
37259 caixa: "cart".to_string(),
37260 },
37261 "generated membro_versao_empty ctor must produce byte-equal \
37262 AplicacaoError to the open-coded struct-literal wrap on the \
37263 same &str fixture",
37264 );
37265 }
37266
37267 #[test]
37268 fn membro_duplicate_ctor_matches_struct_literal_wrap() {
37269 assert_eq!(
37270 AplicacaoError::membro_duplicate("cart"),
37271 AplicacaoError::MembroDuplicate {
37272 caixa: "cart".to_string(),
37273 },
37274 "generated membro_duplicate ctor must produce byte-equal \
37275 AplicacaoError to the open-coded struct-literal wrap on the \
37276 same &str fixture",
37277 );
37278 }
37279
37280 #[test]
37281 fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
37282 assert_eq!(
37283 AplicacaoError::membro_is_self_aplicacao("checkout"),
37284 AplicacaoError::MembroIsSelfAplicacao {
37285 caixa: "checkout".to_string(),
37286 },
37287 "generated membro_is_self_aplicacao ctor must produce byte-equal \
37288 AplicacaoError to the open-coded struct-literal wrap on the \
37289 same &str fixture",
37290 );
37291 }
37292
37293 #[test]
37294 fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
37295 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
37296 // &str`) through a non-default fixture name against every generated
37297 // arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
37298 // wrapper-side lowercase / trim / truncate / re-order on the
37299 // `caixa.to_string()` sole-field construction surfaces here rather
37300 // than at a downstream diagnostic-shape mismatch. Peer of the
37301 // sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
37302 // cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
37303 // envelope (db09650), extended here onto the peer `AplicacaoError`
37304 // `{ caixa: String }` envelope so every substrate-primitive ctor
37305 // family in caixa-core carrying a single-slot `{ caixa: String }`
37306 // shape guarantees the sole-field construction routes the caller's
37307 // `&str` through `.to_string()` verbatim.
37308 let name = "cache-v2";
37309 assert_eq!(
37310 AplicacaoError::contrato_member_missing(name),
37311 AplicacaoError::ContratoMemberMissing {
37312 caixa: name.to_string(),
37313 },
37314 );
37315 assert_eq!(
37316 AplicacaoError::membro_versao_empty(name),
37317 AplicacaoError::MembroVersaoEmpty {
37318 caixa: name.to_string(),
37319 },
37320 );
37321 assert_eq!(
37322 AplicacaoError::membro_duplicate(name),
37323 AplicacaoError::MembroDuplicate {
37324 caixa: name.to_string(),
37325 },
37326 );
37327 assert_eq!(
37328 AplicacaoError::membro_is_self_aplicacao(name),
37329 AplicacaoError::MembroIsSelfAplicacao {
37330 caixa: name.to_string(),
37331 },
37332 );
37333 }
37334
37335 #[test]
37336 fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
37337 assert_eq!(
37338 AplicacaoError::entrada_path_not_absolute("api/cart"),
37339 AplicacaoError::EntradaPathNotAbsolute {
37340 path: "api/cart".to_string(),
37341 },
37342 "generated entrada_path_not_absolute ctor must produce byte-equal \
37343 AplicacaoError to the open-coded struct-literal wrap on the \
37344 same &str fixture",
37345 );
37346 }
37347
37348 #[test]
37349 fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
37350 assert_eq!(
37351 AplicacaoError::entrada_path_duplicate("/api/cart"),
37352 AplicacaoError::EntradaPathDuplicate {
37353 path: "/api/cart".to_string(),
37354 },
37355 "generated entrada_path_duplicate ctor must produce byte-equal \
37356 AplicacaoError to the open-coded struct-literal wrap on the \
37357 same &str fixture",
37358 );
37359 }
37360
37361 // ── membro_versao_invalid ctor pins ────────────────────────────────
37362 //
37363 // Per-variant byte-equality + cross-axis routing pins guaranteeing the
37364 // lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
37365 // produces an `AplicacaoError` structurally identical to the pre-lift
37366 // `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
37367 // versao.to_string(), reason: reason.into() }` open-coded three-slot
37368 // struct-literal on the same `(&str, &str, reason)` fixture. Peer of
37369 // the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
37370 // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
37371 // pins on the peer `SupervisorError` `{ caixa: String, versao: String,
37372 // reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
37373 // extended here onto the paired per-`:membros :versao` axis on the
37374 // sibling `AplicacaoError` envelope so both three-slot `{ caixa,
37375 // versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
37376 // typed-error surface guarantee the shared three-field construction
37377 // routes through one substrate primitive per envelope.
37378
37379 #[test]
37380 fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
37381 let caixa = "cart";
37382 let versao = "not-a-req";
37383 let reason = "sample reason text";
37384 assert_eq!(
37385 AplicacaoError::membro_versao_invalid(caixa, versao, reason),
37386 AplicacaoError::MembroVersaoInvalid {
37387 caixa: caixa.to_string(),
37388 versao: versao.to_string(),
37389 reason: reason.to_string(),
37390 },
37391 "lifted membro_versao_invalid ctor must produce byte-equal \
37392 AplicacaoError to the open-coded struct-literal wrap on the \
37393 same (&str, &str, reason) fixture",
37394 );
37395 }
37396
37397 #[test]
37398 fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
37399 // Cross-axis pin: sweep the two `&str`-shaped constructor input
37400 // axes (`caixa`, `versao`) through non-default fixtures so any
37401 // wrapper-side lowercase / trim / truncate / re-order on either
37402 // `.to_string()` field construction surfaces here rather than at
37403 // a downstream diagnostic-shape mismatch. Peer of the sibling
37404 // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
37405 // routing pin on the peer `SupervisorError` envelope.
37406 let caixa = "Cart-V2";
37407 let versao = "0.1.0-alpha+build.42";
37408 let reason = "constructed reason";
37409 let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
37410 let AplicacaoError::MembroVersaoInvalid {
37411 caixa: got_caixa,
37412 versao: got_versao,
37413 reason: got_reason,
37414 } = err
37415 else {
37416 panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
37417 };
37418 assert_eq!(got_caixa, caixa.to_string());
37419 assert_eq!(got_versao, versao.to_string());
37420 assert_eq!(got_reason, reason.to_string());
37421 }
37422
37423 #[test]
37424 fn membro_versao_invalid_ctor_routes_reason_through_into() {
37425 // Route pin: the `reason: impl Into<String>` bound accepts both
37426 // `&str` literals and `format!(…)` / `String` outputs verbatim,
37427 // matching the sibling
37428 // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
37429 // routing pin on the peer `SupervisorError::child_versao_invalid`.
37430 // Pins the sole `AplicacaoSpec::validate_membros` wire-up's
37431 // `require_valid_versao_requirement`-delivered `reason` closure
37432 // parameter (typed `String`) picks the ctor up without a per-arm
37433 // wrapper transformation, and every future consumer that
37434 // constructs the variant from a `format!(…)` reason surfaces
37435 // byte-equal to the `&str`-literal path.
37436 let caixa = "cart";
37437 let versao = "not-a-req";
37438 let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
37439 let from_format =
37440 AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
37441 let from_string =
37442 AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
37443 assert_eq!(from_literal, from_format);
37444 assert_eq!(from_literal, from_string);
37445 }
37446
37447 #[test]
37448 fn aplicacao_path_only_ctors_route_path_through_to_string() {
37449 // Cross-axis pin: sweep the sole constructor input axis (`path:
37450 // &str`) through a non-default fixture path against every generated
37451 // arm in the [`aplicacao_path_only_ctors!`] macro, so any
37452 // wrapper-side lowercase / trim / truncate / re-order on the
37453 // `path.to_string()` sole-field construction surfaces here rather
37454 // than at a downstream diagnostic-shape mismatch. Peer of the
37455 // sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
37456 // cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
37457 // envelope (d9f6867), extended here onto the sibling
37458 // `AplicacaoError` `{ path: String }` envelope so every substrate-
37459 // primitive ctor family in caixa-core carrying a single-slot
37460 // `{ <slot>: String }` shape guarantees the sole-field construction
37461 // routes the caller's `&str` through `.to_string()` verbatim.
37462 let path = "/api/v2/checkout";
37463 assert_eq!(
37464 AplicacaoError::entrada_path_not_absolute(path),
37465 AplicacaoError::EntradaPathNotAbsolute {
37466 path: path.to_string(),
37467 },
37468 );
37469 assert_eq!(
37470 AplicacaoError::entrada_path_duplicate(path),
37471 AplicacaoError::EntradaPathDuplicate {
37472 path: path.to_string(),
37473 },
37474 );
37475 }
37476
37477 // ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
37478 //
37479 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
37480 // the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
37481 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
37482 // one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
37483 // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
37484 // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
37485 // wrapper-side truncation / re-order / silent `.into()` / silent constant-
37486 // substitution on any one variant surfaces here rather than at a downstream
37487 // per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
37488 // pins on `aplicacao_field_reason_ctors!` (981060b),
37489 // `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
37490 // (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
37491 // `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
37492 // (14b81d5), plus the sibling `DepError` / `SupervisorError` /
37493 // `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
37494 // per-envelope ctor-macro pins.
37495
37496 #[test]
37497 fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
37498 let timeout = Duration::from_micros(1_500);
37499 assert_eq!(
37500 AplicacaoError::policy_timeout_not_canonical(timeout),
37501 AplicacaoError::PolicyTimeoutNotCanonical { timeout },
37502 "generated policy_timeout_not_canonical ctor must produce byte-equal \
37503 `AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
37504 struct-literal wrap on the same `Copy`-`Duration` fixture",
37505 );
37506 }
37507
37508 #[test]
37509 fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
37510 let timeout = Duration::from_secs(3_601);
37511 assert_eq!(
37512 AplicacaoError::policy_timeout_exceeds_cap(timeout),
37513 AplicacaoError::PolicyTimeoutExceedsCap { timeout },
37514 "generated policy_timeout_exceeds_cap ctor must produce byte-equal \
37515 `AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
37516 struct-literal wrap on the same `Copy`-`Duration` fixture",
37517 );
37518 }
37519
37520 #[test]
37521 fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
37522 let retries = 47_u32;
37523 assert_eq!(
37524 AplicacaoError::policy_retries_exceeds_cap(retries),
37525 AplicacaoError::PolicyRetriesExceedsCap { retries },
37526 "generated policy_retries_exceeds_cap ctor must produce byte-equal \
37527 `AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
37528 struct-literal wrap on the same `Copy`-`u32` fixture",
37529 );
37530 }
37531
37532 #[test]
37533 fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
37534 let max_failures = 1_337_u32;
37535 assert_eq!(
37536 AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
37537 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
37538 "generated policy_breaker_max_failures_exceeds_cap ctor must produce \
37539 byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
37540 the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
37541 );
37542 }
37543
37544 #[test]
37545 fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
37546 let window = Duration::from_micros(500);
37547 assert_eq!(
37548 AplicacaoError::policy_breaker_window_not_canonical(window),
37549 AplicacaoError::PolicyBreakerWindowNotCanonical { window },
37550 "generated policy_breaker_window_not_canonical ctor must produce \
37551 byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
37552 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
37553 );
37554 }
37555
37556 #[test]
37557 fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
37558 let window = Duration::from_secs(3_700);
37559 assert_eq!(
37560 AplicacaoError::policy_breaker_window_exceeds_cap(window),
37561 AplicacaoError::PolicyBreakerWindowExceedsCap { window },
37562 "generated policy_breaker_window_exceeds_cap ctor must produce \
37563 byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
37564 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
37565 );
37566 }
37567
37568 #[test]
37569 fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
37570 let rate = 1_000_001_u32;
37571 assert_eq!(
37572 AplicacaoError::policy_rate_limit_exceeds_cap(rate),
37573 AplicacaoError::PolicyRateLimitExceedsCap { rate },
37574 "generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
37575 `AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
37576 struct-literal wrap on the same `Copy`-`u32` fixture",
37577 );
37578 }
37579
37580 #[test]
37581 fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
37582 let window = Duration::from_secs(15);
37583 assert_eq!(
37584 AplicacaoError::policy_rate_limit_window_not_canonical(window),
37585 AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
37586 "generated policy_rate_limit_window_not_canonical ctor must produce \
37587 byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
37588 the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
37589 fixture",
37590 );
37591 }
37592
37593 #[test]
37594 fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
37595 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
37596 // constructor input axis through a non-default `Copy` fixture against
37597 // every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
37598 // wrapper-side silent `.into()` / silent constant-substitution / silent
37599 // field re-name away from the canonical `timeout | retries |
37600 // max_failures | window | rate` axes on any one variant, or a
37601 // `Duration | u32` axis silently rerouted through some other `Copy`
37602 // coercion, surfaces here rather than at a downstream per-`:politicas`
37603 // diagnostic-shape drift. Peer of the sibling
37604 // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
37605 // (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
37606 // (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
37607 // (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
37608 // (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
37609 // families, extended here onto the last M3 per-`:politicas` per-axis
37610 // `AplicacaoError` variant family folded onto a substrate primitive.
37611 //
37612 // Fixtures picked out of each variant's accept-set boundary rather
37613 // than the default value so a silent constant-substitution to `0` /
37614 // `Duration::ZERO` / any per-variant sentinel surfaces here on the
37615 // structural-equality assertion. The two `Duration` fixtures pick the
37616 // sub-millisecond and above-cap ends respectively; the three `u32`
37617 // fixtures pick above-cap magnitudes for `retries` / `max_failures` /
37618 // `rate` respectively (each variant's cap sits well below the fixture
37619 // so the pre-lift struct-literal wrap the fixture is compared against
37620 // is the same shape the pre-lift wire-up produced).
37621 let sub_ms = Duration::from_micros(1_500);
37622 let above_hour = Duration::from_secs(3_700);
37623 let non_canonical_rl_window = Duration::from_secs(15);
37624 assert_eq!(
37625 AplicacaoError::policy_timeout_not_canonical(sub_ms),
37626 AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
37627 );
37628 assert_eq!(
37629 AplicacaoError::policy_timeout_exceeds_cap(above_hour),
37630 AplicacaoError::PolicyTimeoutExceedsCap {
37631 timeout: above_hour,
37632 },
37633 );
37634 assert_eq!(
37635 AplicacaoError::policy_retries_exceeds_cap(47),
37636 AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
37637 );
37638 assert_eq!(
37639 AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
37640 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
37641 max_failures: 1_337,
37642 },
37643 );
37644 assert_eq!(
37645 AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
37646 AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
37647 );
37648 assert_eq!(
37649 AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
37650 AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
37651 );
37652 assert_eq!(
37653 AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
37654 AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
37655 );
37656 assert_eq!(
37657 AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
37658 AplicacaoError::PolicyRateLimitWindowNotCanonical {
37659 window: non_canonical_rl_window,
37660 },
37661 );
37662 }
37663
37664 #[test]
37665 fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
37666 // Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
37667 // every generated ctor `const fn` so a caller can pin an
37668 // `AplicacaoError` at compile time — the same zero-runtime-work
37669 // property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
37670 // closure carried on its `Copy`-pass-through construction path (no
37671 // `.to_string()` / `.into()` allocation, no branching). If any future
37672 // edit silently drops the `const` qualifier from the macro body the
37673 // per-arm `const` bindings below fail to compile, which surfaces the
37674 // regression at the substrate-primitive definition rather than at
37675 // some downstream consumer that had come to rely on the `const`-
37676 // constructibility. Peer of the sibling per-variant
37677 // `_ctor_matches_struct_literal_wrap` pins above on the runtime-
37678 // equality axis; this pin closes the compile-time-const axis on the
37679 // same generated family.
37680 const TIMEOUT_NC: AplicacaoError =
37681 AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
37682 const TIMEOUT_CAP: AplicacaoError =
37683 AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
37684 const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
37685 const MAX_FAIL_CAP: AplicacaoError =
37686 AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
37687 const CB_WIN_NC: AplicacaoError =
37688 AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
37689 const CB_WIN_CAP: AplicacaoError =
37690 AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
37691 const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
37692 const RL_WIN_NC: AplicacaoError =
37693 AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
37694 assert!(matches!(
37695 TIMEOUT_NC,
37696 AplicacaoError::PolicyTimeoutNotCanonical { .. }
37697 ));
37698 assert!(matches!(
37699 TIMEOUT_CAP,
37700 AplicacaoError::PolicyTimeoutExceedsCap { .. }
37701 ));
37702 assert!(matches!(
37703 RETRIES_CAP,
37704 AplicacaoError::PolicyRetriesExceedsCap { .. }
37705 ));
37706 assert!(matches!(
37707 MAX_FAIL_CAP,
37708 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
37709 ));
37710 assert!(matches!(
37711 CB_WIN_NC,
37712 AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
37713 ));
37714 assert!(matches!(
37715 CB_WIN_CAP,
37716 AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
37717 ));
37718 assert!(matches!(
37719 RATE_CAP,
37720 AplicacaoError::PolicyRateLimitExceedsCap { .. }
37721 ));
37722 assert!(matches!(
37723 RL_WIN_NC,
37724 AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
37725 ));
37726 }
37727
37728 // Per-variant equivalence + routing pins for the
37729 // [`AplicacaoError::placement_cluster_duplicate`] standalone ctor
37730 // (see the paired doc-block above the ctor definition) — the
37731 // generated `pub fn placement_cluster_duplicate(cluster: &str) ->
37732 // Self` inherent constructor folds the uniform
37733 // `Self::PlacementClusterDuplicate { cluster: cluster.to_string() }`
37734 // one-field struct-literal onto one substrate primitive. Same
37735 // shape as the sibling
37736 // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) /
37737 // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
37738 // (cdf1a2c) equivalence pins on the paired standalone `AplicacaoError`
37739 // ctors — extended here onto the single-slot per-`:placement
37740 // :clusters` dedup-envelope.
37741
37742 #[test]
37743 fn placement_cluster_duplicate_ctor_matches_struct_literal_wrap() {
37744 // Equivalence pin: the ctor produces byte-equal
37745 // `AplicacaoError::PlacementClusterDuplicate` to the pre-lift
37746 // open-coded struct-literal that read the same field through
37747 // `c.clone()` at the caller site inside
37748 // [`AplicacaoSpec::validate_placement_shape`]. Guards any future
37749 // field-addition / reordering / string-conversion tweak on the
37750 // variant.
37751 let cluster = "rio";
37752 let lifted = AplicacaoError::placement_cluster_duplicate(cluster);
37753 let struct_literal = AplicacaoError::PlacementClusterDuplicate {
37754 cluster: cluster.to_string(),
37755 };
37756 assert_eq!(lifted, struct_literal);
37757 }
37758
37759 #[test]
37760 fn placement_cluster_duplicate_ctor_routes_cluster_through_to_string() {
37761 // Routing pin: sweep the sole constructor input axis
37762 // (`cluster: &str`) through a non-default fixture name so any
37763 // wrapper-side lowercase / trim / truncate / re-order on the
37764 // `cluster.to_string()` sole-field construction surfaces here
37765 // rather than at a downstream diagnostic-shape mismatch. Peer of
37766 // the sibling
37767 // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
37768 // (d9f6867) cross-axis pin on the sibling one-slot
37769 // `{ caixa: String }` envelope — extended here onto the sibling
37770 // `{ cluster: String }` envelope so the sole `String`-slot
37771 // construction routes the caller's `&str` through `.to_string()`
37772 // verbatim.
37773 let cluster = "sao-paulo-2";
37774 let built = AplicacaoError::placement_cluster_duplicate(cluster);
37775 match built {
37776 AplicacaoError::PlacementClusterDuplicate { cluster: c } => {
37777 assert_eq!(
37778 c, cluster,
37779 "cluster slot must thread the caller's `&str` verbatim through .to_string()"
37780 );
37781 }
37782 other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
37783 }
37784 }
37785
37786 // Per-variant equivalence + routing pins for the
37787 // [`AplicacaoError::placement_without_clusters`] standalone ctor
37788 // (see the paired doc-block above the ctor definition) — the
37789 // generated `pub const fn placement_without_clusters(placement:
37790 // &Placement) -> Self` inherent constructor folds the uniform
37791 // `Self::PlacementWithoutClusters { estrategia: placement.estrategia()
37792 // }` one-field `Copy`-pass-through struct-literal onto one substrate
37793 // primitive. Same shape as the sibling
37794 // `placement_cluster_duplicate_ctor_matches_struct_literal_wrap`
37795 // (92b1c92) / `contrato_self_loop_ctor_matches_struct_literal_wrap`
37796 // (b30edfe) equivalence pins on the paired standalone `AplicacaoError`
37797 // ctors — extended here onto the one-slot per-`:placement`
37798 // empty-clusters envelope.
37799
37800 #[test]
37801 fn placement_without_clusters_ctor_matches_struct_literal_wrap() {
37802 // Equivalence pin: the ctor produces byte-equal
37803 // `AplicacaoError::PlacementWithoutClusters` to the pre-lift
37804 // open-coded struct-literal that read the same field through
37805 // `p.estrategia()` at the caller site inside
37806 // [`AplicacaoSpec::validate_placement`]. Guards any future
37807 // field-addition / reordering / accessor-return tweak on the
37808 // variant.
37809 let placement = Placement {
37810 estrategia: PlacementStrategy::Replicated,
37811 clusters: vec![],
37812 affinity: None,
37813 shard_key: None,
37814 };
37815 let lifted = AplicacaoError::placement_without_clusters(&placement);
37816 let struct_literal = AplicacaoError::PlacementWithoutClusters {
37817 estrategia: placement.estrategia(),
37818 };
37819 assert_eq!(lifted, struct_literal);
37820 }
37821
37822 #[test]
37823 fn placement_without_clusters_ctor_routes_estrategia_through_accessor() {
37824 // Routing pin: sweep the sole constructor input axis
37825 // (`placement: &Placement`) through every variant in the closed
37826 // [`PlacementStrategy::ALL`] accept-set so any wrapper-side
37827 // re-derivation / off-by-one arm-swap / stale-field read on the
37828 // `placement.estrategia()` sole-field projection surfaces here
37829 // rather than at a downstream diagnostic-shape mismatch. Peer of
37830 // the sibling
37831 // `validate_placement_reads_through_lifted_estrategia_accessor`
37832 // three-consumer coherence pin — extended here onto the ctor
37833 // itself so the accessor-projection posture is byte-witnessed at
37834 // the substrate primitive rather than only at the caller-site
37835 // fan-out. Sweeps all three [`PlacementStrategy`] variants so any
37836 // future addition to the closed accept-set surfaces as an
37837 // exhaustiveness gap on this iteration list.
37838 for estrategia in [
37839 PlacementStrategy::SingleNode,
37840 PlacementStrategy::Replicated,
37841 PlacementStrategy::Sharded,
37842 ] {
37843 let placement = Placement {
37844 estrategia,
37845 clusters: vec![],
37846 affinity: None,
37847 shard_key: None,
37848 };
37849 let built = AplicacaoError::placement_without_clusters(&placement);
37850 match built {
37851 AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
37852 assert_eq!(
37853 e,
37854 placement.estrategia(),
37855 "estrategia slot must thread the caller's `Placement` verbatim \
37856 through Placement::estrategia() — the ctor reads through the \
37857 lifted accessor",
37858 );
37859 assert_eq!(
37860 e, estrategia,
37861 "estrategia slot must byte-equal the fixture-declared variant",
37862 );
37863 }
37864 other => panic!("expected PlacementWithoutClusters, got {other:?}"),
37865 }
37866 }
37867 }
37868
37869 #[test]
37870 fn placement_without_clusters_ctor_is_const_fn() {
37871 // Fail-before-pass-after pin on
37872 // [`AplicacaoError::placement_without_clusters`]'s `const`-eval-
37873 // surface posture. The ctor threads the paired
37874 // [`Placement::estrategia`] `const fn` `Copy`-scalar accessor's
37875 // return through one `const fn` construction — any future
37876 // accidental downgrade to non-`const` (a `.clone()` on the
37877 // `Copy`-scalar `estrategia:` field expression, an owned-`String`
37878 // materialization on the sibling non-`estrategia:` axis) fails
37879 // `placement_without_clusters_via_const_fn` at caixa-core build
37880 // time with E0015 (`cannot call non-const method`), strictly
37881 // stronger than a runtime `assert!`. Sibling of the peer
37882 // [`aplicacao_policy_scalar_ctors!`] (7ef425e) family's `const fn`
37883 // posture on the sibling per-`:politicas` cap-scalar envelopes
37884 // and the peer [`Placement::estrategia`] const-fn accessor pin at
37885 // [`placement_estrategia_accessor_is_const_fn`] on the paired
37886 // substrate primitive.
37887 const fn placement_without_clusters_via_const_fn(p: &Placement) -> AplicacaoError {
37888 AplicacaoError::placement_without_clusters(p)
37889 }
37890 let placement = Placement {
37891 estrategia: PlacementStrategy::Sharded,
37892 clusters: vec![],
37893 affinity: None,
37894 shard_key: Some("tenantId".into()),
37895 };
37896 assert_eq!(
37897 placement_without_clusters_via_const_fn(&placement),
37898 AplicacaoError::placement_without_clusters(&placement),
37899 );
37900 }
37901
37902 #[test]
37903 fn entrada_member_missing_ctor_matches_struct_literal_wrap() {
37904 // Equivalence pin: the ctor produces byte-equal
37905 // `AplicacaoError::EntradaMemberMissing` to the pre-lift
37906 // open-coded struct-literal that read the same `:para` value
37907 // through `e.destination().to_string()` at the caller site
37908 // inside [`AplicacaoSpec::validate_entrada`]. Guards any future
37909 // field-addition / reordering / accessor-return tweak on the
37910 // variant. Sibling of the peer
37911 // `placement_without_clusters_ctor_matches_struct_literal_wrap`
37912 // and `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
37913 // pins on the sibling per-`:placement` envelope, and sibling of
37914 // the peer `contrato_member_missing_ctor_matches_struct_literal_wrap`
37915 // pin on the sibling per-`:membros :caixa` envelope.
37916 let entrada = Entrada {
37917 host: "checkout.quero.cloud".into(),
37918 para: "phantom-shim".into(),
37919 paths: vec!["/api".into()],
37920 port: 8080,
37921 };
37922 let via_ctor = AplicacaoError::entrada_member_missing(&entrada);
37923 let via_literal = AplicacaoError::EntradaMemberMissing {
37924 para: entrada.destination().to_string(),
37925 };
37926 assert_eq!(
37927 via_ctor, via_literal,
37928 "entrada_member_missing(&entrada) must byte-equal the open-coded \
37929 EntradaMemberMissing struct-literal on the same &Entrada fixture"
37930 );
37931 assert_eq!(
37932 via_ctor.to_string(),
37933 via_literal.to_string(),
37934 "Display byte-string must byte-equal the open-coded struct-literal"
37935 );
37936 }
37937
37938 #[test]
37939 fn entrada_member_missing_ctor_routes_para_through_entrada_accessor() {
37940 // Boundary-sweep pin on the ctor's substrate-primitive
37941 // projection: the `para` slot is stored verbatim from
37942 // [`Entrada::destination`] across a representative set of
37943 // `:entrada :para` byte-strings, so any wrapper-side silent
37944 // normalization, `.into()` divergence, accidental field
37945 // rebrand, or per-arm ctor divergence on the sole-field
37946 // projection surfaces at caixa-core build time rather than at
37947 // a downstream diagnostic consumer that reads `err.para` back
37948 // and gets a different value than the one it stored. Peer of
37949 // the sibling
37950 // `shard_key_on_non_sharded_routes_estrategia_through_placement_accessor`
37951 // boundary-sweep pin on the sibling per-`:placement :shard-key`
37952 // envelope and the peer `placement_without_clusters_ctor_routes_estrategia_through_accessor`
37953 // sweep on the sibling per-`:placement` empty-clusters envelope
37954 // — extended here onto the [`Entrada`]-borrow-projected sole
37955 // `para` slot on the sibling per-`:entrada :para` envelope. The
37956 // sweep list carries a mixed set (well-shaped phantom, hyphen-
37957 // digit tail, single-character floor, and the digit-start form
37958 // the peer `accepts_canonical_entrada_para_forms` positive-
37959 // control test also sweeps) so a future silent per-input
37960 // normalization surfaces on the arm that diverges.
37961 for para in [
37962 "phantom-shim",
37963 "cart-v2",
37964 "a",
37965 "c0",
37966 "3rd-party-shim",
37967 "x-1-2-3-4",
37968 ] {
37969 let entrada = Entrada {
37970 host: "checkout.quero.cloud".into(),
37971 para: para.into(),
37972 paths: vec!["/api".into()],
37973 port: 8080,
37974 };
37975 let err = AplicacaoError::entrada_member_missing(&entrada);
37976 let AplicacaoError::EntradaMemberMissing { para: stored_para } = err else {
37977 panic!("entrada_member_missing must construct EntradaMemberMissing for {para:?}");
37978 };
37979 assert_eq!(
37980 stored_para,
37981 entrada.destination(),
37982 "para slot must round-trip verbatim through Entrada::destination() \
37983 for {para:?}"
37984 );
37985 assert_eq!(
37986 stored_para, para,
37987 "para slot must byte-equal the fixture-declared value for {para:?}"
37988 );
37989 }
37990 }
37991
37992 #[test]
37993 fn validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor() {
37994 // End-to-end pin: the sole in-crate wire-up site
37995 // (`AplicacaoSpec::validate_entrada`'s membership-lookup arm)
37996 // routes through [`AplicacaoError::entrada_member_missing`] and
37997 // the observed `Err` byte-equals the ctor's output on the same
37998 // well-shaped-phantom `:para` fixture. A future silent de-lift
37999 // of the wire-up back to the open-coded struct-literal trips
38000 // this test at caixa-core build time rather than at a
38001 // downstream diagnostic consumer far from the wire-up commit.
38002 // Sibling of the peer
38003 // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
38004 // end-to-end pin on the sibling per-`:placement :shard-key`
38005 // envelope, and sibling of the peer
38006 // `entrada_para_well_shaped_phantom_still_raises_member_missing`
38007 // pattern-match pin on the same wire-up — extended here from a
38008 // `matches!` shape check to a byte-identity + Display parity
38009 // route through the ctor.
38010 let mut s = three_member_spec();
38011 s.entrada.as_mut().unwrap().para = "phantom-shim".into();
38012 let observed = s.validate().unwrap_err();
38013 let expected = AplicacaoError::entrada_member_missing(s.entrada.as_ref().unwrap());
38014 assert_eq!(
38015 observed, expected,
38016 "validate_entrada's phantom-reference-arm Err must byte-equal \
38017 entrada_member_missing(&entrada)"
38018 );
38019 assert_eq!(
38020 observed.to_string(),
38021 expected.to_string(),
38022 "Display byte-string parity"
38023 );
38024 }
38025
38026 #[test]
38027 fn contrato_cycle_ctor_matches_struct_literal_wrap() {
38028 // Equivalence pin: the ctor produces byte-equal
38029 // `AplicacaoError::ContratoCycle` to the pre-lift open-coded
38030 // struct-literal that stored the caller-side reconstructed
38031 // cycle path verbatim at the gray-arm cycle-close return inside
38032 // [`AplicacaoSpec::detect_sync_cycles`]. Guards any future
38033 // field-addition / reordering / re-collect divergence on the
38034 // variant. Sibling of the peer
38035 // `entrada_member_missing_ctor_matches_struct_literal_wrap`
38036 // (deeae5c) pin on the sibling per-`:entrada :para`
38037 // phantom-reference envelope, and sibling of the peer
38038 // `placement_without_clusters_ctor_matches_struct_literal_wrap`
38039 // pin on the sibling per-`:placement` empty-clusters envelope.
38040 let cycle = vec![
38041 "cart".to_string(),
38042 "catalog".to_string(),
38043 "cart".to_string(),
38044 ];
38045 let via_ctor = AplicacaoError::contrato_cycle(cycle.clone());
38046 let via_literal = AplicacaoError::ContratoCycle {
38047 cycle: cycle.clone(),
38048 };
38049 assert_eq!(
38050 via_ctor, via_literal,
38051 "contrato_cycle(cycle) must byte-equal the open-coded \
38052 ContratoCycle struct-literal on the same Vec<String> fixture"
38053 );
38054 assert_eq!(
38055 via_ctor.to_string(),
38056 via_literal.to_string(),
38057 "Display byte-string must byte-equal the open-coded struct-literal"
38058 );
38059 }
38060
38061 #[test]
38062 fn contrato_cycle_ctor_routes_path_verbatim() {
38063 // Boundary-sweep pin on the ctor's substrate-primitive
38064 // pass-through: the `cycle` slot is stored verbatim across a
38065 // representative set of reconstructed cycle paths (two-node
38066 // closed loop; three-node loop; long chain with repeated
38067 // interior nodes; a fixture whose first/last coincide by the
38068 // gray-arm's own append-target-once-more discipline), so any
38069 // wrapper-side silent normalization, dedup, sort, `.into()`
38070 // divergence, accidental field rebrand, or re-collect on the
38071 // sole-field pass-through surfaces at caixa-core build time
38072 // rather than at a downstream diagnostic consumer that reads
38073 // `err.cycle` back and gets a different value than the one it
38074 // stored. Peer of the sibling
38075 // `entrada_member_missing_ctor_routes_para_through_entrada_accessor`
38076 // (deeae5c) boundary-sweep pin on the sibling per-`:entrada
38077 // :para` envelope — extended here onto the owned-[`Vec<String>`]
38078 // pass-through on the sibling per-`:contratos` cycle envelope.
38079 for cycle in [
38080 vec![
38081 "cart".to_string(),
38082 "catalog".to_string(),
38083 "cart".to_string(),
38084 ],
38085 vec![
38086 "cart".to_string(),
38087 "catalog".to_string(),
38088 "payment".to_string(),
38089 "cart".to_string(),
38090 ],
38091 vec![
38092 "a".to_string(),
38093 "b".to_string(),
38094 "c".to_string(),
38095 "d".to_string(),
38096 "b".to_string(),
38097 ],
38098 vec!["only".to_string(), "only".to_string()],
38099 ] {
38100 let err = AplicacaoError::contrato_cycle(cycle.clone());
38101 let AplicacaoError::ContratoCycle { cycle: stored } = err else {
38102 panic!("contrato_cycle must construct ContratoCycle for {cycle:?}");
38103 };
38104 assert_eq!(
38105 stored, cycle,
38106 "cycle slot must round-trip the caller-side Vec<String> verbatim \
38107 for {cycle:?}"
38108 );
38109 }
38110 }
38111
38112 #[test]
38113 fn detect_sync_cycles_arm_routes_through_contrato_cycle_ctor() {
38114 // End-to-end pin: the sole in-crate wire-up site
38115 // (`AplicacaoSpec::detect_sync_cycles`'s gray-arm cycle-close
38116 // return) routes through [`AplicacaoError::contrato_cycle`] and
38117 // the observed `Err` byte-equals the ctor's output on the same
38118 // reconstructed cycle path. A future silent de-lift of the
38119 // wire-up back to the open-coded `AplicacaoError::ContratoCycle
38120 // { cycle }` struct-literal trips this test at caixa-core build
38121 // time rather than at a downstream diagnostic consumer far from
38122 // the wire-up commit. Sibling of the peer
38123 // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
38124 // (deeae5c) end-to-end pin on the sibling per-`:entrada :para`
38125 // envelope, and sibling of the peer
38126 // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
38127 // (14bafca) end-to-end pin on the sibling per-`:placement
38128 // :shard-key` envelope — extended here from a bare
38129 // `matches!(err, AplicacaoError::ContratoCycle { .. })` shape
38130 // check to a byte-identity route through the ctor.
38131 let mut s = three_member_spec();
38132 // Reset to a clean 3-cycle: catalog → cart → payment → catalog
38133 s.contratos = vec![
38134 contract_http("catalog", "cart", "/x"),
38135 contract_http("cart", "payment", "/y"),
38136 contract_http("payment", "catalog", "/z"),
38137 ];
38138 let observed = s.validate().unwrap_err();
38139 let AplicacaoError::ContratoCycle { ref cycle } = observed else {
38140 panic!("expected ContratoCycle from the sync-cycle detector, got {observed:?}");
38141 };
38142 let expected = AplicacaoError::contrato_cycle(cycle.clone());
38143 assert_eq!(
38144 observed, expected,
38145 "detect_sync_cycles's gray-arm Err must byte-equal \
38146 contrato_cycle(cycle) on the reconstructed cycle path"
38147 );
38148 assert_eq!(
38149 observed.to_string(),
38150 expected.to_string(),
38151 "Display byte-string parity"
38152 );
38153 }
38154
38155 // ── policy_breaker_window_below_timeout standalone ctor pins ────────
38156 //
38157 // Fail-before-pass-after pins for the standalone
38158 // [`AplicacaoError::policy_breaker_window_below_timeout`] inherent
38159 // ctor (see the paired doc-block above the ctor definition) — the
38160 // fold of the last open-coded two-slot `{ window: cb.window(),
38161 // timeout: t }` struct-literal inside
38162 // [`MeshPolicy::first_cross_axis_violation`]'s window-below-timeout
38163 // arm onto one substrate primitive on the [`AplicacaoError`]
38164 // envelope, projecting through the [`CircuitBreaker::window`] scalar
38165 // accessor on the substrate primitive. A byte-mismatched ctor body
38166 // would trip the equivalence pin first, ahead of any downstream
38167 // diagnostic-shape drift.
38168 //
38169 // Peer of the sibling standalone-ctor equivalence pins on the peer
38170 // per-envelope substrate-primitive-projection ctors across
38171 // caixa-core: `contrato_self_loop_ctor_matches_struct_literal_wrap`
38172 // (b30edfe) on the sibling `{ caixa: String, wit: String }` two-slot
38173 // per-`:contratos` self-edge envelope,
38174 // `entrada_member_missing_ctor_matches_struct_literal_wrap` (deeae5c)
38175 // on the sibling `{ para: String }` one-slot per-`:entrada :para`
38176 // phantom-reference envelope, and
38177 // `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
38178 // (14bafca) on the sibling `{ estrategia, shard_key }` two-slot
38179 // per-`:placement :shard-key` envelope.
38180
38181 #[test]
38182 fn policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap() {
38183 // Equivalence pin: the ctor produces byte-equal
38184 // `AplicacaoError::PolicyBreakerWindowBelowTimeout` to the pre-
38185 // lift open-coded struct-literal that read the same two fields
38186 // through [`CircuitBreaker::window`] and the paired
38187 // `:politicas :timeout` destructure. Guards any future
38188 // field-addition / reordering / accessor-swap tweak on the
38189 // variant. Same equivalence-pin shape as the sibling
38190 // `contrato_self_loop_ctor_matches_struct_literal_wrap`
38191 // (b30edfe) on the sibling per-`:contratos` self-edge envelope.
38192 let cb = CircuitBreaker {
38193 max_failures: 5,
38194 window: Duration::from_secs(10),
38195 };
38196 let timeout = Duration::from_secs(30);
38197 let via_ctor = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
38198 let via_literal = AplicacaoError::PolicyBreakerWindowBelowTimeout {
38199 window: cb.window(),
38200 timeout,
38201 };
38202 assert_eq!(
38203 via_ctor, via_literal,
38204 "policy_breaker_window_below_timeout(&cb, t) must byte-equal \
38205 the open-coded PolicyBreakerWindowBelowTimeout struct-literal \
38206 on the same Copy-Duration fixture"
38207 );
38208 assert_eq!(
38209 via_ctor.to_string(),
38210 via_literal.to_string(),
38211 "Display byte-string must byte-equal the open-coded struct-literal"
38212 );
38213 }
38214
38215 #[test]
38216 fn policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim() {
38217 // Routing pin sweeping non-default `:circuit-breaker :window`
38218 // and `:timeout` pairs (below-boundary window / above-boundary
38219 // window; sub-second window / multi-minute timeout;
38220 // millisecond-precision fixture) through the paired
38221 // [`CircuitBreaker::window`] accessor and the direct `timeout`
38222 // parameter, so any wrapper-side silent normalization,
38223 // rounding, argument re-order, or accidental slot rebrand on
38224 // the two-slot pass-through surfaces at caixa-core build time
38225 // rather than at a downstream diagnostic consumer that reads
38226 // the two [`Duration`]s back and gets different values than
38227 // the ones it stored.
38228 //
38229 // Deliberately routes through a fixture whose `cb.window` and
38230 // `timeout` are distinct — a silent accessor swap
38231 // (`cb.max_failures` casting to `Duration` would fail to
38232 // compile; a hypothetical field-rename swap swapping the two
38233 // slots at the ctor body would land `timeout` in the `window`
38234 // slot instead of `cb.window()` and vice-versa, tripping the
38235 // per-field assertion here). Peer of the sibling
38236 // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
38237 // (b30edfe) routing pin on the sibling two-slot per-`:contratos`
38238 // envelope.
38239 for (max_failures, window, timeout) in [
38240 (5_u32, Duration::from_secs(10), Duration::from_secs(30)),
38241 (
38242 1_u32,
38243 Duration::from_millis(29_999),
38244 Duration::from_secs(30),
38245 ),
38246 (42_u32, Duration::from_millis(500), Duration::from_secs(120)),
38247 (7_u32, Duration::from_secs(1), Duration::from_secs(60)),
38248 ] {
38249 let cb = CircuitBreaker {
38250 max_failures,
38251 window,
38252 };
38253 let built = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
38254 let AplicacaoError::PolicyBreakerWindowBelowTimeout {
38255 window: stored_window,
38256 timeout: stored_timeout,
38257 } = built
38258 else {
38259 panic!(
38260 "policy_breaker_window_below_timeout must construct \
38261 PolicyBreakerWindowBelowTimeout for cb={cb:?}/timeout={timeout:?}"
38262 );
38263 };
38264 assert_eq!(
38265 stored_window, window,
38266 "window slot must thread CircuitBreaker::window() verbatim \
38267 for cb={cb:?}/timeout={timeout:?}"
38268 );
38269 assert_eq!(
38270 stored_timeout, timeout,
38271 "timeout slot must thread the caller-side :timeout scalar verbatim \
38272 for cb={cb:?}/timeout={timeout:?}"
38273 );
38274 }
38275 }
38276
38277 #[test]
38278 fn first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor() {
38279 // End-to-end pin: the sole in-crate wire-up site
38280 // ([`MeshPolicy::first_cross_axis_violation`]'s
38281 // window-below-timeout arm) routes through
38282 // [`AplicacaoError::policy_breaker_window_below_timeout`] and
38283 // the observed `Err` byte-equals the ctor's output on the same
38284 // sub-boundary `(:window, :timeout)` fixture. A future silent
38285 // de-lift of the wire-up back to the open-coded
38286 // `AplicacaoError::PolicyBreakerWindowBelowTimeout { window,
38287 // timeout }` struct-literal trips this test at caixa-core build
38288 // time rather than at a downstream diagnostic consumer far from
38289 // the wire-up commit. Sibling of the peer
38290 // `detect_sync_cycles_arm_routes_through_contrato_cycle_ctor`
38291 // (5cfcab8) end-to-end pin on the sibling per-`:contratos`
38292 // cross-edge cycle envelope,
38293 // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
38294 // (deeae5c) on the sibling per-`:entrada :para` phantom-
38295 // reference envelope, and
38296 // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
38297 // (14bafca) on the sibling per-`:placement :shard-key`
38298 // envelope — extended here from a bare `matches!(err,
38299 // AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })`
38300 // shape check to a byte-identity route through the ctor.
38301 let mut s = three_member_spec();
38302 s.politicas.timeout = Some(Duration::from_secs(30));
38303 s.politicas.circuit_breaker = Some(CircuitBreaker {
38304 max_failures: 5,
38305 window: Duration::from_secs(10),
38306 });
38307 let observed = s.validate().unwrap_err();
38308 let cb = s.politicas.circuit_breaker.unwrap();
38309 let timeout = s.politicas.timeout.unwrap();
38310 let expected = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
38311 assert_eq!(
38312 observed, expected,
38313 "MeshPolicy::first_cross_axis_violation's window-below-timeout \
38314 arm's Err must byte-equal policy_breaker_window_below_timeout(&cb, t)"
38315 );
38316 assert_eq!(
38317 observed.to_string(),
38318 expected.to_string(),
38319 "Display byte-string parity"
38320 );
38321 }
38322
38323 #[test]
38324 fn policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap() {
38325 // Equivalence pin: the ctor produces byte-equal
38326 // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit` to the
38327 // pre-lift open-coded struct-literal that read the same four fields
38328 // through [`RateLimit::rate`], [`RateLimit::window`],
38329 // [`CircuitBreaker::max_failures`], and [`CircuitBreaker::window`].
38330 // Guards any future field-addition / reordering / accessor-swap
38331 // tweak on the variant. Same equivalence-pin shape as the sibling
38332 // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
38333 // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
38334 // cross-axis envelope.
38335 let rl = RateLimit {
38336 rate: 1,
38337 window: Duration::from_secs(3600),
38338 };
38339 let cb = CircuitBreaker {
38340 max_failures: 5,
38341 window: Duration::from_secs(10),
38342 };
38343 let via_ctor = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
38344 let via_literal = AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
38345 rate: rl.rate(),
38346 rl_window: rl.window(),
38347 max_failures: cb.max_failures(),
38348 cb_window: cb.window(),
38349 };
38350 assert_eq!(
38351 via_ctor, via_literal,
38352 "policy_breaker_cannot_trip_under_rate_limit(&rl, &cb) must \
38353 byte-equal the open-coded PolicyBreakerCannotTripUnderRateLimit \
38354 struct-literal on the same Copy-(u32|Duration) fixture"
38355 );
38356 assert_eq!(
38357 via_ctor.to_string(),
38358 via_literal.to_string(),
38359 "Display byte-string must byte-equal the open-coded struct-literal"
38360 );
38361 }
38362
38363 #[test]
38364 fn policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim() {
38365 // Routing pin sweeping non-default `(:rate, :rate-limit :window,
38366 // :max-failures, :circuit-breaker :window)` tuples across the
38367 // production-playbook starve band — Envoy 5-in-10s vs 1/hour,
38368 // sub-second breaker window, multi-minute rate-limit window,
38369 // multi-tenant per-cluster ratio — through the paired
38370 // [`RateLimit::rate`] / [`RateLimit::window`] /
38371 // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
38372 // accessors, so any wrapper-side silent normalization, rounding,
38373 // argument re-order, or accidental slot rebrand on the four-slot
38374 // pass-through surfaces at caixa-core build time rather than at a
38375 // downstream diagnostic consumer that reads the four scalars back
38376 // and gets different values than the ones it stored.
38377 //
38378 // Deliberately routes through fixtures whose four scalars are
38379 // pairwise distinct (`rate ≠ max_failures`, `rl_window ≠
38380 // cb_window`) — a hypothetical field-rename swap swapping any
38381 // two adjacent slots at the ctor body would land the value from
38382 // the wrong axis, tripping the per-field assertion here. Peer of
38383 // the sibling
38384 // `policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim`
38385 // (9b30c07) routing pin on the sibling two-slot per-`(:timeout,
38386 // :circuit-breaker)` cross-axis envelope.
38387 for (rate, rl_window, max_failures, cb_window) in [
38388 (
38389 1_u32,
38390 Duration::from_secs(3600),
38391 5_u32,
38392 Duration::from_secs(10),
38393 ),
38394 (4_u32, Duration::from_secs(1), 5_u32, Duration::from_secs(1)),
38395 (
38396 2_u32,
38397 Duration::from_millis(500),
38398 10_u32,
38399 Duration::from_secs(300),
38400 ),
38401 (
38402 7_u32,
38403 Duration::from_secs(120),
38404 42_u32,
38405 Duration::from_millis(750),
38406 ),
38407 ] {
38408 let rl = RateLimit {
38409 rate,
38410 window: rl_window,
38411 };
38412 let cb = CircuitBreaker {
38413 max_failures,
38414 window: cb_window,
38415 };
38416 let built = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
38417 let AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
38418 rate: stored_rate,
38419 rl_window: stored_rl_window,
38420 max_failures: stored_max_failures,
38421 cb_window: stored_cb_window,
38422 } = built
38423 else {
38424 panic!(
38425 "policy_breaker_cannot_trip_under_rate_limit must \
38426 construct PolicyBreakerCannotTripUnderRateLimit for \
38427 rl={rl:?}/cb={cb:?}"
38428 );
38429 };
38430 assert_eq!(
38431 stored_rate, rate,
38432 "rate slot must thread RateLimit::rate() verbatim for \
38433 rl={rl:?}/cb={cb:?}"
38434 );
38435 assert_eq!(
38436 stored_rl_window, rl_window,
38437 "rl_window slot must thread RateLimit::window() verbatim \
38438 for rl={rl:?}/cb={cb:?}"
38439 );
38440 assert_eq!(
38441 stored_max_failures, max_failures,
38442 "max_failures slot must thread CircuitBreaker::max_failures() \
38443 verbatim for rl={rl:?}/cb={cb:?}"
38444 );
38445 assert_eq!(
38446 stored_cb_window, cb_window,
38447 "cb_window slot must thread CircuitBreaker::window() verbatim \
38448 for rl={rl:?}/cb={cb:?}"
38449 );
38450 }
38451 }
38452
38453 #[test]
38454 fn first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor()
38455 {
38456 // End-to-end pin: the sole in-crate wire-up site
38457 // ([`MeshPolicy::first_cross_axis_violation`]'s
38458 // starve-under-rate-limit arm) routes through
38459 // [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
38460 // and the observed `Err` byte-equals the ctor's output on the same
38461 // token-bucket-starves-breaker fixture. A future silent de-lift of
38462 // the wire-up back to the open-coded
38463 // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { rate,
38464 // rl_window, max_failures, cb_window }` struct-literal trips this
38465 // test at caixa-core build time rather than at a downstream
38466 // diagnostic consumer far from the wire-up commit. Sibling of the
38467 // peer
38468 // `first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor`
38469 // (9b30c07) end-to-end pin on the sibling per-`(:timeout,
38470 // :circuit-breaker)` cross-axis envelope — extended here from a
38471 // bare `matches!(err,
38472 // AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })`
38473 // shape check to a byte-identity route through the ctor. Clears
38474 // `:timeout` so the sibling window-below-timeout arm does not
38475 // fire first on the ordering-precedent it holds over this arm.
38476 let mut s = three_member_spec();
38477 s.politicas.timeout = None;
38478 s.politicas.circuit_breaker = Some(CircuitBreaker {
38479 max_failures: 5,
38480 window: Duration::from_secs(10),
38481 });
38482 s.politicas.rate_limit = Some(RateLimit {
38483 rate: 1,
38484 window: Duration::from_secs(3600),
38485 });
38486 let observed = s.validate().unwrap_err();
38487 let rl = s.politicas.rate_limit.unwrap();
38488 let cb = s.politicas.circuit_breaker.unwrap();
38489 let expected = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
38490 assert_eq!(
38491 observed, expected,
38492 "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit \
38493 arm's Err must byte-equal \
38494 policy_breaker_cannot_trip_under_rate_limit(&rl, &cb)"
38495 );
38496 assert_eq!(
38497 observed.to_string(),
38498 expected.to_string(),
38499 "Display byte-string parity"
38500 );
38501 }
38502
38503 #[test]
38504 fn policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap() {
38505 // Equivalence pin: the ctor produces byte-equal
38506 // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted` to the
38507 // pre-lift open-coded struct-literal that read the same two fields
38508 // through the bare `retries` destructure and
38509 // [`CircuitBreaker::max_failures`]. Guards any future field-addition
38510 // / reordering / accessor-swap tweak on the variant. Same
38511 // equivalence-pin shape as the sibling
38512 // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
38513 // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
38514 // second cross-axis envelope and
38515 // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
38516 // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)` first
38517 // cross-axis envelope.
38518 let retries = 5_u32;
38519 let cb = CircuitBreaker {
38520 max_failures: 3,
38521 window: Duration::from_secs(60),
38522 };
38523 let via_ctor = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
38524 let via_literal = AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
38525 retries,
38526 max_failures: cb.max_failures(),
38527 };
38528 assert_eq!(
38529 via_ctor, via_literal,
38530 "policy_breaker_trips_before_retries_exhausted(retries, &cb) must \
38531 byte-equal the open-coded PolicyBreakerTripsBeforeRetriesExhausted \
38532 struct-literal on the same Copy-u32 fixture"
38533 );
38534 assert_eq!(
38535 via_ctor.to_string(),
38536 via_literal.to_string(),
38537 "Display byte-string must byte-equal the open-coded struct-literal"
38538 );
38539 }
38540
38541 #[test]
38542 fn policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim() {
38543 // Routing pin sweeping non-default `(retries, max_failures)` tuples
38544 // across the production-playbook retries-saturate band — Envoy 5
38545 // retries vs 3 max-failures, boundary retries==max_failures pair (a
38546 // rejecting arm on the strict-inequality invariant), multi-tenant
38547 // high-retries-vs-low-trip ratio, sub-cap high-max-failures ceiling —
38548 // through the paired bare-`retries` destructure and
38549 // [`CircuitBreaker::max_failures`] accessor, so any wrapper-side
38550 // silent normalization, rounding, argument re-order, or accidental
38551 // slot rebrand on the two-slot pass-through surfaces at caixa-core
38552 // build time rather than at a downstream diagnostic consumer that
38553 // reads the two scalars back and gets different values than the ones
38554 // it stored.
38555 //
38556 // Deliberately routes through fixtures whose two scalars are
38557 // pairwise distinct (`retries ≠ max_failures` on every non-boundary
38558 // arm) — a hypothetical field-rename swap swapping the two slots at
38559 // the ctor body would land the value from the wrong axis, tripping
38560 // the per-field assertion here. Peer of the sibling
38561 // `policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim`
38562 // (6bb4e46) routing pin on the sibling four-slot per-`(:rate-limit,
38563 // :circuit-breaker)` second cross-axis envelope.
38564 for (retries, max_failures) in [
38565 (5_u32, 3_u32),
38566 (3_u32, 3_u32),
38567 (100_u32, 1_u32),
38568 (7_u32, 42_u32),
38569 ] {
38570 let cb = CircuitBreaker {
38571 max_failures,
38572 window: Duration::from_secs(60),
38573 };
38574 let built = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
38575 let AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
38576 retries: stored_retries,
38577 max_failures: stored_max_failures,
38578 } = built
38579 else {
38580 panic!(
38581 "policy_breaker_trips_before_retries_exhausted must \
38582 construct PolicyBreakerTripsBeforeRetriesExhausted for \
38583 retries={retries}/cb={cb:?}"
38584 );
38585 };
38586 assert_eq!(
38587 stored_retries, retries,
38588 "retries slot must thread the bare-`retries` destructure \
38589 verbatim for retries={retries}/cb={cb:?}"
38590 );
38591 assert_eq!(
38592 stored_max_failures, max_failures,
38593 "max_failures slot must thread CircuitBreaker::max_failures() \
38594 verbatim for retries={retries}/cb={cb:?}"
38595 );
38596 }
38597 }
38598
38599 #[test]
38600 fn first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor()
38601 {
38602 // End-to-end pin: the sole in-crate wire-up site
38603 // ([`MeshPolicy::first_cross_axis_violation`]'s retries-saturate
38604 // arm) routes through
38605 // [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
38606 // and the observed `Err` byte-equals the ctor's output on the same
38607 // retries-saturate fixture. A future silent de-lift of the wire-up
38608 // back to the open-coded
38609 // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { retries,
38610 // max_failures }` struct-literal trips this test at caixa-core build
38611 // time rather than at a downstream diagnostic consumer far from the
38612 // wire-up commit. Sibling of the peer
38613 // `first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor`
38614 // (6bb4e46) end-to-end pin on the sibling per-`(:rate-limit,
38615 // :circuit-breaker)` second cross-axis envelope — extended here from
38616 // a bare `matches!(err,
38617 // AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })`
38618 // shape check to a byte-identity route through the ctor. Clears
38619 // `:timeout` and `:rate-limit` so the sibling window-below-timeout
38620 // and starve-under-rate-limit arms do not fire first on the
38621 // ordering-precedent they hold over this arm.
38622 let mut s = three_member_spec();
38623 s.politicas.timeout = None;
38624 s.politicas.rate_limit = None;
38625 s.politicas.retries = Some(5);
38626 s.politicas.circuit_breaker = Some(CircuitBreaker {
38627 max_failures: 3,
38628 window: Duration::from_secs(60),
38629 });
38630 let observed = s.validate().unwrap_err();
38631 let retries = s.politicas.retries.unwrap();
38632 let cb = s.politicas.circuit_breaker.unwrap();
38633 let expected = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
38634 assert_eq!(
38635 observed, expected,
38636 "MeshPolicy::first_cross_axis_violation's retries-saturate arm's \
38637 Err must byte-equal \
38638 policy_breaker_trips_before_retries_exhausted(retries, &cb)"
38639 );
38640 assert_eq!(
38641 observed.to_string(),
38642 expected.to_string(),
38643 "Display byte-string parity"
38644 );
38645 }
38646
38647 #[test]
38648 fn policy_rate_limit_cannot_admit_retry_burst_ctor_matches_struct_literal_wrap() {
38649 // Equivalence pin: the ctor produces byte-equal
38650 // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst` to the
38651 // pre-lift open-coded struct-literal that read the same two fields
38652 // through the bare `retries` destructure and [`RateLimit::rate`].
38653 // Guards any future field-addition / reordering / accessor-swap
38654 // tweak on the variant. Same equivalence-pin shape as the sibling
38655 // `policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap`
38656 // (f54c539) on the sibling per-`(:retries, :circuit-breaker)`
38657 // third cross-axis envelope,
38658 // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
38659 // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
38660 // second cross-axis envelope, and
38661 // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
38662 // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
38663 // first cross-axis envelope.
38664 let retries = 3_u32;
38665 let rl = RateLimit {
38666 rate: 3,
38667 window: Duration::from_secs(1),
38668 };
38669 let via_ctor = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
38670 let via_literal = AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
38671 retries,
38672 rate: rl.rate(),
38673 };
38674 assert_eq!(
38675 via_ctor, via_literal,
38676 "policy_rate_limit_cannot_admit_retry_burst(retries, &rl) must \
38677 byte-equal the open-coded PolicyRateLimitCannotAdmitRetryBurst \
38678 struct-literal on the same Copy-u32 fixture"
38679 );
38680 assert_eq!(
38681 via_ctor.to_string(),
38682 via_literal.to_string(),
38683 "Display byte-string must byte-equal the open-coded struct-literal"
38684 );
38685 }
38686
38687 #[test]
38688 fn policy_rate_limit_cannot_admit_retry_burst_ctor_routes_retries_and_rl_verbatim() {
38689 // Routing pin sweeping non-default `(retries, rate)` tuples across
38690 // the production-playbook rate-limit-starve band — boundary
38691 // `retries==rate` (a rejecting arm on the `>=` invariant stated as
38692 // `rate >= retries + 1`), one-below-boundary pair, multi-tenant
38693 // high-retries-vs-low-rate ratio, and sub-cap high-rate ceiling —
38694 // through the paired bare-`retries` destructure and
38695 // [`RateLimit::rate`] accessor, so any wrapper-side silent
38696 // normalization, rounding, argument re-order, or accidental slot
38697 // rebrand on the two-slot pass-through surfaces at caixa-core
38698 // build time rather than at a downstream diagnostic consumer that
38699 // reads the two scalars back and gets different values than the
38700 // ones it stored.
38701 //
38702 // Deliberately routes through fixtures whose two scalars are
38703 // pairwise distinct on every non-boundary arm — a hypothetical
38704 // field-rename swap swapping the two slots at the ctor body would
38705 // land the value from the wrong axis, tripping the per-field
38706 // assertion here. Peer of the sibling
38707 // `policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim`
38708 // (f54c539) routing pin on the sibling two-slot per-`(:retries,
38709 // :circuit-breaker)` third cross-axis envelope.
38710 for (retries, rate) in [
38711 (3_u32, 3_u32),
38712 (5_u32, 4_u32),
38713 (100_u32, 50_u32),
38714 (2_u32, POLICY_RATE_LIMIT_MAX),
38715 ] {
38716 let rl = RateLimit {
38717 rate,
38718 window: Duration::from_secs(1),
38719 };
38720 let built = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
38721 let AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
38722 retries: stored_retries,
38723 rate: stored_rate,
38724 } = built
38725 else {
38726 panic!(
38727 "policy_rate_limit_cannot_admit_retry_burst must \
38728 construct PolicyRateLimitCannotAdmitRetryBurst for \
38729 retries={retries}/rl={rl:?}"
38730 );
38731 };
38732 assert_eq!(
38733 stored_retries, retries,
38734 "retries slot must thread the bare-`retries` destructure \
38735 verbatim for retries={retries}/rl={rl:?}"
38736 );
38737 assert_eq!(
38738 stored_rate, rate,
38739 "rate slot must thread RateLimit::rate() verbatim for \
38740 retries={retries}/rl={rl:?}"
38741 );
38742 }
38743 }
38744
38745 #[test]
38746 fn first_cross_axis_violation_arm_routes_through_policy_rate_limit_cannot_admit_retry_burst_ctor()
38747 {
38748 // End-to-end pin: the sole in-crate wire-up site
38749 // ([`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
38750 // limit arm) routes through
38751 // [`AplicacaoError::policy_rate_limit_cannot_admit_retry_burst`]
38752 // and the observed `Err` byte-equals the ctor's output on the same
38753 // rate-limit-starve fixture. A future silent de-lift of the
38754 // wire-up back to the open-coded
38755 // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { retries,
38756 // rate }` struct-literal trips this test at caixa-core build time
38757 // rather than at a downstream diagnostic consumer far from the
38758 // wire-up commit. Sibling of the peer
38759 // `first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor`
38760 // (f54c539) end-to-end pin on the sibling per-`(:retries,
38761 // :circuit-breaker)` third cross-axis envelope. Clears `:timeout`
38762 // and `:circuit-breaker` so the sibling window-below-timeout /
38763 // starve-under-rate-limit / trips-before-retries-exhausted arms
38764 // do not fire first on the ordering-precedent they hold over this
38765 // arm.
38766 let mut s = three_member_spec();
38767 s.politicas.timeout = None;
38768 s.politicas.circuit_breaker = None;
38769 s.politicas.retries = Some(5);
38770 s.politicas.rate_limit = Some(RateLimit {
38771 rate: 3,
38772 window: Duration::from_secs(1),
38773 });
38774 let observed = s.validate().unwrap_err();
38775 let retries = s.politicas.retries.unwrap();
38776 let rl = s.politicas.rate_limit.unwrap();
38777 let expected = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
38778 assert_eq!(
38779 observed, expected,
38780 "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit arm's \
38781 Err must byte-equal \
38782 policy_rate_limit_cannot_admit_retry_burst(retries, &rl)"
38783 );
38784 assert_eq!(
38785 observed.to_string(),
38786 expected.to_string(),
38787 "Display byte-string parity"
38788 );
38789 }
38790}